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 /// 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 "SIISelLowering.h" 21 #include "AMDGPU.h" 22 #include "AMDGPUIntrinsicInfo.h" 23 #include "AMDGPUSubtarget.h" 24 #include "AMDGPUTargetMachine.h" 25 #include "SIDefines.h" 26 #include "SIInstrInfo.h" 27 #include "SIMachineFunctionInfo.h" 28 #include "SIRegisterInfo.h" 29 #include "Utils/AMDGPUBaseInfo.h" 30 #include "llvm/ADT/APFloat.h" 31 #include "llvm/ADT/APInt.h" 32 #include "llvm/ADT/ArrayRef.h" 33 #include "llvm/ADT/BitVector.h" 34 #include "llvm/ADT/SmallVector.h" 35 #include "llvm/ADT/Statistic.h" 36 #include "llvm/ADT/StringRef.h" 37 #include "llvm/ADT/StringSwitch.h" 38 #include "llvm/ADT/Twine.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineMemOperand.h" 49 #include "llvm/CodeGen/MachineModuleInfo.h" 50 #include "llvm/CodeGen/MachineOperand.h" 51 #include "llvm/CodeGen/MachineRegisterInfo.h" 52 #include "llvm/CodeGen/SelectionDAG.h" 53 #include "llvm/CodeGen/SelectionDAGNodes.h" 54 #include "llvm/CodeGen/TargetCallingConv.h" 55 #include "llvm/CodeGen/TargetRegisterInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/Constants.h" 58 #include "llvm/IR/DataLayout.h" 59 #include "llvm/IR/DebugLoc.h" 60 #include "llvm/IR/DerivedTypes.h" 61 #include "llvm/IR/DiagnosticInfo.h" 62 #include "llvm/IR/Function.h" 63 #include "llvm/IR/GlobalValue.h" 64 #include "llvm/IR/InstrTypes.h" 65 #include "llvm/IR/Instruction.h" 66 #include "llvm/IR/Instructions.h" 67 #include "llvm/IR/IntrinsicInst.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/Support/Casting.h" 70 #include "llvm/Support/CodeGen.h" 71 #include "llvm/Support/CommandLine.h" 72 #include "llvm/Support/Compiler.h" 73 #include "llvm/Support/ErrorHandling.h" 74 #include "llvm/Support/KnownBits.h" 75 #include "llvm/Support/MachineValueType.h" 76 #include "llvm/Support/MathExtras.h" 77 #include "llvm/Target/TargetOptions.h" 78 #include <cassert> 79 #include <cmath> 80 #include <cstdint> 81 #include <iterator> 82 #include <tuple> 83 #include <utility> 84 #include <vector> 85 86 using namespace llvm; 87 88 #define DEBUG_TYPE "si-lower" 89 90 STATISTIC(NumTailCalls, "Number of tail calls"); 91 92 static cl::opt<bool> EnableVGPRIndexMode( 93 "amdgpu-vgpr-index-mode", 94 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 95 cl::init(false)); 96 97 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits( 98 "amdgpu-frame-index-zero-bits", 99 cl::desc("High bits of frame index assumed to be zero"), 100 cl::init(5), 101 cl::ReallyHidden); 102 103 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 104 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 105 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 106 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 107 return AMDGPU::SGPR0 + Reg; 108 } 109 } 110 llvm_unreachable("Cannot allocate sgpr"); 111 } 112 113 SITargetLowering::SITargetLowering(const TargetMachine &TM, 114 const SISubtarget &STI) 115 : AMDGPUTargetLowering(TM, STI) { 116 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 117 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 118 119 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 120 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 121 122 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 123 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 124 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 125 126 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 127 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 128 129 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 130 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 131 132 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 133 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 134 135 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 136 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 137 138 if (Subtarget->has16BitInsts()) { 139 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 140 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 141 } 142 143 if (Subtarget->hasVOP3PInsts()) { 144 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 145 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 146 } 147 148 computeRegisterProperties(STI.getRegisterInfo()); 149 150 // We need to custom lower vector stores from local memory 151 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 152 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 153 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 154 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 155 setOperationAction(ISD::LOAD, MVT::i1, Custom); 156 157 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 158 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 159 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 160 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 161 setOperationAction(ISD::STORE, MVT::i1, Custom); 162 163 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 164 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 165 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 166 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 167 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 168 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 169 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 170 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 171 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 172 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 173 174 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 176 setOperationAction(ISD::ConstantPool, MVT::v2i64, Expand); 177 178 setOperationAction(ISD::SELECT, MVT::i1, Promote); 179 setOperationAction(ISD::SELECT, MVT::i64, Custom); 180 setOperationAction(ISD::SELECT, MVT::f64, Promote); 181 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 182 183 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 184 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 185 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 186 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 187 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 188 189 setOperationAction(ISD::SETCC, MVT::i1, Promote); 190 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 191 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 192 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 193 194 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 195 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 196 197 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 198 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 199 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 201 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 203 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 204 205 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 206 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 207 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 208 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 209 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 210 211 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 212 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 213 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 214 215 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 216 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 217 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 218 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 219 220 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 221 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 222 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 223 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 224 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 225 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 226 227 setOperationAction(ISD::UADDO, MVT::i32, Legal); 228 setOperationAction(ISD::USUBO, MVT::i32, Legal); 229 230 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 231 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 232 233 #if 0 234 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 235 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 236 #endif 237 238 //setOperationAction(ISD::ADDC, MVT::i64, Expand); 239 //setOperationAction(ISD::SUBC, MVT::i64, Expand); 240 241 // We only support LOAD/STORE and vector manipulation ops for vectors 242 // with > 4 elements. 243 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 244 MVT::v2i64, MVT::v2f64}) { 245 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 246 switch (Op) { 247 case ISD::LOAD: 248 case ISD::STORE: 249 case ISD::BUILD_VECTOR: 250 case ISD::BITCAST: 251 case ISD::EXTRACT_VECTOR_ELT: 252 case ISD::INSERT_VECTOR_ELT: 253 case ISD::INSERT_SUBVECTOR: 254 case ISD::EXTRACT_SUBVECTOR: 255 case ISD::SCALAR_TO_VECTOR: 256 break; 257 case ISD::CONCAT_VECTORS: 258 setOperationAction(Op, VT, Custom); 259 break; 260 default: 261 setOperationAction(Op, VT, Expand); 262 break; 263 } 264 } 265 } 266 267 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 268 // is expanded to avoid having two separate loops in case the index is a VGPR. 269 270 // Most operations are naturally 32-bit vector operations. We only support 271 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 272 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 273 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 274 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 275 276 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 277 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 278 279 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 280 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 281 282 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 283 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 284 } 285 286 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 287 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 288 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 289 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 290 291 // Avoid stack access for these. 292 // TODO: Generalize to more vector types. 293 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 294 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 295 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 296 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 297 298 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 299 // and output demarshalling 300 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 301 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 302 303 // We can't return success/failure, only the old value, 304 // let LLVM add the comparison 305 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 306 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 307 308 if (getSubtarget()->hasFlatAddressSpace()) { 309 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 310 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 311 } 312 313 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 314 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 315 316 // On SI this is s_memtime and s_memrealtime on VI. 317 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 318 setOperationAction(ISD::TRAP, MVT::Other, Custom); 319 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 320 321 setOperationAction(ISD::FMINNUM, MVT::f64, Legal); 322 setOperationAction(ISD::FMAXNUM, MVT::f64, Legal); 323 324 if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) { 325 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 326 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 327 setOperationAction(ISD::FRINT, MVT::f64, Legal); 328 } 329 330 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 331 332 setOperationAction(ISD::FSIN, MVT::f32, Custom); 333 setOperationAction(ISD::FCOS, MVT::f32, Custom); 334 setOperationAction(ISD::FDIV, MVT::f32, Custom); 335 setOperationAction(ISD::FDIV, MVT::f64, Custom); 336 337 if (Subtarget->has16BitInsts()) { 338 setOperationAction(ISD::Constant, MVT::i16, Legal); 339 340 setOperationAction(ISD::SMIN, MVT::i16, Legal); 341 setOperationAction(ISD::SMAX, MVT::i16, Legal); 342 343 setOperationAction(ISD::UMIN, MVT::i16, Legal); 344 setOperationAction(ISD::UMAX, MVT::i16, Legal); 345 346 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 347 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 348 349 setOperationAction(ISD::ROTR, MVT::i16, Promote); 350 setOperationAction(ISD::ROTL, MVT::i16, Promote); 351 352 setOperationAction(ISD::SDIV, MVT::i16, Promote); 353 setOperationAction(ISD::UDIV, MVT::i16, Promote); 354 setOperationAction(ISD::SREM, MVT::i16, Promote); 355 setOperationAction(ISD::UREM, MVT::i16, Promote); 356 357 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 358 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 359 360 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 361 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 362 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 363 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 364 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 365 366 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 367 368 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 369 370 setOperationAction(ISD::LOAD, MVT::i16, Custom); 371 372 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 373 374 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 375 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 376 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 377 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 378 379 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 380 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 381 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 382 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 383 384 // F16 - Constant Actions. 385 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 386 387 // F16 - Load/Store Actions. 388 setOperationAction(ISD::LOAD, MVT::f16, Promote); 389 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 390 setOperationAction(ISD::STORE, MVT::f16, Promote); 391 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 392 393 // F16 - VOP1 Actions. 394 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 395 setOperationAction(ISD::FCOS, MVT::f16, Promote); 396 setOperationAction(ISD::FSIN, MVT::f16, Promote); 397 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 398 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 399 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 400 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 401 setOperationAction(ISD::FROUND, MVT::f16, Custom); 402 403 // F16 - VOP2 Actions. 404 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 405 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 406 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 407 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 408 setOperationAction(ISD::FDIV, MVT::f16, Custom); 409 410 // F16 - VOP3 Actions. 411 setOperationAction(ISD::FMA, MVT::f16, Legal); 412 if (!Subtarget->hasFP16Denormals()) 413 setOperationAction(ISD::FMAD, MVT::f16, Legal); 414 } 415 416 if (Subtarget->hasVOP3PInsts()) { 417 for (MVT VT : {MVT::v2i16, MVT::v2f16}) { 418 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 419 switch (Op) { 420 case ISD::LOAD: 421 case ISD::STORE: 422 case ISD::BUILD_VECTOR: 423 case ISD::BITCAST: 424 case ISD::EXTRACT_VECTOR_ELT: 425 case ISD::INSERT_VECTOR_ELT: 426 case ISD::INSERT_SUBVECTOR: 427 case ISD::EXTRACT_SUBVECTOR: 428 case ISD::SCALAR_TO_VECTOR: 429 break; 430 case ISD::CONCAT_VECTORS: 431 setOperationAction(Op, VT, Custom); 432 break; 433 default: 434 setOperationAction(Op, VT, Expand); 435 break; 436 } 437 } 438 } 439 440 // XXX - Do these do anything? Vector constants turn into build_vector. 441 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 442 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 443 444 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 445 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 446 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 447 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 448 449 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 450 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 451 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 452 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 453 454 setOperationAction(ISD::AND, MVT::v2i16, Promote); 455 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 456 setOperationAction(ISD::OR, MVT::v2i16, Promote); 457 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 458 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 459 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 460 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 461 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 462 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 463 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 464 465 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 466 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 467 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 468 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 469 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 470 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 471 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 472 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 473 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 474 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 475 476 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 477 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 478 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 479 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 480 setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal); 481 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal); 482 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 483 484 // This isn't really legal, but this avoids the legalizer unrolling it (and 485 // allows matching fneg (fabs x) patterns) 486 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 487 488 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 489 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 490 491 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 492 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 493 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 494 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 495 } else { 496 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 497 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 498 } 499 500 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 501 setOperationAction(ISD::SELECT, VT, Custom); 502 } 503 504 setTargetDAGCombine(ISD::ADD); 505 setTargetDAGCombine(ISD::ADDCARRY); 506 setTargetDAGCombine(ISD::SUB); 507 setTargetDAGCombine(ISD::SUBCARRY); 508 setTargetDAGCombine(ISD::FADD); 509 setTargetDAGCombine(ISD::FSUB); 510 setTargetDAGCombine(ISD::FMINNUM); 511 setTargetDAGCombine(ISD::FMAXNUM); 512 setTargetDAGCombine(ISD::SMIN); 513 setTargetDAGCombine(ISD::SMAX); 514 setTargetDAGCombine(ISD::UMIN); 515 setTargetDAGCombine(ISD::UMAX); 516 setTargetDAGCombine(ISD::SETCC); 517 setTargetDAGCombine(ISD::AND); 518 setTargetDAGCombine(ISD::OR); 519 setTargetDAGCombine(ISD::XOR); 520 setTargetDAGCombine(ISD::SINT_TO_FP); 521 setTargetDAGCombine(ISD::UINT_TO_FP); 522 setTargetDAGCombine(ISD::FCANONICALIZE); 523 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 524 setTargetDAGCombine(ISD::ZERO_EXTEND); 525 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 526 setTargetDAGCombine(ISD::BUILD_VECTOR); 527 528 // All memory operations. Some folding on the pointer operand is done to help 529 // matching the constant offsets in the addressing modes. 530 setTargetDAGCombine(ISD::LOAD); 531 setTargetDAGCombine(ISD::STORE); 532 setTargetDAGCombine(ISD::ATOMIC_LOAD); 533 setTargetDAGCombine(ISD::ATOMIC_STORE); 534 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 535 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 536 setTargetDAGCombine(ISD::ATOMIC_SWAP); 537 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 538 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 539 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 540 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 541 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 542 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 543 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 544 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 545 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 546 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 547 548 setSchedulingPreference(Sched::RegPressure); 549 } 550 551 const SISubtarget *SITargetLowering::getSubtarget() const { 552 return static_cast<const SISubtarget *>(Subtarget); 553 } 554 555 //===----------------------------------------------------------------------===// 556 // TargetLowering queries 557 //===----------------------------------------------------------------------===// 558 559 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 560 // SI has some legal vector types, but no legal vector operations. Say no 561 // shuffles are legal in order to prefer scalarizing some vector operations. 562 return false; 563 } 564 565 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 566 const CallInst &CI, 567 MachineFunction &MF, 568 unsigned IntrID) const { 569 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 570 AMDGPU::lookupRsrcIntrinsicByIntr(IntrID)) { 571 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 572 (Intrinsic::ID)IntrID); 573 if (Attr.hasFnAttribute(Attribute::ReadNone)) 574 return false; 575 576 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 577 578 if (RsrcIntr->IsImage) { 579 Info.ptrVal = MFI->getImagePSV( 580 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 581 CI.getArgOperand(RsrcIntr->RsrcArg)); 582 Info.align = 0; 583 } else { 584 Info.ptrVal = MFI->getBufferPSV( 585 *MF.getSubtarget<SISubtarget>().getInstrInfo(), 586 CI.getArgOperand(RsrcIntr->RsrcArg)); 587 } 588 589 Info.flags = MachineMemOperand::MODereferenceable; 590 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 591 Info.opc = ISD::INTRINSIC_W_CHAIN; 592 Info.memVT = MVT::getVT(CI.getType()); 593 Info.flags |= MachineMemOperand::MOLoad; 594 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 595 Info.opc = ISD::INTRINSIC_VOID; 596 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 597 Info.flags |= MachineMemOperand::MOStore; 598 } else { 599 // Atomic 600 Info.opc = ISD::INTRINSIC_W_CHAIN; 601 Info.memVT = MVT::getVT(CI.getType()); 602 Info.flags = MachineMemOperand::MOLoad | 603 MachineMemOperand::MOStore | 604 MachineMemOperand::MODereferenceable; 605 606 // XXX - Should this be volatile without known ordering? 607 Info.flags |= MachineMemOperand::MOVolatile; 608 } 609 return true; 610 } 611 612 switch (IntrID) { 613 case Intrinsic::amdgcn_atomic_inc: 614 case Intrinsic::amdgcn_atomic_dec: 615 case Intrinsic::amdgcn_ds_fadd: 616 case Intrinsic::amdgcn_ds_fmin: 617 case Intrinsic::amdgcn_ds_fmax: { 618 Info.opc = ISD::INTRINSIC_W_CHAIN; 619 Info.memVT = MVT::getVT(CI.getType()); 620 Info.ptrVal = CI.getOperand(0); 621 Info.align = 0; 622 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 623 624 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 625 if (!Vol || !Vol->isZero()) 626 Info.flags |= MachineMemOperand::MOVolatile; 627 628 return true; 629 } 630 631 default: 632 return false; 633 } 634 } 635 636 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 637 SmallVectorImpl<Value*> &Ops, 638 Type *&AccessTy) const { 639 switch (II->getIntrinsicID()) { 640 case Intrinsic::amdgcn_atomic_inc: 641 case Intrinsic::amdgcn_atomic_dec: 642 case Intrinsic::amdgcn_ds_fadd: 643 case Intrinsic::amdgcn_ds_fmin: 644 case Intrinsic::amdgcn_ds_fmax: { 645 Value *Ptr = II->getArgOperand(0); 646 AccessTy = II->getType(); 647 Ops.push_back(Ptr); 648 return true; 649 } 650 default: 651 return false; 652 } 653 } 654 655 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 656 if (!Subtarget->hasFlatInstOffsets()) { 657 // Flat instructions do not have offsets, and only have the register 658 // address. 659 return AM.BaseOffs == 0 && AM.Scale == 0; 660 } 661 662 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 663 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 664 665 // Just r + i 666 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 667 } 668 669 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 670 if (Subtarget->hasFlatGlobalInsts()) 671 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 672 673 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 674 // Assume the we will use FLAT for all global memory accesses 675 // on VI. 676 // FIXME: This assumption is currently wrong. On VI we still use 677 // MUBUF instructions for the r + i addressing mode. As currently 678 // implemented, the MUBUF instructions only work on buffer < 4GB. 679 // It may be possible to support > 4GB buffers with MUBUF instructions, 680 // by setting the stride value in the resource descriptor which would 681 // increase the size limit to (stride * 4GB). However, this is risky, 682 // because it has never been validated. 683 return isLegalFlatAddressingMode(AM); 684 } 685 686 return isLegalMUBUFAddressingMode(AM); 687 } 688 689 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 690 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 691 // additionally can do r + r + i with addr64. 32-bit has more addressing 692 // mode options. Depending on the resource constant, it can also do 693 // (i64 r0) + (i32 r1) * (i14 i). 694 // 695 // Private arrays end up using a scratch buffer most of the time, so also 696 // assume those use MUBUF instructions. Scratch loads / stores are currently 697 // implemented as mubuf instructions with offen bit set, so slightly 698 // different than the normal addr64. 699 if (!isUInt<12>(AM.BaseOffs)) 700 return false; 701 702 // FIXME: Since we can split immediate into soffset and immediate offset, 703 // would it make sense to allow any immediate? 704 705 switch (AM.Scale) { 706 case 0: // r + i or just i, depending on HasBaseReg. 707 return true; 708 case 1: 709 return true; // We have r + r or r + i. 710 case 2: 711 if (AM.HasBaseReg) { 712 // Reject 2 * r + r. 713 return false; 714 } 715 716 // Allow 2 * r as r + r 717 // Or 2 * r + i is allowed as r + r + i. 718 return true; 719 default: // Don't allow n * r 720 return false; 721 } 722 } 723 724 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 725 const AddrMode &AM, Type *Ty, 726 unsigned AS, Instruction *I) const { 727 // No global is ever allowed as a base. 728 if (AM.BaseGV) 729 return false; 730 731 if (AS == AMDGPUASI.GLOBAL_ADDRESS) 732 return isLegalGlobalAddressingMode(AM); 733 734 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 735 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) { 736 // If the offset isn't a multiple of 4, it probably isn't going to be 737 // correctly aligned. 738 // FIXME: Can we get the real alignment here? 739 if (AM.BaseOffs % 4 != 0) 740 return isLegalMUBUFAddressingMode(AM); 741 742 // There are no SMRD extloads, so if we have to do a small type access we 743 // will use a MUBUF load. 744 // FIXME?: We also need to do this if unaligned, but we don't know the 745 // alignment here. 746 if (DL.getTypeStoreSize(Ty) < 4) 747 return isLegalGlobalAddressingMode(AM); 748 749 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 750 // SMRD instructions have an 8-bit, dword offset on SI. 751 if (!isUInt<8>(AM.BaseOffs / 4)) 752 return false; 753 } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) { 754 // On CI+, this can also be a 32-bit literal constant offset. If it fits 755 // in 8-bits, it can use a smaller encoding. 756 if (!isUInt<32>(AM.BaseOffs / 4)) 757 return false; 758 } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) { 759 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 760 if (!isUInt<20>(AM.BaseOffs)) 761 return false; 762 } else 763 llvm_unreachable("unhandled generation"); 764 765 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 766 return true; 767 768 if (AM.Scale == 1 && AM.HasBaseReg) 769 return true; 770 771 return false; 772 773 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 774 return isLegalMUBUFAddressingMode(AM); 775 } else if (AS == AMDGPUASI.LOCAL_ADDRESS || 776 AS == AMDGPUASI.REGION_ADDRESS) { 777 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 778 // field. 779 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 780 // an 8-bit dword offset but we don't know the alignment here. 781 if (!isUInt<16>(AM.BaseOffs)) 782 return false; 783 784 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 785 return true; 786 787 if (AM.Scale == 1 && AM.HasBaseReg) 788 return true; 789 790 return false; 791 } else if (AS == AMDGPUASI.FLAT_ADDRESS || 792 AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) { 793 // For an unknown address space, this usually means that this is for some 794 // reason being used for pure arithmetic, and not based on some addressing 795 // computation. We don't have instructions that compute pointers with any 796 // addressing modes, so treat them as having no offset like flat 797 // instructions. 798 return isLegalFlatAddressingMode(AM); 799 } else { 800 llvm_unreachable("unhandled address space"); 801 } 802 } 803 804 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 805 const SelectionDAG &DAG) const { 806 if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) { 807 return (MemVT.getSizeInBits() <= 4 * 32); 808 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 809 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 810 return (MemVT.getSizeInBits() <= MaxPrivateBits); 811 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 812 return (MemVT.getSizeInBits() <= 2 * 32); 813 } 814 return true; 815 } 816 817 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 818 unsigned AddrSpace, 819 unsigned Align, 820 bool *IsFast) const { 821 if (IsFast) 822 *IsFast = false; 823 824 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 825 // which isn't a simple VT. 826 // Until MVT is extended to handle this, simply check for the size and 827 // rely on the condition below: allow accesses if the size is a multiple of 4. 828 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 829 VT.getStoreSize() > 16)) { 830 return false; 831 } 832 833 if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS || 834 AddrSpace == AMDGPUASI.REGION_ADDRESS) { 835 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 836 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 837 // with adjacent offsets. 838 bool AlignedBy4 = (Align % 4 == 0); 839 if (IsFast) 840 *IsFast = AlignedBy4; 841 842 return AlignedBy4; 843 } 844 845 // FIXME: We have to be conservative here and assume that flat operations 846 // will access scratch. If we had access to the IR function, then we 847 // could determine if any private memory was used in the function. 848 if (!Subtarget->hasUnalignedScratchAccess() && 849 (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS || 850 AddrSpace == AMDGPUASI.FLAT_ADDRESS)) { 851 return false; 852 } 853 854 if (Subtarget->hasUnalignedBufferAccess()) { 855 // If we have an uniform constant load, it still requires using a slow 856 // buffer instruction if unaligned. 857 if (IsFast) { 858 *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS || 859 AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ? 860 (Align % 4 == 0) : true; 861 } 862 863 return true; 864 } 865 866 // Smaller than dword value must be aligned. 867 if (VT.bitsLT(MVT::i32)) 868 return false; 869 870 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 871 // byte-address are ignored, thus forcing Dword alignment. 872 // This applies to private, global, and constant memory. 873 if (IsFast) 874 *IsFast = true; 875 876 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 877 } 878 879 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 880 unsigned SrcAlign, bool IsMemset, 881 bool ZeroMemset, 882 bool MemcpyStrSrc, 883 MachineFunction &MF) const { 884 // FIXME: Should account for address space here. 885 886 // The default fallback uses the private pointer size as a guess for a type to 887 // use. Make sure we switch these to 64-bit accesses. 888 889 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 890 return MVT::v4i32; 891 892 if (Size >= 8 && DstAlign >= 4) 893 return MVT::v2i32; 894 895 // Use the default. 896 return MVT::Other; 897 } 898 899 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) { 900 return AS == AMDGPUASI.GLOBAL_ADDRESS || 901 AS == AMDGPUASI.FLAT_ADDRESS || 902 AS == AMDGPUASI.CONSTANT_ADDRESS || 903 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT; 904 } 905 906 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 907 unsigned DestAS) const { 908 return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) && 909 isFlatGlobalAddrSpace(DestAS, AMDGPUASI); 910 } 911 912 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 913 const MemSDNode *MemNode = cast<MemSDNode>(N); 914 const Value *Ptr = MemNode->getMemOperand()->getValue(); 915 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 916 return I && I->getMetadata("amdgpu.noclobber"); 917 } 918 919 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS, 920 unsigned DestAS) const { 921 // Flat -> private/local is a simple truncate. 922 // Flat -> global is no-op 923 if (SrcAS == AMDGPUASI.FLAT_ADDRESS) 924 return true; 925 926 return isNoopAddrSpaceCast(SrcAS, DestAS); 927 } 928 929 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 930 const MemSDNode *MemNode = cast<MemSDNode>(N); 931 932 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 933 } 934 935 TargetLoweringBase::LegalizeTypeAction 936 SITargetLowering::getPreferredVectorAction(EVT VT) const { 937 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 938 return TypeSplitVector; 939 940 return TargetLoweringBase::getPreferredVectorAction(VT); 941 } 942 943 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 944 Type *Ty) const { 945 // FIXME: Could be smarter if called for vector constants. 946 return true; 947 } 948 949 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 950 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 951 switch (Op) { 952 case ISD::LOAD: 953 case ISD::STORE: 954 955 // These operations are done with 32-bit instructions anyway. 956 case ISD::AND: 957 case ISD::OR: 958 case ISD::XOR: 959 case ISD::SELECT: 960 // TODO: Extensions? 961 return true; 962 default: 963 return false; 964 } 965 } 966 967 // SimplifySetCC uses this function to determine whether or not it should 968 // create setcc with i1 operands. We don't have instructions for i1 setcc. 969 if (VT == MVT::i1 && Op == ISD::SETCC) 970 return false; 971 972 return TargetLowering::isTypeDesirableForOp(Op, VT); 973 } 974 975 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 976 const SDLoc &SL, 977 SDValue Chain, 978 uint64_t Offset) const { 979 const DataLayout &DL = DAG.getDataLayout(); 980 MachineFunction &MF = DAG.getMachineFunction(); 981 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 982 983 const ArgDescriptor *InputPtrReg; 984 const TargetRegisterClass *RC; 985 986 std::tie(InputPtrReg, RC) 987 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 988 989 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 990 MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS); 991 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 992 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 993 994 return DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr, 995 DAG.getConstant(Offset, SL, PtrVT)); 996 } 997 998 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 999 const SDLoc &SL) const { 1000 auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>(); 1001 uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT); 1002 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1003 } 1004 1005 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1006 const SDLoc &SL, SDValue Val, 1007 bool Signed, 1008 const ISD::InputArg *Arg) const { 1009 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1010 VT.bitsLT(MemVT)) { 1011 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1012 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1013 } 1014 1015 if (MemVT.isFloatingPoint()) 1016 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1017 else if (Signed) 1018 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1019 else 1020 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1021 1022 return Val; 1023 } 1024 1025 SDValue SITargetLowering::lowerKernargMemParameter( 1026 SelectionDAG &DAG, EVT VT, EVT MemVT, 1027 const SDLoc &SL, SDValue Chain, 1028 uint64_t Offset, bool Signed, 1029 const ISD::InputArg *Arg) const { 1030 const DataLayout &DL = DAG.getDataLayout(); 1031 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1032 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 1033 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1034 1035 unsigned Align = DL.getABITypeAlignment(Ty); 1036 1037 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1038 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1039 MachineMemOperand::MODereferenceable | 1040 MachineMemOperand::MOInvariant); 1041 1042 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1043 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1044 } 1045 1046 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1047 const SDLoc &SL, SDValue Chain, 1048 const ISD::InputArg &Arg) const { 1049 MachineFunction &MF = DAG.getMachineFunction(); 1050 MachineFrameInfo &MFI = MF.getFrameInfo(); 1051 1052 if (Arg.Flags.isByVal()) { 1053 unsigned Size = Arg.Flags.getByValSize(); 1054 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1055 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1056 } 1057 1058 unsigned ArgOffset = VA.getLocMemOffset(); 1059 unsigned ArgSize = VA.getValVT().getStoreSize(); 1060 1061 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1062 1063 // Create load nodes to retrieve arguments from the stack. 1064 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1065 SDValue ArgValue; 1066 1067 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1068 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1069 MVT MemVT = VA.getValVT(); 1070 1071 switch (VA.getLocInfo()) { 1072 default: 1073 break; 1074 case CCValAssign::BCvt: 1075 MemVT = VA.getLocVT(); 1076 break; 1077 case CCValAssign::SExt: 1078 ExtType = ISD::SEXTLOAD; 1079 break; 1080 case CCValAssign::ZExt: 1081 ExtType = ISD::ZEXTLOAD; 1082 break; 1083 case CCValAssign::AExt: 1084 ExtType = ISD::EXTLOAD; 1085 break; 1086 } 1087 1088 ArgValue = DAG.getExtLoad( 1089 ExtType, SL, VA.getLocVT(), Chain, FIN, 1090 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1091 MemVT); 1092 return ArgValue; 1093 } 1094 1095 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1096 const SIMachineFunctionInfo &MFI, 1097 EVT VT, 1098 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1099 const ArgDescriptor *Reg; 1100 const TargetRegisterClass *RC; 1101 1102 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1103 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1104 } 1105 1106 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1107 CallingConv::ID CallConv, 1108 ArrayRef<ISD::InputArg> Ins, 1109 BitVector &Skipped, 1110 FunctionType *FType, 1111 SIMachineFunctionInfo *Info) { 1112 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1113 const ISD::InputArg &Arg = Ins[I]; 1114 1115 // First check if it's a PS input addr. 1116 if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() && 1117 !Arg.Flags.isByVal() && PSInputNum <= 15) { 1118 1119 if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) { 1120 // We can safely skip PS inputs. 1121 Skipped.set(I); 1122 ++PSInputNum; 1123 continue; 1124 } 1125 1126 Info->markPSInputAllocated(PSInputNum); 1127 if (Arg.Used) 1128 Info->markPSInputEnabled(PSInputNum); 1129 1130 ++PSInputNum; 1131 } 1132 1133 // Second split vertices into their elements. 1134 if (Arg.VT.isVector()) { 1135 ISD::InputArg NewArg = Arg; 1136 NewArg.Flags.setSplit(); 1137 NewArg.VT = Arg.VT.getVectorElementType(); 1138 1139 // We REALLY want the ORIGINAL number of vertex elements here, e.g. a 1140 // three or five element vertex only needs three or five registers, 1141 // NOT four or eight. 1142 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1143 unsigned NumElements = ParamType->getVectorNumElements(); 1144 1145 for (unsigned J = 0; J != NumElements; ++J) { 1146 Splits.push_back(NewArg); 1147 NewArg.PartOffset += NewArg.VT.getStoreSize(); 1148 } 1149 } else { 1150 Splits.push_back(Arg); 1151 } 1152 } 1153 } 1154 1155 // Allocate special inputs passed in VGPRs. 1156 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1157 MachineFunction &MF, 1158 const SIRegisterInfo &TRI, 1159 SIMachineFunctionInfo &Info) { 1160 if (Info.hasWorkItemIDX()) { 1161 unsigned Reg = AMDGPU::VGPR0; 1162 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1163 1164 CCInfo.AllocateReg(Reg); 1165 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1166 } 1167 1168 if (Info.hasWorkItemIDY()) { 1169 unsigned Reg = AMDGPU::VGPR1; 1170 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1171 1172 CCInfo.AllocateReg(Reg); 1173 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1174 } 1175 1176 if (Info.hasWorkItemIDZ()) { 1177 unsigned Reg = AMDGPU::VGPR2; 1178 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1179 1180 CCInfo.AllocateReg(Reg); 1181 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1182 } 1183 } 1184 1185 // Try to allocate a VGPR at the end of the argument list, or if no argument 1186 // VGPRs are left allocating a stack slot. 1187 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) { 1188 ArrayRef<MCPhysReg> ArgVGPRs 1189 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1190 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1191 if (RegIdx == ArgVGPRs.size()) { 1192 // Spill to stack required. 1193 int64_t Offset = CCInfo.AllocateStack(4, 4); 1194 1195 return ArgDescriptor::createStack(Offset); 1196 } 1197 1198 unsigned Reg = ArgVGPRs[RegIdx]; 1199 Reg = CCInfo.AllocateReg(Reg); 1200 assert(Reg != AMDGPU::NoRegister); 1201 1202 MachineFunction &MF = CCInfo.getMachineFunction(); 1203 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1204 return ArgDescriptor::createRegister(Reg); 1205 } 1206 1207 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1208 const TargetRegisterClass *RC, 1209 unsigned NumArgRegs) { 1210 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1211 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1212 if (RegIdx == ArgSGPRs.size()) 1213 report_fatal_error("ran out of SGPRs for arguments"); 1214 1215 unsigned Reg = ArgSGPRs[RegIdx]; 1216 Reg = CCInfo.AllocateReg(Reg); 1217 assert(Reg != AMDGPU::NoRegister); 1218 1219 MachineFunction &MF = CCInfo.getMachineFunction(); 1220 MF.addLiveIn(Reg, RC); 1221 return ArgDescriptor::createRegister(Reg); 1222 } 1223 1224 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1225 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1226 } 1227 1228 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1229 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1230 } 1231 1232 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1233 MachineFunction &MF, 1234 const SIRegisterInfo &TRI, 1235 SIMachineFunctionInfo &Info) { 1236 if (Info.hasWorkItemIDX()) 1237 Info.setWorkItemIDX(allocateVGPR32Input(CCInfo)); 1238 1239 if (Info.hasWorkItemIDY()) 1240 Info.setWorkItemIDY(allocateVGPR32Input(CCInfo)); 1241 1242 if (Info.hasWorkItemIDZ()) 1243 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo)); 1244 } 1245 1246 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1247 MachineFunction &MF, 1248 const SIRegisterInfo &TRI, 1249 SIMachineFunctionInfo &Info) { 1250 auto &ArgInfo = Info.getArgInfo(); 1251 1252 // TODO: Unify handling with private memory pointers. 1253 1254 if (Info.hasDispatchPtr()) 1255 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1256 1257 if (Info.hasQueuePtr()) 1258 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1259 1260 if (Info.hasKernargSegmentPtr()) 1261 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1262 1263 if (Info.hasDispatchID()) 1264 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1265 1266 // flat_scratch_init is not applicable for non-kernel functions. 1267 1268 if (Info.hasWorkGroupIDX()) 1269 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1270 1271 if (Info.hasWorkGroupIDY()) 1272 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1273 1274 if (Info.hasWorkGroupIDZ()) 1275 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1276 1277 if (Info.hasImplicitArgPtr()) 1278 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1279 } 1280 1281 // Allocate special inputs passed in user SGPRs. 1282 static void allocateHSAUserSGPRs(CCState &CCInfo, 1283 MachineFunction &MF, 1284 const SIRegisterInfo &TRI, 1285 SIMachineFunctionInfo &Info) { 1286 if (Info.hasImplicitBufferPtr()) { 1287 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1288 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1289 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1290 } 1291 1292 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1293 if (Info.hasPrivateSegmentBuffer()) { 1294 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1295 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1296 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1297 } 1298 1299 if (Info.hasDispatchPtr()) { 1300 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1301 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1302 CCInfo.AllocateReg(DispatchPtrReg); 1303 } 1304 1305 if (Info.hasQueuePtr()) { 1306 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1307 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1308 CCInfo.AllocateReg(QueuePtrReg); 1309 } 1310 1311 if (Info.hasKernargSegmentPtr()) { 1312 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1313 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1314 CCInfo.AllocateReg(InputPtrReg); 1315 } 1316 1317 if (Info.hasDispatchID()) { 1318 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1319 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1320 CCInfo.AllocateReg(DispatchIDReg); 1321 } 1322 1323 if (Info.hasFlatScratchInit()) { 1324 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1325 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1326 CCInfo.AllocateReg(FlatScratchInitReg); 1327 } 1328 1329 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1330 // these from the dispatch pointer. 1331 } 1332 1333 // Allocate special input registers that are initialized per-wave. 1334 static void allocateSystemSGPRs(CCState &CCInfo, 1335 MachineFunction &MF, 1336 SIMachineFunctionInfo &Info, 1337 CallingConv::ID CallConv, 1338 bool IsShader) { 1339 if (Info.hasWorkGroupIDX()) { 1340 unsigned Reg = Info.addWorkGroupIDX(); 1341 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1342 CCInfo.AllocateReg(Reg); 1343 } 1344 1345 if (Info.hasWorkGroupIDY()) { 1346 unsigned Reg = Info.addWorkGroupIDY(); 1347 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1348 CCInfo.AllocateReg(Reg); 1349 } 1350 1351 if (Info.hasWorkGroupIDZ()) { 1352 unsigned Reg = Info.addWorkGroupIDZ(); 1353 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1354 CCInfo.AllocateReg(Reg); 1355 } 1356 1357 if (Info.hasWorkGroupInfo()) { 1358 unsigned Reg = Info.addWorkGroupInfo(); 1359 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1360 CCInfo.AllocateReg(Reg); 1361 } 1362 1363 if (Info.hasPrivateSegmentWaveByteOffset()) { 1364 // Scratch wave offset passed in system SGPR. 1365 unsigned PrivateSegmentWaveByteOffsetReg; 1366 1367 if (IsShader) { 1368 PrivateSegmentWaveByteOffsetReg = 1369 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1370 1371 // This is true if the scratch wave byte offset doesn't have a fixed 1372 // location. 1373 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1374 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1375 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1376 } 1377 } else 1378 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1379 1380 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1381 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1382 } 1383 } 1384 1385 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1386 MachineFunction &MF, 1387 const SIRegisterInfo &TRI, 1388 SIMachineFunctionInfo &Info) { 1389 // Now that we've figured out where the scratch register inputs are, see if 1390 // should reserve the arguments and use them directly. 1391 MachineFrameInfo &MFI = MF.getFrameInfo(); 1392 bool HasStackObjects = MFI.hasStackObjects(); 1393 1394 // Record that we know we have non-spill stack objects so we don't need to 1395 // check all stack objects later. 1396 if (HasStackObjects) 1397 Info.setHasNonSpillStackObjects(true); 1398 1399 // Everything live out of a block is spilled with fast regalloc, so it's 1400 // almost certain that spilling will be required. 1401 if (TM.getOptLevel() == CodeGenOpt::None) 1402 HasStackObjects = true; 1403 1404 // For now assume stack access is needed in any callee functions, so we need 1405 // the scratch registers to pass in. 1406 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1407 1408 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1409 if (ST.isAmdCodeObjectV2(MF)) { 1410 if (RequiresStackAccess) { 1411 // If we have stack objects, we unquestionably need the private buffer 1412 // resource. For the Code Object V2 ABI, this will be the first 4 user 1413 // SGPR inputs. We can reserve those and use them directly. 1414 1415 unsigned PrivateSegmentBufferReg = Info.getPreloadedReg( 1416 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1417 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1418 1419 if (MFI.hasCalls()) { 1420 // If we have calls, we need to keep the frame register in a register 1421 // that won't be clobbered by a call, so ensure it is copied somewhere. 1422 1423 // This is not a problem for the scratch wave offset, because the same 1424 // registers are reserved in all functions. 1425 1426 // FIXME: Nothing is really ensuring this is a call preserved register, 1427 // it's just selected from the end so it happens to be. 1428 unsigned ReservedOffsetReg 1429 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1430 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1431 } else { 1432 unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg( 1433 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1434 Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg); 1435 } 1436 } else { 1437 unsigned ReservedBufferReg 1438 = TRI.reservedPrivateSegmentBufferReg(MF); 1439 unsigned ReservedOffsetReg 1440 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1441 1442 // We tentatively reserve the last registers (skipping the last two 1443 // which may contain VCC). After register allocation, we'll replace 1444 // these with the ones immediately after those which were really 1445 // allocated. In the prologue copies will be inserted from the argument 1446 // to these reserved registers. 1447 Info.setScratchRSrcReg(ReservedBufferReg); 1448 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1449 } 1450 } else { 1451 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1452 1453 // Without HSA, relocations are used for the scratch pointer and the 1454 // buffer resource setup is always inserted in the prologue. Scratch wave 1455 // offset is still in an input SGPR. 1456 Info.setScratchRSrcReg(ReservedBufferReg); 1457 1458 if (HasStackObjects && !MFI.hasCalls()) { 1459 unsigned ScratchWaveOffsetReg = Info.getPreloadedReg( 1460 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1461 Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg); 1462 } else { 1463 unsigned ReservedOffsetReg 1464 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1465 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1466 } 1467 } 1468 } 1469 1470 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1471 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1472 return !Info->isEntryFunction(); 1473 } 1474 1475 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1476 1477 } 1478 1479 void SITargetLowering::insertCopiesSplitCSR( 1480 MachineBasicBlock *Entry, 1481 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1482 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1483 1484 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1485 if (!IStart) 1486 return; 1487 1488 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1489 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1490 MachineBasicBlock::iterator MBBI = Entry->begin(); 1491 for (const MCPhysReg *I = IStart; *I; ++I) { 1492 const TargetRegisterClass *RC = nullptr; 1493 if (AMDGPU::SReg_64RegClass.contains(*I)) 1494 RC = &AMDGPU::SGPR_64RegClass; 1495 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1496 RC = &AMDGPU::SGPR_32RegClass; 1497 else 1498 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1499 1500 unsigned NewVR = MRI->createVirtualRegister(RC); 1501 // Create copy from CSR to a virtual register. 1502 Entry->addLiveIn(*I); 1503 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1504 .addReg(*I); 1505 1506 // Insert the copy-back instructions right before the terminator. 1507 for (auto *Exit : Exits) 1508 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1509 TII->get(TargetOpcode::COPY), *I) 1510 .addReg(NewVR); 1511 } 1512 } 1513 1514 SDValue SITargetLowering::LowerFormalArguments( 1515 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1516 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1517 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1518 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1519 1520 MachineFunction &MF = DAG.getMachineFunction(); 1521 FunctionType *FType = MF.getFunction().getFunctionType(); 1522 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1523 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 1524 1525 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1526 const Function &Fn = MF.getFunction(); 1527 DiagnosticInfoUnsupported NoGraphicsHSA( 1528 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1529 DAG.getContext()->diagnose(NoGraphicsHSA); 1530 return DAG.getEntryNode(); 1531 } 1532 1533 // Create stack objects that are used for emitting debugger prologue if 1534 // "amdgpu-debugger-emit-prologue" attribute was specified. 1535 if (ST.debuggerEmitPrologue()) 1536 createDebuggerPrologueStackObjects(MF); 1537 1538 SmallVector<ISD::InputArg, 16> Splits; 1539 SmallVector<CCValAssign, 16> ArgLocs; 1540 BitVector Skipped(Ins.size()); 1541 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1542 *DAG.getContext()); 1543 1544 bool IsShader = AMDGPU::isShader(CallConv); 1545 bool IsKernel = AMDGPU::isKernel(CallConv); 1546 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1547 1548 if (!IsEntryFunc) { 1549 // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over 1550 // this when allocating argument fixed offsets. 1551 CCInfo.AllocateStack(4, 4); 1552 } 1553 1554 if (IsShader) { 1555 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1556 1557 // At least one interpolation mode must be enabled or else the GPU will 1558 // hang. 1559 // 1560 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1561 // set PSInputAddr, the user wants to enable some bits after the compilation 1562 // based on run-time states. Since we can't know what the final PSInputEna 1563 // will look like, so we shouldn't do anything here and the user should take 1564 // responsibility for the correct programming. 1565 // 1566 // Otherwise, the following restrictions apply: 1567 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1568 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1569 // enabled too. 1570 if (CallConv == CallingConv::AMDGPU_PS) { 1571 if ((Info->getPSInputAddr() & 0x7F) == 0 || 1572 ((Info->getPSInputAddr() & 0xF) == 0 && 1573 Info->isPSInputAllocated(11))) { 1574 CCInfo.AllocateReg(AMDGPU::VGPR0); 1575 CCInfo.AllocateReg(AMDGPU::VGPR1); 1576 Info->markPSInputAllocated(0); 1577 Info->markPSInputEnabled(0); 1578 } 1579 if (Subtarget->isAmdPalOS()) { 1580 // For isAmdPalOS, the user does not enable some bits after compilation 1581 // based on run-time states; the register values being generated here are 1582 // the final ones set in hardware. Therefore we need to apply the 1583 // workaround to PSInputAddr and PSInputEnable together. (The case where 1584 // a bit is set in PSInputAddr but not PSInputEnable is where the 1585 // frontend set up an input arg for a particular interpolation mode, but 1586 // nothing uses that input arg. Really we should have an earlier pass 1587 // that removes such an arg.) 1588 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 1589 if ((PsInputBits & 0x7F) == 0 || 1590 ((PsInputBits & 0xF) == 0 && 1591 (PsInputBits >> 11 & 1))) 1592 Info->markPSInputEnabled( 1593 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 1594 } 1595 } 1596 1597 assert(!Info->hasDispatchPtr() && 1598 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 1599 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 1600 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 1601 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 1602 !Info->hasWorkItemIDZ()); 1603 } else if (IsKernel) { 1604 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 1605 } else { 1606 Splits.append(Ins.begin(), Ins.end()); 1607 } 1608 1609 if (IsEntryFunc) { 1610 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 1611 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 1612 } 1613 1614 if (IsKernel) { 1615 analyzeFormalArgumentsCompute(CCInfo, Ins); 1616 } else { 1617 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 1618 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 1619 } 1620 1621 SmallVector<SDValue, 16> Chains; 1622 1623 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 1624 const ISD::InputArg &Arg = Ins[i]; 1625 if (Skipped[i]) { 1626 InVals.push_back(DAG.getUNDEF(Arg.VT)); 1627 continue; 1628 } 1629 1630 CCValAssign &VA = ArgLocs[ArgIdx++]; 1631 MVT VT = VA.getLocVT(); 1632 1633 if (IsEntryFunc && VA.isMemLoc()) { 1634 VT = Ins[i].VT; 1635 EVT MemVT = VA.getLocVT(); 1636 1637 const uint64_t Offset = Subtarget->getExplicitKernelArgOffset(MF) + 1638 VA.getLocMemOffset(); 1639 Info->setABIArgOffset(Offset + MemVT.getStoreSize()); 1640 1641 // The first 36 bytes of the input buffer contains information about 1642 // thread group and global sizes. 1643 SDValue Arg = lowerKernargMemParameter( 1644 DAG, VT, MemVT, DL, Chain, Offset, Ins[i].Flags.isSExt(), &Ins[i]); 1645 Chains.push_back(Arg.getValue(1)); 1646 1647 auto *ParamTy = 1648 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 1649 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 1650 ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 1651 // On SI local pointers are just offsets into LDS, so they are always 1652 // less than 16-bits. On CI and newer they could potentially be 1653 // real pointers, so we can't guarantee their size. 1654 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 1655 DAG.getValueType(MVT::i16)); 1656 } 1657 1658 InVals.push_back(Arg); 1659 continue; 1660 } else if (!IsEntryFunc && VA.isMemLoc()) { 1661 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 1662 InVals.push_back(Val); 1663 if (!Arg.Flags.isByVal()) 1664 Chains.push_back(Val.getValue(1)); 1665 continue; 1666 } 1667 1668 assert(VA.isRegLoc() && "Parameter must be in a register!"); 1669 1670 unsigned Reg = VA.getLocReg(); 1671 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 1672 EVT ValVT = VA.getValVT(); 1673 1674 Reg = MF.addLiveIn(Reg, RC); 1675 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1676 1677 if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) { 1678 // The return object should be reasonably addressable. 1679 1680 // FIXME: This helps when the return is a real sret. If it is a 1681 // automatically inserted sret (i.e. CanLowerReturn returns false), an 1682 // extra copy is inserted in SelectionDAGBuilder which obscures this. 1683 unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits; 1684 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1685 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 1686 } 1687 1688 // If this is an 8 or 16-bit value, it is really passed promoted 1689 // to 32 bits. Insert an assert[sz]ext to capture this, then 1690 // truncate to the right size. 1691 switch (VA.getLocInfo()) { 1692 case CCValAssign::Full: 1693 break; 1694 case CCValAssign::BCvt: 1695 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 1696 break; 1697 case CCValAssign::SExt: 1698 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 1699 DAG.getValueType(ValVT)); 1700 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1701 break; 1702 case CCValAssign::ZExt: 1703 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 1704 DAG.getValueType(ValVT)); 1705 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1706 break; 1707 case CCValAssign::AExt: 1708 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 1709 break; 1710 default: 1711 llvm_unreachable("Unknown loc info!"); 1712 } 1713 1714 if (IsShader && Arg.VT.isVector()) { 1715 // Build a vector from the registers 1716 Type *ParamType = FType->getParamType(Arg.getOrigArgIndex()); 1717 unsigned NumElements = ParamType->getVectorNumElements(); 1718 1719 SmallVector<SDValue, 4> Regs; 1720 Regs.push_back(Val); 1721 for (unsigned j = 1; j != NumElements; ++j) { 1722 Reg = ArgLocs[ArgIdx++].getLocReg(); 1723 Reg = MF.addLiveIn(Reg, RC); 1724 1725 SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT); 1726 Regs.push_back(Copy); 1727 } 1728 1729 // Fill up the missing vector elements 1730 NumElements = Arg.VT.getVectorNumElements() - NumElements; 1731 Regs.append(NumElements, DAG.getUNDEF(VT)); 1732 1733 InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs)); 1734 continue; 1735 } 1736 1737 InVals.push_back(Val); 1738 } 1739 1740 if (!IsEntryFunc) { 1741 // Special inputs come after user arguments. 1742 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 1743 } 1744 1745 // Start adding system SGPRs. 1746 if (IsEntryFunc) { 1747 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 1748 } else { 1749 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 1750 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 1751 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 1752 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 1753 } 1754 1755 auto &ArgUsageInfo = 1756 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 1757 ArgUsageInfo.setFuncArgInfo(MF.getFunction(), Info->getArgInfo()); 1758 1759 unsigned StackArgSize = CCInfo.getNextStackOffset(); 1760 Info->setBytesInStackArgArea(StackArgSize); 1761 1762 return Chains.empty() ? Chain : 1763 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 1764 } 1765 1766 // TODO: If return values can't fit in registers, we should return as many as 1767 // possible in registers before passing on stack. 1768 bool SITargetLowering::CanLowerReturn( 1769 CallingConv::ID CallConv, 1770 MachineFunction &MF, bool IsVarArg, 1771 const SmallVectorImpl<ISD::OutputArg> &Outs, 1772 LLVMContext &Context) const { 1773 // Replacing returns with sret/stack usage doesn't make sense for shaders. 1774 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 1775 // for shaders. Vector types should be explicitly handled by CC. 1776 if (AMDGPU::isEntryFunctionCC(CallConv)) 1777 return true; 1778 1779 SmallVector<CCValAssign, 16> RVLocs; 1780 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 1781 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 1782 } 1783 1784 SDValue 1785 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 1786 bool isVarArg, 1787 const SmallVectorImpl<ISD::OutputArg> &Outs, 1788 const SmallVectorImpl<SDValue> &OutVals, 1789 const SDLoc &DL, SelectionDAG &DAG) const { 1790 MachineFunction &MF = DAG.getMachineFunction(); 1791 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1792 1793 if (AMDGPU::isKernel(CallConv)) { 1794 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 1795 OutVals, DL, DAG); 1796 } 1797 1798 bool IsShader = AMDGPU::isShader(CallConv); 1799 1800 Info->setIfReturnsVoid(Outs.size() == 0); 1801 bool IsWaveEnd = Info->returnsVoid() && IsShader; 1802 1803 SmallVector<ISD::OutputArg, 48> Splits; 1804 SmallVector<SDValue, 48> SplitVals; 1805 1806 // Split vectors into their elements. 1807 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 1808 const ISD::OutputArg &Out = Outs[i]; 1809 1810 if (IsShader && Out.VT.isVector()) { 1811 MVT VT = Out.VT.getVectorElementType(); 1812 ISD::OutputArg NewOut = Out; 1813 NewOut.Flags.setSplit(); 1814 NewOut.VT = VT; 1815 1816 // We want the original number of vector elements here, e.g. 1817 // three or five, not four or eight. 1818 unsigned NumElements = Out.ArgVT.getVectorNumElements(); 1819 1820 for (unsigned j = 0; j != NumElements; ++j) { 1821 SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i], 1822 DAG.getConstant(j, DL, MVT::i32)); 1823 SplitVals.push_back(Elem); 1824 Splits.push_back(NewOut); 1825 NewOut.PartOffset += NewOut.VT.getStoreSize(); 1826 } 1827 } else { 1828 SplitVals.push_back(OutVals[i]); 1829 Splits.push_back(Out); 1830 } 1831 } 1832 1833 // CCValAssign - represent the assignment of the return value to a location. 1834 SmallVector<CCValAssign, 48> RVLocs; 1835 1836 // CCState - Info about the registers and stack slots. 1837 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 1838 *DAG.getContext()); 1839 1840 // Analyze outgoing return values. 1841 CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg)); 1842 1843 SDValue Flag; 1844 SmallVector<SDValue, 48> RetOps; 1845 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 1846 1847 // Add return address for callable functions. 1848 if (!Info->isEntryFunction()) { 1849 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1850 SDValue ReturnAddrReg = CreateLiveInRegister( 1851 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 1852 1853 // FIXME: Should be able to use a vreg here, but need a way to prevent it 1854 // from being allcoated to a CSR. 1855 1856 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 1857 MVT::i64); 1858 1859 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 1860 Flag = Chain.getValue(1); 1861 1862 RetOps.push_back(PhysReturnAddrReg); 1863 } 1864 1865 // Copy the result values into the output registers. 1866 for (unsigned i = 0, realRVLocIdx = 0; 1867 i != RVLocs.size(); 1868 ++i, ++realRVLocIdx) { 1869 CCValAssign &VA = RVLocs[i]; 1870 assert(VA.isRegLoc() && "Can only return in registers!"); 1871 // TODO: Partially return in registers if return values don't fit. 1872 1873 SDValue Arg = SplitVals[realRVLocIdx]; 1874 1875 // Copied from other backends. 1876 switch (VA.getLocInfo()) { 1877 case CCValAssign::Full: 1878 break; 1879 case CCValAssign::BCvt: 1880 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 1881 break; 1882 case CCValAssign::SExt: 1883 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 1884 break; 1885 case CCValAssign::ZExt: 1886 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 1887 break; 1888 case CCValAssign::AExt: 1889 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 1890 break; 1891 default: 1892 llvm_unreachable("Unknown loc info!"); 1893 } 1894 1895 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 1896 Flag = Chain.getValue(1); 1897 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 1898 } 1899 1900 // FIXME: Does sret work properly? 1901 if (!Info->isEntryFunction()) { 1902 const SIRegisterInfo *TRI 1903 = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo(); 1904 const MCPhysReg *I = 1905 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 1906 if (I) { 1907 for (; *I; ++I) { 1908 if (AMDGPU::SReg_64RegClass.contains(*I)) 1909 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 1910 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1911 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 1912 else 1913 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1914 } 1915 } 1916 } 1917 1918 // Update chain and glue. 1919 RetOps[0] = Chain; 1920 if (Flag.getNode()) 1921 RetOps.push_back(Flag); 1922 1923 unsigned Opc = AMDGPUISD::ENDPGM; 1924 if (!IsWaveEnd) 1925 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 1926 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 1927 } 1928 1929 SDValue SITargetLowering::LowerCallResult( 1930 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 1931 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1932 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 1933 SDValue ThisVal) const { 1934 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 1935 1936 // Assign locations to each value returned by this call. 1937 SmallVector<CCValAssign, 16> RVLocs; 1938 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 1939 *DAG.getContext()); 1940 CCInfo.AnalyzeCallResult(Ins, RetCC); 1941 1942 // Copy all of the result registers out of their specified physreg. 1943 for (unsigned i = 0; i != RVLocs.size(); ++i) { 1944 CCValAssign VA = RVLocs[i]; 1945 SDValue Val; 1946 1947 if (VA.isRegLoc()) { 1948 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 1949 Chain = Val.getValue(1); 1950 InFlag = Val.getValue(2); 1951 } else if (VA.isMemLoc()) { 1952 report_fatal_error("TODO: return values in memory"); 1953 } else 1954 llvm_unreachable("unknown argument location type"); 1955 1956 switch (VA.getLocInfo()) { 1957 case CCValAssign::Full: 1958 break; 1959 case CCValAssign::BCvt: 1960 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 1961 break; 1962 case CCValAssign::ZExt: 1963 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 1964 DAG.getValueType(VA.getValVT())); 1965 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1966 break; 1967 case CCValAssign::SExt: 1968 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 1969 DAG.getValueType(VA.getValVT())); 1970 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1971 break; 1972 case CCValAssign::AExt: 1973 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 1974 break; 1975 default: 1976 llvm_unreachable("Unknown loc info!"); 1977 } 1978 1979 InVals.push_back(Val); 1980 } 1981 1982 return Chain; 1983 } 1984 1985 // Add code to pass special inputs required depending on used features separate 1986 // from the explicit user arguments present in the IR. 1987 void SITargetLowering::passSpecialInputs( 1988 CallLoweringInfo &CLI, 1989 const SIMachineFunctionInfo &Info, 1990 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 1991 SmallVectorImpl<SDValue> &MemOpChains, 1992 SDValue Chain, 1993 SDValue StackPtr) const { 1994 // If we don't have a call site, this was a call inserted by 1995 // legalization. These can never use special inputs. 1996 if (!CLI.CS) 1997 return; 1998 1999 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2000 assert(CalleeFunc); 2001 2002 SelectionDAG &DAG = CLI.DAG; 2003 const SDLoc &DL = CLI.DL; 2004 2005 const SISubtarget *ST = getSubtarget(); 2006 const SIRegisterInfo *TRI = ST->getRegisterInfo(); 2007 2008 auto &ArgUsageInfo = 2009 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2010 const AMDGPUFunctionArgInfo &CalleeArgInfo 2011 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2012 2013 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2014 2015 // TODO: Unify with private memory register handling. This is complicated by 2016 // the fact that at least in kernels, the input argument is not necessarily 2017 // in the same location as the input. 2018 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2019 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2020 AMDGPUFunctionArgInfo::QUEUE_PTR, 2021 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2022 AMDGPUFunctionArgInfo::DISPATCH_ID, 2023 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2024 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2025 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2026 AMDGPUFunctionArgInfo::WORKITEM_ID_X, 2027 AMDGPUFunctionArgInfo::WORKITEM_ID_Y, 2028 AMDGPUFunctionArgInfo::WORKITEM_ID_Z, 2029 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2030 }; 2031 2032 for (auto InputID : InputRegs) { 2033 const ArgDescriptor *OutgoingArg; 2034 const TargetRegisterClass *ArgRC; 2035 2036 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2037 if (!OutgoingArg) 2038 continue; 2039 2040 const ArgDescriptor *IncomingArg; 2041 const TargetRegisterClass *IncomingArgRC; 2042 std::tie(IncomingArg, IncomingArgRC) 2043 = CallerArgInfo.getPreloadedValue(InputID); 2044 assert(IncomingArgRC == ArgRC); 2045 2046 // All special arguments are ints for now. 2047 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2048 SDValue InputReg; 2049 2050 if (IncomingArg) { 2051 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2052 } else { 2053 // The implicit arg ptr is special because it doesn't have a corresponding 2054 // input for kernels, and is computed from the kernarg segment pointer. 2055 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2056 InputReg = getImplicitArgPtr(DAG, DL); 2057 } 2058 2059 if (OutgoingArg->isRegister()) { 2060 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2061 } else { 2062 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr, 2063 InputReg, 2064 OutgoingArg->getStackOffset()); 2065 MemOpChains.push_back(ArgStore); 2066 } 2067 } 2068 } 2069 2070 static bool canGuaranteeTCO(CallingConv::ID CC) { 2071 return CC == CallingConv::Fast; 2072 } 2073 2074 /// Return true if we might ever do TCO for calls with this calling convention. 2075 static bool mayTailCallThisCC(CallingConv::ID CC) { 2076 switch (CC) { 2077 case CallingConv::C: 2078 return true; 2079 default: 2080 return canGuaranteeTCO(CC); 2081 } 2082 } 2083 2084 bool SITargetLowering::isEligibleForTailCallOptimization( 2085 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2086 const SmallVectorImpl<ISD::OutputArg> &Outs, 2087 const SmallVectorImpl<SDValue> &OutVals, 2088 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2089 if (!mayTailCallThisCC(CalleeCC)) 2090 return false; 2091 2092 MachineFunction &MF = DAG.getMachineFunction(); 2093 const Function &CallerF = MF.getFunction(); 2094 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2095 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2096 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2097 2098 // Kernels aren't callable, and don't have a live in return address so it 2099 // doesn't make sense to do a tail call with entry functions. 2100 if (!CallerPreserved) 2101 return false; 2102 2103 bool CCMatch = CallerCC == CalleeCC; 2104 2105 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2106 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2107 return true; 2108 return false; 2109 } 2110 2111 // TODO: Can we handle var args? 2112 if (IsVarArg) 2113 return false; 2114 2115 for (const Argument &Arg : CallerF.args()) { 2116 if (Arg.hasByValAttr()) 2117 return false; 2118 } 2119 2120 LLVMContext &Ctx = *DAG.getContext(); 2121 2122 // Check that the call results are passed in the same way. 2123 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2124 CCAssignFnForCall(CalleeCC, IsVarArg), 2125 CCAssignFnForCall(CallerCC, IsVarArg))) 2126 return false; 2127 2128 // The callee has to preserve all registers the caller needs to preserve. 2129 if (!CCMatch) { 2130 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2131 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2132 return false; 2133 } 2134 2135 // Nothing more to check if the callee is taking no arguments. 2136 if (Outs.empty()) 2137 return true; 2138 2139 SmallVector<CCValAssign, 16> ArgLocs; 2140 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2141 2142 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2143 2144 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2145 // If the stack arguments for this call do not fit into our own save area then 2146 // the call cannot be made tail. 2147 // TODO: Is this really necessary? 2148 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2149 return false; 2150 2151 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2152 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2153 } 2154 2155 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2156 if (!CI->isTailCall()) 2157 return false; 2158 2159 const Function *ParentFn = CI->getParent()->getParent(); 2160 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2161 return false; 2162 2163 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2164 return (Attr.getValueAsString() != "true"); 2165 } 2166 2167 // The wave scratch offset register is used as the global base pointer. 2168 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2169 SmallVectorImpl<SDValue> &InVals) const { 2170 SelectionDAG &DAG = CLI.DAG; 2171 const SDLoc &DL = CLI.DL; 2172 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2173 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2174 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2175 SDValue Chain = CLI.Chain; 2176 SDValue Callee = CLI.Callee; 2177 bool &IsTailCall = CLI.IsTailCall; 2178 CallingConv::ID CallConv = CLI.CallConv; 2179 bool IsVarArg = CLI.IsVarArg; 2180 bool IsSibCall = false; 2181 bool IsThisReturn = false; 2182 MachineFunction &MF = DAG.getMachineFunction(); 2183 2184 if (IsVarArg) { 2185 return lowerUnhandledCall(CLI, InVals, 2186 "unsupported call to variadic function "); 2187 } 2188 2189 if (!CLI.CS.getCalledFunction()) { 2190 return lowerUnhandledCall(CLI, InVals, 2191 "unsupported indirect call to function "); 2192 } 2193 2194 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2195 return lowerUnhandledCall(CLI, InVals, 2196 "unsupported required tail call to function "); 2197 } 2198 2199 // The first 4 bytes are reserved for the callee's emergency stack slot. 2200 const unsigned CalleeUsableStackOffset = 4; 2201 2202 if (IsTailCall) { 2203 IsTailCall = isEligibleForTailCallOptimization( 2204 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2205 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2206 report_fatal_error("failed to perform tail call elimination on a call " 2207 "site marked musttail"); 2208 } 2209 2210 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2211 2212 // A sibling call is one where we're under the usual C ABI and not planning 2213 // to change that but can still do a tail call: 2214 if (!TailCallOpt && IsTailCall) 2215 IsSibCall = true; 2216 2217 if (IsTailCall) 2218 ++NumTailCalls; 2219 } 2220 2221 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) { 2222 // FIXME: Remove this hack for function pointer types after removing 2223 // support of old address space mapping. In the new address space 2224 // mapping the pointer in default address space is 64 bit, therefore 2225 // does not need this hack. 2226 if (Callee.getValueType() == MVT::i32) { 2227 const GlobalValue *GV = GA->getGlobal(); 2228 Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false, 2229 GA->getTargetFlags()); 2230 } 2231 } 2232 assert(Callee.getValueType() == MVT::i64); 2233 2234 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2235 2236 // Analyze operands of the call, assigning locations to each operand. 2237 SmallVector<CCValAssign, 16> ArgLocs; 2238 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2239 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2240 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2241 2242 // Get a count of how many bytes are to be pushed on the stack. 2243 unsigned NumBytes = CCInfo.getNextStackOffset(); 2244 2245 if (IsSibCall) { 2246 // Since we're not changing the ABI to make this a tail call, the memory 2247 // operands are already available in the caller's incoming argument space. 2248 NumBytes = 0; 2249 } 2250 2251 // FPDiff is the byte offset of the call's argument area from the callee's. 2252 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2253 // by this amount for a tail call. In a sibling call it must be 0 because the 2254 // caller will deallocate the entire stack and the callee still expects its 2255 // arguments to begin at SP+0. Completely unused for non-tail calls. 2256 int32_t FPDiff = 0; 2257 MachineFrameInfo &MFI = MF.getFrameInfo(); 2258 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2259 2260 SDValue CallerSavedFP; 2261 2262 // Adjust the stack pointer for the new arguments... 2263 // These operations are automatically eliminated by the prolog/epilog pass 2264 if (!IsSibCall) { 2265 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2266 2267 unsigned OffsetReg = Info->getScratchWaveOffsetReg(); 2268 2269 // In the HSA case, this should be an identity copy. 2270 SDValue ScratchRSrcReg 2271 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2272 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2273 2274 // TODO: Don't hardcode these registers and get from the callee function. 2275 SDValue ScratchWaveOffsetReg 2276 = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32); 2277 RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg); 2278 2279 if (!Info->isEntryFunction()) { 2280 // Avoid clobbering this function's FP value. In the current convention 2281 // callee will overwrite this, so do save/restore around the call site. 2282 CallerSavedFP = DAG.getCopyFromReg(Chain, DL, 2283 Info->getFrameOffsetReg(), MVT::i32); 2284 } 2285 } 2286 2287 // Stack pointer relative accesses are done by changing the offset SGPR. This 2288 // is just the VGPR offset component. 2289 SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32); 2290 2291 SmallVector<SDValue, 8> MemOpChains; 2292 MVT PtrVT = MVT::i32; 2293 2294 // Walk the register/memloc assignments, inserting copies/loads. 2295 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2296 ++i, ++realArgIdx) { 2297 CCValAssign &VA = ArgLocs[i]; 2298 SDValue Arg = OutVals[realArgIdx]; 2299 2300 // Promote the value if needed. 2301 switch (VA.getLocInfo()) { 2302 case CCValAssign::Full: 2303 break; 2304 case CCValAssign::BCvt: 2305 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2306 break; 2307 case CCValAssign::ZExt: 2308 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2309 break; 2310 case CCValAssign::SExt: 2311 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2312 break; 2313 case CCValAssign::AExt: 2314 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2315 break; 2316 case CCValAssign::FPExt: 2317 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2318 break; 2319 default: 2320 llvm_unreachable("Unknown loc info!"); 2321 } 2322 2323 if (VA.isRegLoc()) { 2324 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2325 } else { 2326 assert(VA.isMemLoc()); 2327 2328 SDValue DstAddr; 2329 MachinePointerInfo DstInfo; 2330 2331 unsigned LocMemOffset = VA.getLocMemOffset(); 2332 int32_t Offset = LocMemOffset; 2333 2334 SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset); 2335 2336 if (IsTailCall) { 2337 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2338 unsigned OpSize = Flags.isByVal() ? 2339 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2340 2341 Offset = Offset + FPDiff; 2342 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2343 2344 DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT), 2345 StackPtr); 2346 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2347 2348 // Make sure any stack arguments overlapping with where we're storing 2349 // are loaded before this eventual operation. Otherwise they'll be 2350 // clobbered. 2351 2352 // FIXME: Why is this really necessary? This seems to just result in a 2353 // lot of code to copy the stack and write them back to the same 2354 // locations, which are supposed to be immutable? 2355 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2356 } else { 2357 DstAddr = PtrOff; 2358 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2359 } 2360 2361 if (Outs[i].Flags.isByVal()) { 2362 SDValue SizeNode = 2363 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2364 SDValue Cpy = DAG.getMemcpy( 2365 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2366 /*isVol = */ false, /*AlwaysInline = */ true, 2367 /*isTailCall = */ false, DstInfo, 2368 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2369 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS)))); 2370 2371 MemOpChains.push_back(Cpy); 2372 } else { 2373 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 2374 MemOpChains.push_back(Store); 2375 } 2376 } 2377 } 2378 2379 // Copy special input registers after user input arguments. 2380 passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr); 2381 2382 if (!MemOpChains.empty()) 2383 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2384 2385 // Build a sequence of copy-to-reg nodes chained together with token chain 2386 // and flag operands which copy the outgoing args into the appropriate regs. 2387 SDValue InFlag; 2388 for (auto &RegToPass : RegsToPass) { 2389 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2390 RegToPass.second, InFlag); 2391 InFlag = Chain.getValue(1); 2392 } 2393 2394 2395 SDValue PhysReturnAddrReg; 2396 if (IsTailCall) { 2397 // Since the return is being combined with the call, we need to pass on the 2398 // return address. 2399 2400 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2401 SDValue ReturnAddrReg = CreateLiveInRegister( 2402 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2403 2404 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2405 MVT::i64); 2406 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2407 InFlag = Chain.getValue(1); 2408 } 2409 2410 // We don't usually want to end the call-sequence here because we would tidy 2411 // the frame up *after* the call, however in the ABI-changing tail-call case 2412 // we've carefully laid out the parameters so that when sp is reset they'll be 2413 // in the correct location. 2414 if (IsTailCall && !IsSibCall) { 2415 Chain = DAG.getCALLSEQ_END(Chain, 2416 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2417 DAG.getTargetConstant(0, DL, MVT::i32), 2418 InFlag, DL); 2419 InFlag = Chain.getValue(1); 2420 } 2421 2422 std::vector<SDValue> Ops; 2423 Ops.push_back(Chain); 2424 Ops.push_back(Callee); 2425 2426 if (IsTailCall) { 2427 // Each tail call may have to adjust the stack by a different amount, so 2428 // this information must travel along with the operation for eventual 2429 // consumption by emitEpilogue. 2430 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2431 2432 Ops.push_back(PhysReturnAddrReg); 2433 } 2434 2435 // Add argument registers to the end of the list so that they are known live 2436 // into the call. 2437 for (auto &RegToPass : RegsToPass) { 2438 Ops.push_back(DAG.getRegister(RegToPass.first, 2439 RegToPass.second.getValueType())); 2440 } 2441 2442 // Add a register mask operand representing the call-preserved registers. 2443 2444 const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo(); 2445 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2446 assert(Mask && "Missing call preserved mask for calling convention"); 2447 Ops.push_back(DAG.getRegisterMask(Mask)); 2448 2449 if (InFlag.getNode()) 2450 Ops.push_back(InFlag); 2451 2452 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2453 2454 // If we're doing a tall call, use a TC_RETURN here rather than an 2455 // actual call instruction. 2456 if (IsTailCall) { 2457 MFI.setHasTailCall(); 2458 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2459 } 2460 2461 // Returns a chain and a flag for retval copy to use. 2462 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2463 Chain = Call.getValue(0); 2464 InFlag = Call.getValue(1); 2465 2466 if (CallerSavedFP) { 2467 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32); 2468 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag); 2469 InFlag = Chain.getValue(1); 2470 } 2471 2472 uint64_t CalleePopBytes = NumBytes; 2473 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2474 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2475 InFlag, DL); 2476 if (!Ins.empty()) 2477 InFlag = Chain.getValue(1); 2478 2479 // Handle result values, copying them out of physregs into vregs that we 2480 // return. 2481 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2482 InVals, IsThisReturn, 2483 IsThisReturn ? OutVals[0] : SDValue()); 2484 } 2485 2486 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2487 SelectionDAG &DAG) const { 2488 unsigned Reg = StringSwitch<unsigned>(RegName) 2489 .Case("m0", AMDGPU::M0) 2490 .Case("exec", AMDGPU::EXEC) 2491 .Case("exec_lo", AMDGPU::EXEC_LO) 2492 .Case("exec_hi", AMDGPU::EXEC_HI) 2493 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2494 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2495 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2496 .Default(AMDGPU::NoRegister); 2497 2498 if (Reg == AMDGPU::NoRegister) { 2499 report_fatal_error(Twine("invalid register name \"" 2500 + StringRef(RegName) + "\".")); 2501 2502 } 2503 2504 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS && 2505 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2506 report_fatal_error(Twine("invalid register \"" 2507 + StringRef(RegName) + "\" for subtarget.")); 2508 } 2509 2510 switch (Reg) { 2511 case AMDGPU::M0: 2512 case AMDGPU::EXEC_LO: 2513 case AMDGPU::EXEC_HI: 2514 case AMDGPU::FLAT_SCR_LO: 2515 case AMDGPU::FLAT_SCR_HI: 2516 if (VT.getSizeInBits() == 32) 2517 return Reg; 2518 break; 2519 case AMDGPU::EXEC: 2520 case AMDGPU::FLAT_SCR: 2521 if (VT.getSizeInBits() == 64) 2522 return Reg; 2523 break; 2524 default: 2525 llvm_unreachable("missing register type checking"); 2526 } 2527 2528 report_fatal_error(Twine("invalid type for register \"" 2529 + StringRef(RegName) + "\".")); 2530 } 2531 2532 // If kill is not the last instruction, split the block so kill is always a 2533 // proper terminator. 2534 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2535 MachineBasicBlock *BB) const { 2536 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2537 2538 MachineBasicBlock::iterator SplitPoint(&MI); 2539 ++SplitPoint; 2540 2541 if (SplitPoint == BB->end()) { 2542 // Don't bother with a new block. 2543 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2544 return BB; 2545 } 2546 2547 MachineFunction *MF = BB->getParent(); 2548 MachineBasicBlock *SplitBB 2549 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2550 2551 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2552 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2553 2554 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2555 BB->addSuccessor(SplitBB); 2556 2557 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2558 return SplitBB; 2559 } 2560 2561 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 2562 // wavefront. If the value is uniform and just happens to be in a VGPR, this 2563 // will only do one iteration. In the worst case, this will loop 64 times. 2564 // 2565 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 2566 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 2567 const SIInstrInfo *TII, 2568 MachineRegisterInfo &MRI, 2569 MachineBasicBlock &OrigBB, 2570 MachineBasicBlock &LoopBB, 2571 const DebugLoc &DL, 2572 const MachineOperand &IdxReg, 2573 unsigned InitReg, 2574 unsigned ResultReg, 2575 unsigned PhiReg, 2576 unsigned InitSaveExecReg, 2577 int Offset, 2578 bool UseGPRIdxMode, 2579 bool IsIndirectSrc) { 2580 MachineBasicBlock::iterator I = LoopBB.begin(); 2581 2582 unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2583 unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2584 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2585 unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass); 2586 2587 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 2588 .addReg(InitReg) 2589 .addMBB(&OrigBB) 2590 .addReg(ResultReg) 2591 .addMBB(&LoopBB); 2592 2593 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 2594 .addReg(InitSaveExecReg) 2595 .addMBB(&OrigBB) 2596 .addReg(NewExec) 2597 .addMBB(&LoopBB); 2598 2599 // Read the next variant <- also loop target. 2600 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 2601 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 2602 2603 // Compare the just read M0 value to all possible Idx values. 2604 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 2605 .addReg(CurrentIdxReg) 2606 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 2607 2608 // Update EXEC, save the original EXEC value to VCC. 2609 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec) 2610 .addReg(CondReg, RegState::Kill); 2611 2612 MRI.setSimpleHint(NewExec, CondReg); 2613 2614 if (UseGPRIdxMode) { 2615 unsigned IdxReg; 2616 if (Offset == 0) { 2617 IdxReg = CurrentIdxReg; 2618 } else { 2619 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 2620 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 2621 .addReg(CurrentIdxReg, RegState::Kill) 2622 .addImm(Offset); 2623 } 2624 unsigned IdxMode = IsIndirectSrc ? 2625 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2626 MachineInstr *SetOn = 2627 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2628 .addReg(IdxReg, RegState::Kill) 2629 .addImm(IdxMode); 2630 SetOn->getOperand(3).setIsUndef(); 2631 } else { 2632 // Move index from VCC into M0 2633 if (Offset == 0) { 2634 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2635 .addReg(CurrentIdxReg, RegState::Kill); 2636 } else { 2637 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2638 .addReg(CurrentIdxReg, RegState::Kill) 2639 .addImm(Offset); 2640 } 2641 } 2642 2643 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 2644 MachineInstr *InsertPt = 2645 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC) 2646 .addReg(AMDGPU::EXEC) 2647 .addReg(NewExec); 2648 2649 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 2650 // s_cbranch_scc0? 2651 2652 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 2653 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 2654 .addMBB(&LoopBB); 2655 2656 return InsertPt->getIterator(); 2657 } 2658 2659 // This has slightly sub-optimal regalloc when the source vector is killed by 2660 // the read. The register allocator does not understand that the kill is 2661 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 2662 // subregister from it, using 1 more VGPR than necessary. This was saved when 2663 // this was expanded after register allocation. 2664 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 2665 MachineBasicBlock &MBB, 2666 MachineInstr &MI, 2667 unsigned InitResultReg, 2668 unsigned PhiReg, 2669 int Offset, 2670 bool UseGPRIdxMode, 2671 bool IsIndirectSrc) { 2672 MachineFunction *MF = MBB.getParent(); 2673 MachineRegisterInfo &MRI = MF->getRegInfo(); 2674 const DebugLoc &DL = MI.getDebugLoc(); 2675 MachineBasicBlock::iterator I(&MI); 2676 2677 unsigned DstReg = MI.getOperand(0).getReg(); 2678 unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 2679 unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 2680 2681 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 2682 2683 // Save the EXEC mask 2684 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec) 2685 .addReg(AMDGPU::EXEC); 2686 2687 // To insert the loop we need to split the block. Move everything after this 2688 // point to a new block, and insert a new empty block between the two. 2689 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 2690 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 2691 MachineFunction::iterator MBBI(MBB); 2692 ++MBBI; 2693 2694 MF->insert(MBBI, LoopBB); 2695 MF->insert(MBBI, RemainderBB); 2696 2697 LoopBB->addSuccessor(LoopBB); 2698 LoopBB->addSuccessor(RemainderBB); 2699 2700 // Move the rest of the block into a new block. 2701 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 2702 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 2703 2704 MBB.addSuccessor(LoopBB); 2705 2706 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2707 2708 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 2709 InitResultReg, DstReg, PhiReg, TmpExec, 2710 Offset, UseGPRIdxMode, IsIndirectSrc); 2711 2712 MachineBasicBlock::iterator First = RemainderBB->begin(); 2713 BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) 2714 .addReg(SaveExec); 2715 2716 return InsPt; 2717 } 2718 2719 // Returns subreg index, offset 2720 static std::pair<unsigned, int> 2721 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 2722 const TargetRegisterClass *SuperRC, 2723 unsigned VecReg, 2724 int Offset) { 2725 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 2726 2727 // Skip out of bounds offsets, or else we would end up using an undefined 2728 // register. 2729 if (Offset >= NumElts || Offset < 0) 2730 return std::make_pair(AMDGPU::sub0, Offset); 2731 2732 return std::make_pair(AMDGPU::sub0 + Offset, 0); 2733 } 2734 2735 // Return true if the index is an SGPR and was set. 2736 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 2737 MachineRegisterInfo &MRI, 2738 MachineInstr &MI, 2739 int Offset, 2740 bool UseGPRIdxMode, 2741 bool IsIndirectSrc) { 2742 MachineBasicBlock *MBB = MI.getParent(); 2743 const DebugLoc &DL = MI.getDebugLoc(); 2744 MachineBasicBlock::iterator I(&MI); 2745 2746 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2747 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 2748 2749 assert(Idx->getReg() != AMDGPU::NoRegister); 2750 2751 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 2752 return false; 2753 2754 if (UseGPRIdxMode) { 2755 unsigned IdxMode = IsIndirectSrc ? 2756 VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE; 2757 if (Offset == 0) { 2758 MachineInstr *SetOn = 2759 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2760 .add(*Idx) 2761 .addImm(IdxMode); 2762 2763 SetOn->getOperand(3).setIsUndef(); 2764 } else { 2765 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 2766 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 2767 .add(*Idx) 2768 .addImm(Offset); 2769 MachineInstr *SetOn = 2770 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 2771 .addReg(Tmp, RegState::Kill) 2772 .addImm(IdxMode); 2773 2774 SetOn->getOperand(3).setIsUndef(); 2775 } 2776 2777 return true; 2778 } 2779 2780 if (Offset == 0) { 2781 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 2782 .add(*Idx); 2783 } else { 2784 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 2785 .add(*Idx) 2786 .addImm(Offset); 2787 } 2788 2789 return true; 2790 } 2791 2792 // Control flow needs to be inserted if indexing with a VGPR. 2793 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 2794 MachineBasicBlock &MBB, 2795 const SISubtarget &ST) { 2796 const SIInstrInfo *TII = ST.getInstrInfo(); 2797 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2798 MachineFunction *MF = MBB.getParent(); 2799 MachineRegisterInfo &MRI = MF->getRegInfo(); 2800 2801 unsigned Dst = MI.getOperand(0).getReg(); 2802 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 2803 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2804 2805 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 2806 2807 unsigned SubReg; 2808 std::tie(SubReg, Offset) 2809 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 2810 2811 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2812 2813 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 2814 MachineBasicBlock::iterator I(&MI); 2815 const DebugLoc &DL = MI.getDebugLoc(); 2816 2817 if (UseGPRIdxMode) { 2818 // TODO: Look at the uses to avoid the copy. This may require rescheduling 2819 // to avoid interfering with other uses, so probably requires a new 2820 // optimization pass. 2821 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2822 .addReg(SrcReg, RegState::Undef, SubReg) 2823 .addReg(SrcReg, RegState::Implicit) 2824 .addReg(AMDGPU::M0, RegState::Implicit); 2825 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2826 } else { 2827 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2828 .addReg(SrcReg, RegState::Undef, SubReg) 2829 .addReg(SrcReg, RegState::Implicit); 2830 } 2831 2832 MI.eraseFromParent(); 2833 2834 return &MBB; 2835 } 2836 2837 const DebugLoc &DL = MI.getDebugLoc(); 2838 MachineBasicBlock::iterator I(&MI); 2839 2840 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2841 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 2842 2843 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 2844 2845 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 2846 Offset, UseGPRIdxMode, true); 2847 MachineBasicBlock *LoopBB = InsPt->getParent(); 2848 2849 if (UseGPRIdxMode) { 2850 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 2851 .addReg(SrcReg, RegState::Undef, SubReg) 2852 .addReg(SrcReg, RegState::Implicit) 2853 .addReg(AMDGPU::M0, RegState::Implicit); 2854 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2855 } else { 2856 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 2857 .addReg(SrcReg, RegState::Undef, SubReg) 2858 .addReg(SrcReg, RegState::Implicit); 2859 } 2860 2861 MI.eraseFromParent(); 2862 2863 return LoopBB; 2864 } 2865 2866 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 2867 const TargetRegisterClass *VecRC) { 2868 switch (TRI.getRegSizeInBits(*VecRC)) { 2869 case 32: // 4 bytes 2870 return AMDGPU::V_MOVRELD_B32_V1; 2871 case 64: // 8 bytes 2872 return AMDGPU::V_MOVRELD_B32_V2; 2873 case 128: // 16 bytes 2874 return AMDGPU::V_MOVRELD_B32_V4; 2875 case 256: // 32 bytes 2876 return AMDGPU::V_MOVRELD_B32_V8; 2877 case 512: // 64 bytes 2878 return AMDGPU::V_MOVRELD_B32_V16; 2879 default: 2880 llvm_unreachable("unsupported size for MOVRELD pseudos"); 2881 } 2882 } 2883 2884 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 2885 MachineBasicBlock &MBB, 2886 const SISubtarget &ST) { 2887 const SIInstrInfo *TII = ST.getInstrInfo(); 2888 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 2889 MachineFunction *MF = MBB.getParent(); 2890 MachineRegisterInfo &MRI = MF->getRegInfo(); 2891 2892 unsigned Dst = MI.getOperand(0).getReg(); 2893 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 2894 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 2895 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 2896 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 2897 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 2898 2899 // This can be an immediate, but will be folded later. 2900 assert(Val->getReg()); 2901 2902 unsigned SubReg; 2903 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 2904 SrcVec->getReg(), 2905 Offset); 2906 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 2907 2908 if (Idx->getReg() == AMDGPU::NoRegister) { 2909 MachineBasicBlock::iterator I(&MI); 2910 const DebugLoc &DL = MI.getDebugLoc(); 2911 2912 assert(Offset == 0); 2913 2914 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 2915 .add(*SrcVec) 2916 .add(*Val) 2917 .addImm(SubReg); 2918 2919 MI.eraseFromParent(); 2920 return &MBB; 2921 } 2922 2923 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 2924 MachineBasicBlock::iterator I(&MI); 2925 const DebugLoc &DL = MI.getDebugLoc(); 2926 2927 if (UseGPRIdxMode) { 2928 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2929 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 2930 .add(*Val) 2931 .addReg(Dst, RegState::ImplicitDefine) 2932 .addReg(SrcVec->getReg(), RegState::Implicit) 2933 .addReg(AMDGPU::M0, RegState::Implicit); 2934 2935 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2936 } else { 2937 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2938 2939 BuildMI(MBB, I, DL, MovRelDesc) 2940 .addReg(Dst, RegState::Define) 2941 .addReg(SrcVec->getReg()) 2942 .add(*Val) 2943 .addImm(SubReg - AMDGPU::sub0); 2944 } 2945 2946 MI.eraseFromParent(); 2947 return &MBB; 2948 } 2949 2950 if (Val->isReg()) 2951 MRI.clearKillFlags(Val->getReg()); 2952 2953 const DebugLoc &DL = MI.getDebugLoc(); 2954 2955 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 2956 2957 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 2958 Offset, UseGPRIdxMode, false); 2959 MachineBasicBlock *LoopBB = InsPt->getParent(); 2960 2961 if (UseGPRIdxMode) { 2962 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 2963 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 2964 .add(*Val) // src0 2965 .addReg(Dst, RegState::ImplicitDefine) 2966 .addReg(PhiReg, RegState::Implicit) 2967 .addReg(AMDGPU::M0, RegState::Implicit); 2968 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 2969 } else { 2970 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 2971 2972 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 2973 .addReg(Dst, RegState::Define) 2974 .addReg(PhiReg) 2975 .add(*Val) 2976 .addImm(SubReg - AMDGPU::sub0); 2977 } 2978 2979 MI.eraseFromParent(); 2980 2981 return LoopBB; 2982 } 2983 2984 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 2985 MachineInstr &MI, MachineBasicBlock *BB) const { 2986 2987 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2988 MachineFunction *MF = BB->getParent(); 2989 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 2990 2991 if (TII->isMIMG(MI)) { 2992 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 2993 report_fatal_error("missing mem operand from MIMG instruction"); 2994 } 2995 // Add a memoperand for mimg instructions so that they aren't assumed to 2996 // be ordered memory instuctions. 2997 2998 return BB; 2999 } 3000 3001 switch (MI.getOpcode()) { 3002 case AMDGPU::S_ADD_U64_PSEUDO: 3003 case AMDGPU::S_SUB_U64_PSEUDO: { 3004 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3005 const DebugLoc &DL = MI.getDebugLoc(); 3006 3007 MachineOperand &Dest = MI.getOperand(0); 3008 MachineOperand &Src0 = MI.getOperand(1); 3009 MachineOperand &Src1 = MI.getOperand(2); 3010 3011 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3012 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3013 3014 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3015 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3016 &AMDGPU::SReg_32_XM0RegClass); 3017 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3018 Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3019 &AMDGPU::SReg_32_XM0RegClass); 3020 3021 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3022 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0, 3023 &AMDGPU::SReg_32_XM0RegClass); 3024 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3025 Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1, 3026 &AMDGPU::SReg_32_XM0RegClass); 3027 3028 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3029 3030 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3031 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3032 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3033 .add(Src0Sub0) 3034 .add(Src1Sub0); 3035 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3036 .add(Src0Sub1) 3037 .add(Src1Sub1); 3038 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3039 .addReg(DestSub0) 3040 .addImm(AMDGPU::sub0) 3041 .addReg(DestSub1) 3042 .addImm(AMDGPU::sub1); 3043 MI.eraseFromParent(); 3044 return BB; 3045 } 3046 case AMDGPU::SI_INIT_M0: { 3047 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3048 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3049 .add(MI.getOperand(0)); 3050 MI.eraseFromParent(); 3051 return BB; 3052 } 3053 case AMDGPU::SI_INIT_EXEC: 3054 // This should be before all vector instructions. 3055 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3056 AMDGPU::EXEC) 3057 .addImm(MI.getOperand(0).getImm()); 3058 MI.eraseFromParent(); 3059 return BB; 3060 3061 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3062 // Extract the thread count from an SGPR input and set EXEC accordingly. 3063 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3064 // 3065 // S_BFE_U32 count, input, {shift, 7} 3066 // S_BFM_B64 exec, count, 0 3067 // S_CMP_EQ_U32 count, 64 3068 // S_CMOV_B64 exec, -1 3069 MachineInstr *FirstMI = &*BB->begin(); 3070 MachineRegisterInfo &MRI = MF->getRegInfo(); 3071 unsigned InputReg = MI.getOperand(0).getReg(); 3072 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3073 bool Found = false; 3074 3075 // Move the COPY of the input reg to the beginning, so that we can use it. 3076 for (auto I = BB->begin(); I != &MI; I++) { 3077 if (I->getOpcode() != TargetOpcode::COPY || 3078 I->getOperand(0).getReg() != InputReg) 3079 continue; 3080 3081 if (I == FirstMI) { 3082 FirstMI = &*++BB->begin(); 3083 } else { 3084 I->removeFromParent(); 3085 BB->insert(FirstMI, &*I); 3086 } 3087 Found = true; 3088 break; 3089 } 3090 assert(Found); 3091 (void)Found; 3092 3093 // This should be before all vector instructions. 3094 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3095 .addReg(InputReg) 3096 .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000); 3097 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64), 3098 AMDGPU::EXEC) 3099 .addReg(CountReg) 3100 .addImm(0); 3101 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3102 .addReg(CountReg, RegState::Kill) 3103 .addImm(64); 3104 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64), 3105 AMDGPU::EXEC) 3106 .addImm(-1); 3107 MI.eraseFromParent(); 3108 return BB; 3109 } 3110 3111 case AMDGPU::GET_GROUPSTATICSIZE: { 3112 DebugLoc DL = MI.getDebugLoc(); 3113 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3114 .add(MI.getOperand(0)) 3115 .addImm(MFI->getLDSSize()); 3116 MI.eraseFromParent(); 3117 return BB; 3118 } 3119 case AMDGPU::SI_INDIRECT_SRC_V1: 3120 case AMDGPU::SI_INDIRECT_SRC_V2: 3121 case AMDGPU::SI_INDIRECT_SRC_V4: 3122 case AMDGPU::SI_INDIRECT_SRC_V8: 3123 case AMDGPU::SI_INDIRECT_SRC_V16: 3124 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3125 case AMDGPU::SI_INDIRECT_DST_V1: 3126 case AMDGPU::SI_INDIRECT_DST_V2: 3127 case AMDGPU::SI_INDIRECT_DST_V4: 3128 case AMDGPU::SI_INDIRECT_DST_V8: 3129 case AMDGPU::SI_INDIRECT_DST_V16: 3130 return emitIndirectDst(MI, *BB, *getSubtarget()); 3131 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3132 case AMDGPU::SI_KILL_I1_PSEUDO: 3133 return splitKillBlock(MI, BB); 3134 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3135 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3136 3137 unsigned Dst = MI.getOperand(0).getReg(); 3138 unsigned Src0 = MI.getOperand(1).getReg(); 3139 unsigned Src1 = MI.getOperand(2).getReg(); 3140 const DebugLoc &DL = MI.getDebugLoc(); 3141 unsigned SrcCond = MI.getOperand(3).getReg(); 3142 3143 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3144 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3145 unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass); 3146 3147 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3148 .addReg(SrcCond); 3149 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3150 .addReg(Src0, 0, AMDGPU::sub0) 3151 .addReg(Src1, 0, AMDGPU::sub0) 3152 .addReg(SrcCondCopy); 3153 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3154 .addReg(Src0, 0, AMDGPU::sub1) 3155 .addReg(Src1, 0, AMDGPU::sub1) 3156 .addReg(SrcCondCopy); 3157 3158 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3159 .addReg(DstLo) 3160 .addImm(AMDGPU::sub0) 3161 .addReg(DstHi) 3162 .addImm(AMDGPU::sub1); 3163 MI.eraseFromParent(); 3164 return BB; 3165 } 3166 case AMDGPU::SI_BR_UNDEF: { 3167 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3168 const DebugLoc &DL = MI.getDebugLoc(); 3169 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3170 .add(MI.getOperand(0)); 3171 Br->getOperand(1).setIsUndef(true); // read undef SCC 3172 MI.eraseFromParent(); 3173 return BB; 3174 } 3175 case AMDGPU::ADJCALLSTACKUP: 3176 case AMDGPU::ADJCALLSTACKDOWN: { 3177 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3178 MachineInstrBuilder MIB(*MF, &MI); 3179 3180 // Add an implicit use of the frame offset reg to prevent the restore copy 3181 // inserted after the call from being reorderd after stack operations in the 3182 // the caller's frame. 3183 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3184 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3185 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3186 return BB; 3187 } 3188 case AMDGPU::SI_CALL_ISEL: 3189 case AMDGPU::SI_TCRETURN_ISEL: { 3190 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3191 const DebugLoc &DL = MI.getDebugLoc(); 3192 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3193 3194 MachineRegisterInfo &MRI = MF->getRegInfo(); 3195 unsigned GlobalAddrReg = MI.getOperand(0).getReg(); 3196 MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg); 3197 assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET); 3198 3199 const GlobalValue *G = PCRel->getOperand(1).getGlobal(); 3200 3201 MachineInstrBuilder MIB; 3202 if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) { 3203 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg) 3204 .add(MI.getOperand(0)) 3205 .addGlobalAddress(G); 3206 } else { 3207 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN)) 3208 .add(MI.getOperand(0)) 3209 .addGlobalAddress(G); 3210 3211 // There is an additional imm operand for tcreturn, but it should be in the 3212 // right place already. 3213 } 3214 3215 for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) 3216 MIB.add(MI.getOperand(I)); 3217 3218 MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end()); 3219 MI.eraseFromParent(); 3220 return BB; 3221 } 3222 default: 3223 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3224 } 3225 } 3226 3227 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3228 return isTypeLegal(VT.getScalarType()); 3229 } 3230 3231 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3232 // This currently forces unfolding various combinations of fsub into fma with 3233 // free fneg'd operands. As long as we have fast FMA (controlled by 3234 // isFMAFasterThanFMulAndFAdd), we should perform these. 3235 3236 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3237 // most of these combines appear to be cycle neutral but save on instruction 3238 // count / code size. 3239 return true; 3240 } 3241 3242 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3243 EVT VT) const { 3244 if (!VT.isVector()) { 3245 return MVT::i1; 3246 } 3247 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3248 } 3249 3250 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3251 // TODO: Should i16 be used always if legal? For now it would force VALU 3252 // shifts. 3253 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3254 } 3255 3256 // Answering this is somewhat tricky and depends on the specific device which 3257 // have different rates for fma or all f64 operations. 3258 // 3259 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3260 // regardless of which device (although the number of cycles differs between 3261 // devices), so it is always profitable for f64. 3262 // 3263 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3264 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3265 // which we can always do even without fused FP ops since it returns the same 3266 // result as the separate operations and since it is always full 3267 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3268 // however does not support denormals, so we do report fma as faster if we have 3269 // a fast fma device and require denormals. 3270 // 3271 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3272 VT = VT.getScalarType(); 3273 3274 switch (VT.getSimpleVT().SimpleTy) { 3275 case MVT::f32: { 3276 // This is as fast on some subtargets. However, we always have full rate f32 3277 // mad available which returns the same result as the separate operations 3278 // which we should prefer over fma. We can't use this if we want to support 3279 // denormals, so only report this in these cases. 3280 if (Subtarget->hasFP32Denormals()) 3281 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3282 3283 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3284 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3285 } 3286 case MVT::f64: 3287 return true; 3288 case MVT::f16: 3289 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3290 default: 3291 break; 3292 } 3293 3294 return false; 3295 } 3296 3297 //===----------------------------------------------------------------------===// 3298 // Custom DAG Lowering Operations 3299 //===----------------------------------------------------------------------===// 3300 3301 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3302 switch (Op.getOpcode()) { 3303 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3304 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3305 case ISD::LOAD: { 3306 SDValue Result = LowerLOAD(Op, DAG); 3307 assert((!Result.getNode() || 3308 Result.getNode()->getNumValues() == 2) && 3309 "Load should return a value and a chain"); 3310 return Result; 3311 } 3312 3313 case ISD::FSIN: 3314 case ISD::FCOS: 3315 return LowerTrig(Op, DAG); 3316 case ISD::SELECT: return LowerSELECT(Op, DAG); 3317 case ISD::FDIV: return LowerFDIV(Op, DAG); 3318 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3319 case ISD::STORE: return LowerSTORE(Op, DAG); 3320 case ISD::GlobalAddress: { 3321 MachineFunction &MF = DAG.getMachineFunction(); 3322 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3323 return LowerGlobalAddress(MFI, Op, DAG); 3324 } 3325 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3326 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3327 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3328 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3329 case ISD::INSERT_VECTOR_ELT: 3330 return lowerINSERT_VECTOR_ELT(Op, DAG); 3331 case ISD::EXTRACT_VECTOR_ELT: 3332 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3333 case ISD::FP_ROUND: 3334 return lowerFP_ROUND(Op, DAG); 3335 case ISD::TRAP: 3336 case ISD::DEBUGTRAP: 3337 return lowerTRAP(Op, DAG); 3338 } 3339 return SDValue(); 3340 } 3341 3342 static unsigned getImageOpcode(unsigned IID) { 3343 switch (IID) { 3344 case Intrinsic::amdgcn_image_load: 3345 return AMDGPUISD::IMAGE_LOAD; 3346 case Intrinsic::amdgcn_image_load_mip: 3347 return AMDGPUISD::IMAGE_LOAD_MIP; 3348 3349 // Basic sample. 3350 case Intrinsic::amdgcn_image_sample: 3351 return AMDGPUISD::IMAGE_SAMPLE; 3352 case Intrinsic::amdgcn_image_sample_cl: 3353 return AMDGPUISD::IMAGE_SAMPLE_CL; 3354 case Intrinsic::amdgcn_image_sample_d: 3355 return AMDGPUISD::IMAGE_SAMPLE_D; 3356 case Intrinsic::amdgcn_image_sample_d_cl: 3357 return AMDGPUISD::IMAGE_SAMPLE_D_CL; 3358 case Intrinsic::amdgcn_image_sample_l: 3359 return AMDGPUISD::IMAGE_SAMPLE_L; 3360 case Intrinsic::amdgcn_image_sample_b: 3361 return AMDGPUISD::IMAGE_SAMPLE_B; 3362 case Intrinsic::amdgcn_image_sample_b_cl: 3363 return AMDGPUISD::IMAGE_SAMPLE_B_CL; 3364 case Intrinsic::amdgcn_image_sample_lz: 3365 return AMDGPUISD::IMAGE_SAMPLE_LZ; 3366 case Intrinsic::amdgcn_image_sample_cd: 3367 return AMDGPUISD::IMAGE_SAMPLE_CD; 3368 case Intrinsic::amdgcn_image_sample_cd_cl: 3369 return AMDGPUISD::IMAGE_SAMPLE_CD_CL; 3370 3371 // Sample with comparison. 3372 case Intrinsic::amdgcn_image_sample_c: 3373 return AMDGPUISD::IMAGE_SAMPLE_C; 3374 case Intrinsic::amdgcn_image_sample_c_cl: 3375 return AMDGPUISD::IMAGE_SAMPLE_C_CL; 3376 case Intrinsic::amdgcn_image_sample_c_d: 3377 return AMDGPUISD::IMAGE_SAMPLE_C_D; 3378 case Intrinsic::amdgcn_image_sample_c_d_cl: 3379 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL; 3380 case Intrinsic::amdgcn_image_sample_c_l: 3381 return AMDGPUISD::IMAGE_SAMPLE_C_L; 3382 case Intrinsic::amdgcn_image_sample_c_b: 3383 return AMDGPUISD::IMAGE_SAMPLE_C_B; 3384 case Intrinsic::amdgcn_image_sample_c_b_cl: 3385 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL; 3386 case Intrinsic::amdgcn_image_sample_c_lz: 3387 return AMDGPUISD::IMAGE_SAMPLE_C_LZ; 3388 case Intrinsic::amdgcn_image_sample_c_cd: 3389 return AMDGPUISD::IMAGE_SAMPLE_C_CD; 3390 case Intrinsic::amdgcn_image_sample_c_cd_cl: 3391 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL; 3392 3393 // Sample with offsets. 3394 case Intrinsic::amdgcn_image_sample_o: 3395 return AMDGPUISD::IMAGE_SAMPLE_O; 3396 case Intrinsic::amdgcn_image_sample_cl_o: 3397 return AMDGPUISD::IMAGE_SAMPLE_CL_O; 3398 case Intrinsic::amdgcn_image_sample_d_o: 3399 return AMDGPUISD::IMAGE_SAMPLE_D_O; 3400 case Intrinsic::amdgcn_image_sample_d_cl_o: 3401 return AMDGPUISD::IMAGE_SAMPLE_D_CL_O; 3402 case Intrinsic::amdgcn_image_sample_l_o: 3403 return AMDGPUISD::IMAGE_SAMPLE_L_O; 3404 case Intrinsic::amdgcn_image_sample_b_o: 3405 return AMDGPUISD::IMAGE_SAMPLE_B_O; 3406 case Intrinsic::amdgcn_image_sample_b_cl_o: 3407 return AMDGPUISD::IMAGE_SAMPLE_B_CL_O; 3408 case Intrinsic::amdgcn_image_sample_lz_o: 3409 return AMDGPUISD::IMAGE_SAMPLE_LZ_O; 3410 case Intrinsic::amdgcn_image_sample_cd_o: 3411 return AMDGPUISD::IMAGE_SAMPLE_CD_O; 3412 case Intrinsic::amdgcn_image_sample_cd_cl_o: 3413 return AMDGPUISD::IMAGE_SAMPLE_CD_CL_O; 3414 3415 // Sample with comparison and offsets. 3416 case Intrinsic::amdgcn_image_sample_c_o: 3417 return AMDGPUISD::IMAGE_SAMPLE_C_O; 3418 case Intrinsic::amdgcn_image_sample_c_cl_o: 3419 return AMDGPUISD::IMAGE_SAMPLE_C_CL_O; 3420 case Intrinsic::amdgcn_image_sample_c_d_o: 3421 return AMDGPUISD::IMAGE_SAMPLE_C_D_O; 3422 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 3423 return AMDGPUISD::IMAGE_SAMPLE_C_D_CL_O; 3424 case Intrinsic::amdgcn_image_sample_c_l_o: 3425 return AMDGPUISD::IMAGE_SAMPLE_C_L_O; 3426 case Intrinsic::amdgcn_image_sample_c_b_o: 3427 return AMDGPUISD::IMAGE_SAMPLE_C_B_O; 3428 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 3429 return AMDGPUISD::IMAGE_SAMPLE_C_B_CL_O; 3430 case Intrinsic::amdgcn_image_sample_c_lz_o: 3431 return AMDGPUISD::IMAGE_SAMPLE_C_LZ_O; 3432 case Intrinsic::amdgcn_image_sample_c_cd_o: 3433 return AMDGPUISD::IMAGE_SAMPLE_C_CD_O; 3434 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 3435 return AMDGPUISD::IMAGE_SAMPLE_C_CD_CL_O; 3436 3437 // Basic gather4. 3438 case Intrinsic::amdgcn_image_gather4: 3439 return AMDGPUISD::IMAGE_GATHER4; 3440 case Intrinsic::amdgcn_image_gather4_cl: 3441 return AMDGPUISD::IMAGE_GATHER4_CL; 3442 case Intrinsic::amdgcn_image_gather4_l: 3443 return AMDGPUISD::IMAGE_GATHER4_L; 3444 case Intrinsic::amdgcn_image_gather4_b: 3445 return AMDGPUISD::IMAGE_GATHER4_B; 3446 case Intrinsic::amdgcn_image_gather4_b_cl: 3447 return AMDGPUISD::IMAGE_GATHER4_B_CL; 3448 case Intrinsic::amdgcn_image_gather4_lz: 3449 return AMDGPUISD::IMAGE_GATHER4_LZ; 3450 3451 // Gather4 with comparison. 3452 case Intrinsic::amdgcn_image_gather4_c: 3453 return AMDGPUISD::IMAGE_GATHER4_C; 3454 case Intrinsic::amdgcn_image_gather4_c_cl: 3455 return AMDGPUISD::IMAGE_GATHER4_C_CL; 3456 case Intrinsic::amdgcn_image_gather4_c_l: 3457 return AMDGPUISD::IMAGE_GATHER4_C_L; 3458 case Intrinsic::amdgcn_image_gather4_c_b: 3459 return AMDGPUISD::IMAGE_GATHER4_C_B; 3460 case Intrinsic::amdgcn_image_gather4_c_b_cl: 3461 return AMDGPUISD::IMAGE_GATHER4_C_B_CL; 3462 case Intrinsic::amdgcn_image_gather4_c_lz: 3463 return AMDGPUISD::IMAGE_GATHER4_C_LZ; 3464 3465 // Gather4 with offsets. 3466 case Intrinsic::amdgcn_image_gather4_o: 3467 return AMDGPUISD::IMAGE_GATHER4_O; 3468 case Intrinsic::amdgcn_image_gather4_cl_o: 3469 return AMDGPUISD::IMAGE_GATHER4_CL_O; 3470 case Intrinsic::amdgcn_image_gather4_l_o: 3471 return AMDGPUISD::IMAGE_GATHER4_L_O; 3472 case Intrinsic::amdgcn_image_gather4_b_o: 3473 return AMDGPUISD::IMAGE_GATHER4_B_O; 3474 case Intrinsic::amdgcn_image_gather4_b_cl_o: 3475 return AMDGPUISD::IMAGE_GATHER4_B_CL_O; 3476 case Intrinsic::amdgcn_image_gather4_lz_o: 3477 return AMDGPUISD::IMAGE_GATHER4_LZ_O; 3478 3479 // Gather4 with comparison and offsets. 3480 case Intrinsic::amdgcn_image_gather4_c_o: 3481 return AMDGPUISD::IMAGE_GATHER4_C_O; 3482 case Intrinsic::amdgcn_image_gather4_c_cl_o: 3483 return AMDGPUISD::IMAGE_GATHER4_C_CL_O; 3484 case Intrinsic::amdgcn_image_gather4_c_l_o: 3485 return AMDGPUISD::IMAGE_GATHER4_C_L_O; 3486 case Intrinsic::amdgcn_image_gather4_c_b_o: 3487 return AMDGPUISD::IMAGE_GATHER4_C_B_O; 3488 case Intrinsic::amdgcn_image_gather4_c_b_cl_o: 3489 return AMDGPUISD::IMAGE_GATHER4_C_B_CL_O; 3490 case Intrinsic::amdgcn_image_gather4_c_lz_o: 3491 return AMDGPUISD::IMAGE_GATHER4_C_LZ_O; 3492 3493 default: 3494 break; 3495 } 3496 return 0; 3497 } 3498 3499 static SDValue adjustLoadValueType(SDValue Result, EVT LoadVT, SDLoc DL, 3500 SelectionDAG &DAG, bool Unpacked) { 3501 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 3502 // Truncate to v2i16/v4i16. 3503 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 3504 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, IntLoadVT, Result); 3505 // Bitcast to original type (v2f16/v4f16). 3506 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Trunc); 3507 } 3508 // Cast back to the original packed type. 3509 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 3510 } 3511 3512 // This is to lower INTRINSIC_W_CHAIN with illegal result types. 3513 SDValue SITargetLowering::lowerIntrinsicWChain_IllegalReturnType(SDValue Op, 3514 SDValue &Chain, SelectionDAG &DAG) const { 3515 EVT LoadVT = Op.getValueType(); 3516 // TODO: handle v3f16. 3517 if (LoadVT != MVT::v2f16 && LoadVT != MVT::v4f16) 3518 return SDValue(); 3519 3520 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 3521 EVT UnpackedLoadVT = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32; 3522 EVT EquivLoadVT = Unpacked ? UnpackedLoadVT : 3523 getEquivalentMemType(*DAG.getContext(), LoadVT); 3524 // Change from v4f16/v2f16 to EquivLoadVT. 3525 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 3526 3527 SDValue Res; 3528 SDLoc DL(Op); 3529 MemSDNode *M = cast<MemSDNode>(Op); 3530 unsigned IID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 3531 switch (IID) { 3532 case Intrinsic::amdgcn_tbuffer_load: { 3533 SDValue Ops[] = { 3534 Op.getOperand(0), // Chain 3535 Op.getOperand(2), // rsrc 3536 Op.getOperand(3), // vindex 3537 Op.getOperand(4), // voffset 3538 Op.getOperand(5), // soffset 3539 Op.getOperand(6), // offset 3540 Op.getOperand(7), // dfmt 3541 Op.getOperand(8), // nfmt 3542 Op.getOperand(9), // glc 3543 Op.getOperand(10) // slc 3544 }; 3545 Res = DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, DL, 3546 VTList, Ops, M->getMemoryVT(), 3547 M->getMemOperand()); 3548 Chain = Res.getValue(1); 3549 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3550 } 3551 case Intrinsic::amdgcn_buffer_load_format: { 3552 SDValue Ops[] = { 3553 Op.getOperand(0), // Chain 3554 Op.getOperand(2), // rsrc 3555 Op.getOperand(3), // vindex 3556 Op.getOperand(4), // offset 3557 Op.getOperand(5), // glc 3558 Op.getOperand(6) // slc 3559 }; 3560 Res = DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 3561 DL, VTList, Ops, M->getMemoryVT(), 3562 M->getMemOperand()); 3563 Chain = Res.getValue(1); 3564 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3565 } 3566 case Intrinsic::amdgcn_image_load: 3567 case Intrinsic::amdgcn_image_load_mip: { 3568 SDValue Ops[] = { 3569 Op.getOperand(0), // Chain 3570 Op.getOperand(2), // vaddr 3571 Op.getOperand(3), // rsrc 3572 Op.getOperand(4), // dmask 3573 Op.getOperand(5), // glc 3574 Op.getOperand(6), // slc 3575 Op.getOperand(7), // lwe 3576 Op.getOperand(8) // da 3577 }; 3578 unsigned Opc = getImageOpcode(IID); 3579 Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(), 3580 M->getMemOperand()); 3581 Chain = Res.getValue(1); 3582 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3583 } 3584 // Basic sample. 3585 case Intrinsic::amdgcn_image_sample: 3586 case Intrinsic::amdgcn_image_sample_cl: 3587 case Intrinsic::amdgcn_image_sample_d: 3588 case Intrinsic::amdgcn_image_sample_d_cl: 3589 case Intrinsic::amdgcn_image_sample_l: 3590 case Intrinsic::amdgcn_image_sample_b: 3591 case Intrinsic::amdgcn_image_sample_b_cl: 3592 case Intrinsic::amdgcn_image_sample_lz: 3593 case Intrinsic::amdgcn_image_sample_cd: 3594 case Intrinsic::amdgcn_image_sample_cd_cl: 3595 3596 // Sample with comparison. 3597 case Intrinsic::amdgcn_image_sample_c: 3598 case Intrinsic::amdgcn_image_sample_c_cl: 3599 case Intrinsic::amdgcn_image_sample_c_d: 3600 case Intrinsic::amdgcn_image_sample_c_d_cl: 3601 case Intrinsic::amdgcn_image_sample_c_l: 3602 case Intrinsic::amdgcn_image_sample_c_b: 3603 case Intrinsic::amdgcn_image_sample_c_b_cl: 3604 case Intrinsic::amdgcn_image_sample_c_lz: 3605 case Intrinsic::amdgcn_image_sample_c_cd: 3606 case Intrinsic::amdgcn_image_sample_c_cd_cl: 3607 3608 // Sample with offsets. 3609 case Intrinsic::amdgcn_image_sample_o: 3610 case Intrinsic::amdgcn_image_sample_cl_o: 3611 case Intrinsic::amdgcn_image_sample_d_o: 3612 case Intrinsic::amdgcn_image_sample_d_cl_o: 3613 case Intrinsic::amdgcn_image_sample_l_o: 3614 case Intrinsic::amdgcn_image_sample_b_o: 3615 case Intrinsic::amdgcn_image_sample_b_cl_o: 3616 case Intrinsic::amdgcn_image_sample_lz_o: 3617 case Intrinsic::amdgcn_image_sample_cd_o: 3618 case Intrinsic::amdgcn_image_sample_cd_cl_o: 3619 3620 // Sample with comparison and offsets. 3621 case Intrinsic::amdgcn_image_sample_c_o: 3622 case Intrinsic::amdgcn_image_sample_c_cl_o: 3623 case Intrinsic::amdgcn_image_sample_c_d_o: 3624 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 3625 case Intrinsic::amdgcn_image_sample_c_l_o: 3626 case Intrinsic::amdgcn_image_sample_c_b_o: 3627 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 3628 case Intrinsic::amdgcn_image_sample_c_lz_o: 3629 case Intrinsic::amdgcn_image_sample_c_cd_o: 3630 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: 3631 3632 // Basic gather4 3633 case Intrinsic::amdgcn_image_gather4: 3634 case Intrinsic::amdgcn_image_gather4_cl: 3635 case Intrinsic::amdgcn_image_gather4_l: 3636 case Intrinsic::amdgcn_image_gather4_b: 3637 case Intrinsic::amdgcn_image_gather4_b_cl: 3638 case Intrinsic::amdgcn_image_gather4_lz: 3639 3640 // Gather4 with comparison 3641 case Intrinsic::amdgcn_image_gather4_c: 3642 case Intrinsic::amdgcn_image_gather4_c_cl: 3643 case Intrinsic::amdgcn_image_gather4_c_l: 3644 case Intrinsic::amdgcn_image_gather4_c_b: 3645 case Intrinsic::amdgcn_image_gather4_c_b_cl: 3646 case Intrinsic::amdgcn_image_gather4_c_lz: 3647 3648 // Gather4 with offsets 3649 case Intrinsic::amdgcn_image_gather4_o: 3650 case Intrinsic::amdgcn_image_gather4_cl_o: 3651 case Intrinsic::amdgcn_image_gather4_l_o: 3652 case Intrinsic::amdgcn_image_gather4_b_o: 3653 case Intrinsic::amdgcn_image_gather4_b_cl_o: 3654 case Intrinsic::amdgcn_image_gather4_lz_o: 3655 3656 // Gather4 with comparison and offsets 3657 case Intrinsic::amdgcn_image_gather4_c_o: 3658 case Intrinsic::amdgcn_image_gather4_c_cl_o: 3659 case Intrinsic::amdgcn_image_gather4_c_l_o: 3660 case Intrinsic::amdgcn_image_gather4_c_b_o: 3661 case Intrinsic::amdgcn_image_gather4_c_b_cl_o: 3662 case Intrinsic::amdgcn_image_gather4_c_lz_o: { 3663 SDValue Ops[] = { 3664 Op.getOperand(0), // Chain 3665 Op.getOperand(2), // vaddr 3666 Op.getOperand(3), // rsrc 3667 Op.getOperand(4), // sampler 3668 Op.getOperand(5), // dmask 3669 Op.getOperand(6), // unorm 3670 Op.getOperand(7), // glc 3671 Op.getOperand(8), // slc 3672 Op.getOperand(9), // lwe 3673 Op.getOperand(10) // da 3674 }; 3675 unsigned Opc = getImageOpcode(IID); 3676 Res = DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, M->getMemoryVT(), 3677 M->getMemOperand()); 3678 Chain = Res.getValue(1); 3679 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3680 } 3681 default: { 3682 const AMDGPU::D16ImageDimIntrinsic *D16ImageDimIntr = 3683 AMDGPU::lookupD16ImageDimIntrinsicByIntr(IID); 3684 if (D16ImageDimIntr) { 3685 SmallVector<SDValue, 20> Ops; 3686 for (auto Value : Op.getNode()->op_values()) 3687 Ops.push_back(Value); 3688 Ops[1] = DAG.getConstant(D16ImageDimIntr->D16HelperIntr, DL, MVT::i32); 3689 Res = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTList, Ops, 3690 M->getMemoryVT(), M->getMemOperand()); 3691 Chain = Res.getValue(1); 3692 return adjustLoadValueType(Res, LoadVT, DL, DAG, Unpacked); 3693 } 3694 3695 return SDValue(); 3696 } 3697 } 3698 } 3699 3700 void SITargetLowering::ReplaceNodeResults(SDNode *N, 3701 SmallVectorImpl<SDValue> &Results, 3702 SelectionDAG &DAG) const { 3703 switch (N->getOpcode()) { 3704 case ISD::INSERT_VECTOR_ELT: { 3705 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 3706 Results.push_back(Res); 3707 return; 3708 } 3709 case ISD::EXTRACT_VECTOR_ELT: { 3710 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 3711 Results.push_back(Res); 3712 return; 3713 } 3714 case ISD::INTRINSIC_WO_CHAIN: { 3715 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 3716 switch (IID) { 3717 case Intrinsic::amdgcn_cvt_pkrtz: { 3718 SDValue Src0 = N->getOperand(1); 3719 SDValue Src1 = N->getOperand(2); 3720 SDLoc SL(N); 3721 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 3722 Src0, Src1); 3723 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 3724 return; 3725 } 3726 case Intrinsic::amdgcn_cvt_pknorm_i16: 3727 case Intrinsic::amdgcn_cvt_pknorm_u16: 3728 case Intrinsic::amdgcn_cvt_pk_i16: 3729 case Intrinsic::amdgcn_cvt_pk_u16: { 3730 SDValue Src0 = N->getOperand(1); 3731 SDValue Src1 = N->getOperand(2); 3732 SDLoc SL(N); 3733 unsigned Opcode; 3734 3735 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 3736 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 3737 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 3738 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 3739 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 3740 Opcode = AMDGPUISD::CVT_PK_I16_I32; 3741 else 3742 Opcode = AMDGPUISD::CVT_PK_U16_U32; 3743 3744 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 3745 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 3746 return; 3747 } 3748 } 3749 break; 3750 } 3751 case ISD::INTRINSIC_W_CHAIN: { 3752 SDValue Chain; 3753 if (SDValue Res = lowerIntrinsicWChain_IllegalReturnType(SDValue(N, 0), 3754 Chain, DAG)) { 3755 Results.push_back(Res); 3756 Results.push_back(Chain); 3757 return; 3758 } 3759 break; 3760 } 3761 case ISD::SELECT: { 3762 SDLoc SL(N); 3763 EVT VT = N->getValueType(0); 3764 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 3765 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 3766 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 3767 3768 EVT SelectVT = NewVT; 3769 if (NewVT.bitsLT(MVT::i32)) { 3770 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 3771 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 3772 SelectVT = MVT::i32; 3773 } 3774 3775 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 3776 N->getOperand(0), LHS, RHS); 3777 3778 if (NewVT != SelectVT) 3779 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 3780 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 3781 return; 3782 } 3783 default: 3784 break; 3785 } 3786 } 3787 3788 /// Helper function for LowerBRCOND 3789 static SDNode *findUser(SDValue Value, unsigned Opcode) { 3790 3791 SDNode *Parent = Value.getNode(); 3792 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 3793 I != E; ++I) { 3794 3795 if (I.getUse().get() != Value) 3796 continue; 3797 3798 if (I->getOpcode() == Opcode) 3799 return *I; 3800 } 3801 return nullptr; 3802 } 3803 3804 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 3805 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 3806 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 3807 case Intrinsic::amdgcn_if: 3808 return AMDGPUISD::IF; 3809 case Intrinsic::amdgcn_else: 3810 return AMDGPUISD::ELSE; 3811 case Intrinsic::amdgcn_loop: 3812 return AMDGPUISD::LOOP; 3813 case Intrinsic::amdgcn_end_cf: 3814 llvm_unreachable("should not occur"); 3815 default: 3816 return 0; 3817 } 3818 } 3819 3820 // break, if_break, else_break are all only used as inputs to loop, not 3821 // directly as branch conditions. 3822 return 0; 3823 } 3824 3825 void SITargetLowering::createDebuggerPrologueStackObjects( 3826 MachineFunction &MF) const { 3827 // Create stack objects that are used for emitting debugger prologue. 3828 // 3829 // Debugger prologue writes work group IDs and work item IDs to scratch memory 3830 // at fixed location in the following format: 3831 // offset 0: work group ID x 3832 // offset 4: work group ID y 3833 // offset 8: work group ID z 3834 // offset 16: work item ID x 3835 // offset 20: work item ID y 3836 // offset 24: work item ID z 3837 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3838 int ObjectIdx = 0; 3839 3840 // For each dimension: 3841 for (unsigned i = 0; i < 3; ++i) { 3842 // Create fixed stack object for work group ID. 3843 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true); 3844 Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx); 3845 // Create fixed stack object for work item ID. 3846 ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true); 3847 Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx); 3848 } 3849 } 3850 3851 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 3852 const Triple &TT = getTargetMachine().getTargetTriple(); 3853 return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS || 3854 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) && 3855 AMDGPU::shouldEmitConstantsToTextSection(TT); 3856 } 3857 3858 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 3859 return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 3860 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS || 3861 GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) && 3862 !shouldEmitFixup(GV) && 3863 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3864 } 3865 3866 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 3867 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 3868 } 3869 3870 /// This transforms the control flow intrinsics to get the branch destination as 3871 /// last parameter, also switches branch target with BR if the need arise 3872 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 3873 SelectionDAG &DAG) const { 3874 SDLoc DL(BRCOND); 3875 3876 SDNode *Intr = BRCOND.getOperand(1).getNode(); 3877 SDValue Target = BRCOND.getOperand(2); 3878 SDNode *BR = nullptr; 3879 SDNode *SetCC = nullptr; 3880 3881 if (Intr->getOpcode() == ISD::SETCC) { 3882 // As long as we negate the condition everything is fine 3883 SetCC = Intr; 3884 Intr = SetCC->getOperand(0).getNode(); 3885 3886 } else { 3887 // Get the target from BR if we don't negate the condition 3888 BR = findUser(BRCOND, ISD::BR); 3889 Target = BR->getOperand(1); 3890 } 3891 3892 // FIXME: This changes the types of the intrinsics instead of introducing new 3893 // nodes with the correct types. 3894 // e.g. llvm.amdgcn.loop 3895 3896 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 3897 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 3898 3899 unsigned CFNode = isCFIntrinsic(Intr); 3900 if (CFNode == 0) { 3901 // This is a uniform branch so we don't need to legalize. 3902 return BRCOND; 3903 } 3904 3905 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 3906 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 3907 3908 assert(!SetCC || 3909 (SetCC->getConstantOperandVal(1) == 1 && 3910 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 3911 ISD::SETNE)); 3912 3913 // operands of the new intrinsic call 3914 SmallVector<SDValue, 4> Ops; 3915 if (HaveChain) 3916 Ops.push_back(BRCOND.getOperand(0)); 3917 3918 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 3919 Ops.push_back(Target); 3920 3921 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 3922 3923 // build the new intrinsic call 3924 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 3925 3926 if (!HaveChain) { 3927 SDValue Ops[] = { 3928 SDValue(Result, 0), 3929 BRCOND.getOperand(0) 3930 }; 3931 3932 Result = DAG.getMergeValues(Ops, DL).getNode(); 3933 } 3934 3935 if (BR) { 3936 // Give the branch instruction our target 3937 SDValue Ops[] = { 3938 BR->getOperand(0), 3939 BRCOND.getOperand(2) 3940 }; 3941 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 3942 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 3943 BR = NewBR.getNode(); 3944 } 3945 3946 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 3947 3948 // Copy the intrinsic results to registers 3949 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 3950 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 3951 if (!CopyToReg) 3952 continue; 3953 3954 Chain = DAG.getCopyToReg( 3955 Chain, DL, 3956 CopyToReg->getOperand(1), 3957 SDValue(Result, i - 1), 3958 SDValue()); 3959 3960 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 3961 } 3962 3963 // Remove the old intrinsic from the chain 3964 DAG.ReplaceAllUsesOfValueWith( 3965 SDValue(Intr, Intr->getNumValues() - 1), 3966 Intr->getOperand(0)); 3967 3968 return Chain; 3969 } 3970 3971 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 3972 SDValue Op, 3973 const SDLoc &DL, 3974 EVT VT) const { 3975 return Op.getValueType().bitsLE(VT) ? 3976 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 3977 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 3978 } 3979 3980 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 3981 assert(Op.getValueType() == MVT::f16 && 3982 "Do not know how to custom lower FP_ROUND for non-f16 type"); 3983 3984 SDValue Src = Op.getOperand(0); 3985 EVT SrcVT = Src.getValueType(); 3986 if (SrcVT != MVT::f64) 3987 return Op; 3988 3989 SDLoc DL(Op); 3990 3991 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 3992 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 3993 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 3994 } 3995 3996 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 3997 SDLoc SL(Op); 3998 MachineFunction &MF = DAG.getMachineFunction(); 3999 SDValue Chain = Op.getOperand(0); 4000 4001 unsigned TrapID = Op.getOpcode() == ISD::DEBUGTRAP ? 4002 SISubtarget::TrapIDLLVMDebugTrap : SISubtarget::TrapIDLLVMTrap; 4003 4004 if (Subtarget->getTrapHandlerAbi() == SISubtarget::TrapHandlerAbiHsa && 4005 Subtarget->isTrapHandlerEnabled()) { 4006 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4007 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4008 assert(UserSGPR != AMDGPU::NoRegister); 4009 4010 SDValue QueuePtr = CreateLiveInRegister( 4011 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4012 4013 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4014 4015 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4016 QueuePtr, SDValue()); 4017 4018 SDValue Ops[] = { 4019 ToReg, 4020 DAG.getTargetConstant(TrapID, SL, MVT::i16), 4021 SGPR01, 4022 ToReg.getValue(1) 4023 }; 4024 4025 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4026 } 4027 4028 switch (TrapID) { 4029 case SISubtarget::TrapIDLLVMTrap: 4030 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4031 case SISubtarget::TrapIDLLVMDebugTrap: { 4032 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4033 "debugtrap handler not supported", 4034 Op.getDebugLoc(), 4035 DS_Warning); 4036 LLVMContext &Ctx = MF.getFunction().getContext(); 4037 Ctx.diagnose(NoTrap); 4038 return Chain; 4039 } 4040 default: 4041 llvm_unreachable("unsupported trap handler type!"); 4042 } 4043 4044 return Chain; 4045 } 4046 4047 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4048 SelectionDAG &DAG) const { 4049 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4050 if (Subtarget->hasApertureRegs()) { 4051 unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ? 4052 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4053 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4054 unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ? 4055 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4056 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4057 unsigned Encoding = 4058 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4059 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4060 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4061 4062 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4063 SDValue ApertureReg = SDValue( 4064 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4065 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4066 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4067 } 4068 4069 MachineFunction &MF = DAG.getMachineFunction(); 4070 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4071 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4072 assert(UserSGPR != AMDGPU::NoRegister); 4073 4074 SDValue QueuePtr = CreateLiveInRegister( 4075 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4076 4077 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4078 // private_segment_aperture_base_hi. 4079 uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44; 4080 4081 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4082 4083 // TODO: Use custom target PseudoSourceValue. 4084 // TODO: We should use the value from the IR intrinsic call, but it might not 4085 // be available and how do we get it? 4086 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4087 AMDGPUASI.CONSTANT_ADDRESS)); 4088 4089 MachinePointerInfo PtrInfo(V, StructOffset); 4090 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4091 MinAlign(64, StructOffset), 4092 MachineMemOperand::MODereferenceable | 4093 MachineMemOperand::MOInvariant); 4094 } 4095 4096 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4097 SelectionDAG &DAG) const { 4098 SDLoc SL(Op); 4099 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4100 4101 SDValue Src = ASC->getOperand(0); 4102 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4103 4104 const AMDGPUTargetMachine &TM = 4105 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4106 4107 // flat -> local/private 4108 if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 4109 unsigned DestAS = ASC->getDestAddressSpace(); 4110 4111 if (DestAS == AMDGPUASI.LOCAL_ADDRESS || 4112 DestAS == AMDGPUASI.PRIVATE_ADDRESS) { 4113 unsigned NullVal = TM.getNullPointerValue(DestAS); 4114 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4115 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4116 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4117 4118 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4119 NonNull, Ptr, SegmentNullPtr); 4120 } 4121 } 4122 4123 // local/private -> flat 4124 if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) { 4125 unsigned SrcAS = ASC->getSrcAddressSpace(); 4126 4127 if (SrcAS == AMDGPUASI.LOCAL_ADDRESS || 4128 SrcAS == AMDGPUASI.PRIVATE_ADDRESS) { 4129 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4130 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4131 4132 SDValue NonNull 4133 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4134 4135 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4136 SDValue CvtPtr 4137 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4138 4139 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4140 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4141 FlatNullPtr); 4142 } 4143 } 4144 4145 // global <-> flat are no-ops and never emitted. 4146 4147 const MachineFunction &MF = DAG.getMachineFunction(); 4148 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4149 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4150 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4151 4152 return DAG.getUNDEF(ASC->getValueType(0)); 4153 } 4154 4155 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4156 SelectionDAG &DAG) const { 4157 SDValue Idx = Op.getOperand(2); 4158 if (isa<ConstantSDNode>(Idx)) 4159 return SDValue(); 4160 4161 // Avoid stack access for dynamic indexing. 4162 SDLoc SL(Op); 4163 SDValue Vec = Op.getOperand(0); 4164 SDValue Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Op.getOperand(1)); 4165 4166 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4167 SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Val); 4168 4169 // Convert vector index to bit-index. 4170 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, 4171 DAG.getConstant(4, SL, MVT::i32)); 4172 4173 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 4174 4175 SDValue BFM = DAG.getNode(ISD::SHL, SL, MVT::i32, 4176 DAG.getConstant(0xffff, SL, MVT::i32), 4177 ScaledIdx); 4178 4179 SDValue LHS = DAG.getNode(ISD::AND, SL, MVT::i32, BFM, ExtVal); 4180 SDValue RHS = DAG.getNode(ISD::AND, SL, MVT::i32, 4181 DAG.getNOT(SL, BFM, MVT::i32), BCVec); 4182 4183 SDValue BFI = DAG.getNode(ISD::OR, SL, MVT::i32, LHS, RHS); 4184 return DAG.getNode(ISD::BITCAST, SL, Op.getValueType(), BFI); 4185 } 4186 4187 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4188 SelectionDAG &DAG) const { 4189 SDLoc SL(Op); 4190 4191 EVT ResultVT = Op.getValueType(); 4192 SDValue Vec = Op.getOperand(0); 4193 SDValue Idx = Op.getOperand(1); 4194 4195 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4196 4197 // Make sure we do any optimizations that will make it easier to fold 4198 // source modifiers before obscuring it with bit operations. 4199 4200 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4201 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4202 return Combined; 4203 4204 SDValue Four = DAG.getConstant(4, SL, MVT::i32); 4205 4206 // Convert vector index to bit-index (* 16) 4207 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, Four); 4208 4209 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Vec); 4210 SDValue Elt = DAG.getNode(ISD::SRL, SL, MVT::i32, BC, ScaledIdx); 4211 4212 SDValue Result = Elt; 4213 if (ResultVT.bitsLT(MVT::i32)) 4214 Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Result); 4215 4216 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4217 } 4218 4219 bool 4220 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4221 // We can fold offsets for anything that doesn't require a GOT relocation. 4222 return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS || 4223 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS || 4224 GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) && 4225 !shouldEmitGOTReloc(GA->getGlobal()); 4226 } 4227 4228 static SDValue 4229 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4230 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4231 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4232 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4233 // lowered to the following code sequence: 4234 // 4235 // For constant address space: 4236 // s_getpc_b64 s[0:1] 4237 // s_add_u32 s0, s0, $symbol 4238 // s_addc_u32 s1, s1, 0 4239 // 4240 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4241 // a fixup or relocation is emitted to replace $symbol with a literal 4242 // constant, which is a pc-relative offset from the encoding of the $symbol 4243 // operand to the global variable. 4244 // 4245 // For global address space: 4246 // s_getpc_b64 s[0:1] 4247 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4248 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4249 // 4250 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4251 // fixups or relocations are emitted to replace $symbol@*@lo and 4252 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4253 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4254 // operand to the global variable. 4255 // 4256 // What we want here is an offset from the value returned by s_getpc 4257 // (which is the address of the s_add_u32 instruction) to the global 4258 // variable, but since the encoding of $symbol starts 4 bytes after the start 4259 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4260 // small. This requires us to add 4 to the global variable offset in order to 4261 // compute the correct address. 4262 SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4263 GAFlags); 4264 SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, 4265 GAFlags == SIInstrInfo::MO_NONE ? 4266 GAFlags : GAFlags + 1); 4267 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4268 } 4269 4270 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4271 SDValue Op, 4272 SelectionDAG &DAG) const { 4273 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4274 const GlobalValue *GV = GSD->getGlobal(); 4275 4276 if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS && 4277 GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT && 4278 GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS && 4279 // FIXME: It isn't correct to rely on the type of the pointer. This should 4280 // be removed when address space 0 is 64-bit. 4281 !GV->getType()->getElementType()->isFunctionTy()) 4282 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4283 4284 SDLoc DL(GSD); 4285 EVT PtrVT = Op.getValueType(); 4286 4287 if (shouldEmitFixup(GV)) 4288 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 4289 else if (shouldEmitPCReloc(GV)) 4290 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 4291 SIInstrInfo::MO_REL32); 4292 4293 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 4294 SIInstrInfo::MO_GOTPCREL32); 4295 4296 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 4297 PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS); 4298 const DataLayout &DataLayout = DAG.getDataLayout(); 4299 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 4300 // FIXME: Use a PseudoSourceValue once those can be assigned an address space. 4301 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 4302 4303 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 4304 MachineMemOperand::MODereferenceable | 4305 MachineMemOperand::MOInvariant); 4306 } 4307 4308 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 4309 const SDLoc &DL, SDValue V) const { 4310 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 4311 // the destination register. 4312 // 4313 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 4314 // so we will end up with redundant moves to m0. 4315 // 4316 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 4317 4318 // A Null SDValue creates a glue result. 4319 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 4320 V, Chain); 4321 return SDValue(M0, 0); 4322 } 4323 4324 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 4325 SDValue Op, 4326 MVT VT, 4327 unsigned Offset) const { 4328 SDLoc SL(Op); 4329 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 4330 DAG.getEntryNode(), Offset, false); 4331 // The local size values will have the hi 16-bits as zero. 4332 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 4333 DAG.getValueType(VT)); 4334 } 4335 4336 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4337 EVT VT) { 4338 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4339 "non-hsa intrinsic with hsa target", 4340 DL.getDebugLoc()); 4341 DAG.getContext()->diagnose(BadIntrin); 4342 return DAG.getUNDEF(VT); 4343 } 4344 4345 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4346 EVT VT) { 4347 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4348 "intrinsic not supported on subtarget", 4349 DL.getDebugLoc()); 4350 DAG.getContext()->diagnose(BadIntrin); 4351 return DAG.getUNDEF(VT); 4352 } 4353 4354 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4355 SelectionDAG &DAG) const { 4356 MachineFunction &MF = DAG.getMachineFunction(); 4357 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 4358 4359 EVT VT = Op.getValueType(); 4360 SDLoc DL(Op); 4361 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4362 4363 // TODO: Should this propagate fast-math-flags? 4364 4365 switch (IntrinsicID) { 4366 case Intrinsic::amdgcn_implicit_buffer_ptr: { 4367 if (getSubtarget()->isAmdCodeObjectV2(MF)) 4368 return emitNonHSAIntrinsicError(DAG, DL, VT); 4369 return getPreloadedValue(DAG, *MFI, VT, 4370 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 4371 } 4372 case Intrinsic::amdgcn_dispatch_ptr: 4373 case Intrinsic::amdgcn_queue_ptr: { 4374 if (!Subtarget->isAmdCodeObjectV2(MF)) { 4375 DiagnosticInfoUnsupported BadIntrin( 4376 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 4377 DL.getDebugLoc()); 4378 DAG.getContext()->diagnose(BadIntrin); 4379 return DAG.getUNDEF(VT); 4380 } 4381 4382 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 4383 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 4384 return getPreloadedValue(DAG, *MFI, VT, RegID); 4385 } 4386 case Intrinsic::amdgcn_implicitarg_ptr: { 4387 if (MFI->isEntryFunction()) 4388 return getImplicitArgPtr(DAG, DL); 4389 return getPreloadedValue(DAG, *MFI, VT, 4390 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 4391 } 4392 case Intrinsic::amdgcn_kernarg_segment_ptr: { 4393 return getPreloadedValue(DAG, *MFI, VT, 4394 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 4395 } 4396 case Intrinsic::amdgcn_dispatch_id: { 4397 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 4398 } 4399 case Intrinsic::amdgcn_rcp: 4400 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 4401 case Intrinsic::amdgcn_rsq: 4402 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 4403 case Intrinsic::amdgcn_rsq_legacy: 4404 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 4405 return emitRemovedIntrinsicError(DAG, DL, VT); 4406 4407 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 4408 case Intrinsic::amdgcn_rcp_legacy: 4409 if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) 4410 return emitRemovedIntrinsicError(DAG, DL, VT); 4411 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 4412 case Intrinsic::amdgcn_rsq_clamp: { 4413 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4414 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 4415 4416 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 4417 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 4418 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 4419 4420 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 4421 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 4422 DAG.getConstantFP(Max, DL, VT)); 4423 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 4424 DAG.getConstantFP(Min, DL, VT)); 4425 } 4426 case Intrinsic::r600_read_ngroups_x: 4427 if (Subtarget->isAmdHsaOS()) 4428 return emitNonHSAIntrinsicError(DAG, DL, VT); 4429 4430 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4431 SI::KernelInputOffsets::NGROUPS_X, false); 4432 case Intrinsic::r600_read_ngroups_y: 4433 if (Subtarget->isAmdHsaOS()) 4434 return emitNonHSAIntrinsicError(DAG, DL, VT); 4435 4436 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4437 SI::KernelInputOffsets::NGROUPS_Y, false); 4438 case Intrinsic::r600_read_ngroups_z: 4439 if (Subtarget->isAmdHsaOS()) 4440 return emitNonHSAIntrinsicError(DAG, DL, VT); 4441 4442 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4443 SI::KernelInputOffsets::NGROUPS_Z, false); 4444 case Intrinsic::r600_read_global_size_x: 4445 if (Subtarget->isAmdHsaOS()) 4446 return emitNonHSAIntrinsicError(DAG, DL, VT); 4447 4448 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4449 SI::KernelInputOffsets::GLOBAL_SIZE_X, false); 4450 case Intrinsic::r600_read_global_size_y: 4451 if (Subtarget->isAmdHsaOS()) 4452 return emitNonHSAIntrinsicError(DAG, DL, VT); 4453 4454 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4455 SI::KernelInputOffsets::GLOBAL_SIZE_Y, false); 4456 case Intrinsic::r600_read_global_size_z: 4457 if (Subtarget->isAmdHsaOS()) 4458 return emitNonHSAIntrinsicError(DAG, DL, VT); 4459 4460 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 4461 SI::KernelInputOffsets::GLOBAL_SIZE_Z, false); 4462 case Intrinsic::r600_read_local_size_x: 4463 if (Subtarget->isAmdHsaOS()) 4464 return emitNonHSAIntrinsicError(DAG, DL, VT); 4465 4466 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4467 SI::KernelInputOffsets::LOCAL_SIZE_X); 4468 case Intrinsic::r600_read_local_size_y: 4469 if (Subtarget->isAmdHsaOS()) 4470 return emitNonHSAIntrinsicError(DAG, DL, VT); 4471 4472 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4473 SI::KernelInputOffsets::LOCAL_SIZE_Y); 4474 case Intrinsic::r600_read_local_size_z: 4475 if (Subtarget->isAmdHsaOS()) 4476 return emitNonHSAIntrinsicError(DAG, DL, VT); 4477 4478 return lowerImplicitZextParam(DAG, Op, MVT::i16, 4479 SI::KernelInputOffsets::LOCAL_SIZE_Z); 4480 case Intrinsic::amdgcn_workgroup_id_x: 4481 case Intrinsic::r600_read_tgid_x: 4482 return getPreloadedValue(DAG, *MFI, VT, 4483 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 4484 case Intrinsic::amdgcn_workgroup_id_y: 4485 case Intrinsic::r600_read_tgid_y: 4486 return getPreloadedValue(DAG, *MFI, VT, 4487 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 4488 case Intrinsic::amdgcn_workgroup_id_z: 4489 case Intrinsic::r600_read_tgid_z: 4490 return getPreloadedValue(DAG, *MFI, VT, 4491 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 4492 case Intrinsic::amdgcn_workitem_id_x: { 4493 case Intrinsic::r600_read_tidig_x: 4494 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4495 SDLoc(DAG.getEntryNode()), 4496 MFI->getArgInfo().WorkItemIDX); 4497 } 4498 case Intrinsic::amdgcn_workitem_id_y: 4499 case Intrinsic::r600_read_tidig_y: 4500 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4501 SDLoc(DAG.getEntryNode()), 4502 MFI->getArgInfo().WorkItemIDY); 4503 case Intrinsic::amdgcn_workitem_id_z: 4504 case Intrinsic::r600_read_tidig_z: 4505 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 4506 SDLoc(DAG.getEntryNode()), 4507 MFI->getArgInfo().WorkItemIDZ); 4508 case AMDGPUIntrinsic::SI_load_const: { 4509 SDValue Ops[] = { 4510 Op.getOperand(1), 4511 Op.getOperand(2) 4512 }; 4513 4514 MachineMemOperand *MMO = MF.getMachineMemOperand( 4515 MachinePointerInfo(), 4516 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 4517 MachineMemOperand::MOInvariant, 4518 VT.getStoreSize(), 4); 4519 return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL, 4520 Op->getVTList(), Ops, VT, MMO); 4521 } 4522 case Intrinsic::amdgcn_fdiv_fast: 4523 return lowerFDIV_FAST(Op, DAG); 4524 case Intrinsic::amdgcn_interp_mov: { 4525 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4526 SDValue Glue = M0.getValue(1); 4527 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 4528 Op.getOperand(2), Op.getOperand(3), Glue); 4529 } 4530 case Intrinsic::amdgcn_interp_p1: { 4531 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 4532 SDValue Glue = M0.getValue(1); 4533 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 4534 Op.getOperand(2), Op.getOperand(3), Glue); 4535 } 4536 case Intrinsic::amdgcn_interp_p2: { 4537 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 4538 SDValue Glue = SDValue(M0.getNode(), 1); 4539 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 4540 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 4541 Glue); 4542 } 4543 case Intrinsic::amdgcn_sin: 4544 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 4545 4546 case Intrinsic::amdgcn_cos: 4547 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 4548 4549 case Intrinsic::amdgcn_log_clamp: { 4550 if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS) 4551 return SDValue(); 4552 4553 DiagnosticInfoUnsupported BadIntrin( 4554 MF.getFunction(), "intrinsic not supported on subtarget", 4555 DL.getDebugLoc()); 4556 DAG.getContext()->diagnose(BadIntrin); 4557 return DAG.getUNDEF(VT); 4558 } 4559 case Intrinsic::amdgcn_ldexp: 4560 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 4561 Op.getOperand(1), Op.getOperand(2)); 4562 4563 case Intrinsic::amdgcn_fract: 4564 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 4565 4566 case Intrinsic::amdgcn_class: 4567 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 4568 Op.getOperand(1), Op.getOperand(2)); 4569 case Intrinsic::amdgcn_div_fmas: 4570 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 4571 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 4572 Op.getOperand(4)); 4573 4574 case Intrinsic::amdgcn_div_fixup: 4575 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 4576 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4577 4578 case Intrinsic::amdgcn_trig_preop: 4579 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 4580 Op.getOperand(1), Op.getOperand(2)); 4581 case Intrinsic::amdgcn_div_scale: { 4582 // 3rd parameter required to be a constant. 4583 const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4584 if (!Param) 4585 return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL); 4586 4587 // Translate to the operands expected by the machine instruction. The 4588 // first parameter must be the same as the first instruction. 4589 SDValue Numerator = Op.getOperand(1); 4590 SDValue Denominator = Op.getOperand(2); 4591 4592 // Note this order is opposite of the machine instruction's operations, 4593 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 4594 // intrinsic has the numerator as the first operand to match a normal 4595 // division operation. 4596 4597 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 4598 4599 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 4600 Denominator, Numerator); 4601 } 4602 case Intrinsic::amdgcn_icmp: { 4603 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4604 if (!CD) 4605 return DAG.getUNDEF(VT); 4606 4607 int CondCode = CD->getSExtValue(); 4608 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4609 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4610 return DAG.getUNDEF(VT); 4611 4612 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4613 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4614 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4615 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4616 } 4617 case Intrinsic::amdgcn_fcmp: { 4618 const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3)); 4619 if (!CD) 4620 return DAG.getUNDEF(VT); 4621 4622 int CondCode = CD->getSExtValue(); 4623 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4624 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) 4625 return DAG.getUNDEF(VT); 4626 4627 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4628 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4629 return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1), 4630 Op.getOperand(2), DAG.getCondCode(CCOpcode)); 4631 } 4632 case Intrinsic::amdgcn_fmed3: 4633 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 4634 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4635 case Intrinsic::amdgcn_fmul_legacy: 4636 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 4637 Op.getOperand(1), Op.getOperand(2)); 4638 case Intrinsic::amdgcn_sffbh: 4639 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 4640 case Intrinsic::amdgcn_sbfe: 4641 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 4642 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4643 case Intrinsic::amdgcn_ubfe: 4644 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 4645 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4646 case Intrinsic::amdgcn_cvt_pkrtz: 4647 case Intrinsic::amdgcn_cvt_pknorm_i16: 4648 case Intrinsic::amdgcn_cvt_pknorm_u16: 4649 case Intrinsic::amdgcn_cvt_pk_i16: 4650 case Intrinsic::amdgcn_cvt_pk_u16: { 4651 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 4652 EVT VT = Op.getValueType(); 4653 unsigned Opcode; 4654 4655 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 4656 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 4657 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 4658 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4659 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 4660 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4661 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 4662 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4663 else 4664 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4665 4666 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 4667 Op.getOperand(1), Op.getOperand(2)); 4668 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 4669 } 4670 case Intrinsic::amdgcn_wqm: { 4671 SDValue Src = Op.getOperand(1); 4672 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 4673 0); 4674 } 4675 case Intrinsic::amdgcn_wwm: { 4676 SDValue Src = Op.getOperand(1); 4677 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 4678 0); 4679 } 4680 case Intrinsic::amdgcn_image_getlod: 4681 case Intrinsic::amdgcn_image_getresinfo: { 4682 unsigned Idx = (IntrinsicID == Intrinsic::amdgcn_image_getresinfo) ? 3 : 4; 4683 4684 // Replace dmask with everything disabled with undef. 4685 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(Idx)); 4686 if (!DMask || DMask->isNullValue()) 4687 return DAG.getUNDEF(Op.getValueType()); 4688 return SDValue(); 4689 } 4690 default: 4691 return Op; 4692 } 4693 } 4694 4695 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4696 SelectionDAG &DAG) const { 4697 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4698 SDLoc DL(Op); 4699 4700 switch (IntrID) { 4701 case Intrinsic::amdgcn_atomic_inc: 4702 case Intrinsic::amdgcn_atomic_dec: 4703 case Intrinsic::amdgcn_ds_fadd: 4704 case Intrinsic::amdgcn_ds_fmin: 4705 case Intrinsic::amdgcn_ds_fmax: { 4706 MemSDNode *M = cast<MemSDNode>(Op); 4707 unsigned Opc; 4708 switch (IntrID) { 4709 case Intrinsic::amdgcn_atomic_inc: 4710 Opc = AMDGPUISD::ATOMIC_INC; 4711 break; 4712 case Intrinsic::amdgcn_atomic_dec: 4713 Opc = AMDGPUISD::ATOMIC_DEC; 4714 break; 4715 case Intrinsic::amdgcn_ds_fadd: 4716 Opc = AMDGPUISD::ATOMIC_LOAD_FADD; 4717 break; 4718 case Intrinsic::amdgcn_ds_fmin: 4719 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 4720 break; 4721 case Intrinsic::amdgcn_ds_fmax: 4722 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 4723 break; 4724 default: 4725 llvm_unreachable("Unknown intrinsic!"); 4726 } 4727 SDValue Ops[] = { 4728 M->getOperand(0), // Chain 4729 M->getOperand(2), // Ptr 4730 M->getOperand(3) // Value 4731 }; 4732 4733 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 4734 M->getMemoryVT(), M->getMemOperand()); 4735 } 4736 case Intrinsic::amdgcn_buffer_load: 4737 case Intrinsic::amdgcn_buffer_load_format: { 4738 SDValue Ops[] = { 4739 Op.getOperand(0), // Chain 4740 Op.getOperand(2), // rsrc 4741 Op.getOperand(3), // vindex 4742 Op.getOperand(4), // offset 4743 Op.getOperand(5), // glc 4744 Op.getOperand(6) // slc 4745 }; 4746 4747 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 4748 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 4749 EVT VT = Op.getValueType(); 4750 EVT IntVT = VT.changeTypeToInteger(); 4751 4752 auto *M = cast<MemSDNode>(Op); 4753 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 4754 M->getMemOperand()); 4755 } 4756 case Intrinsic::amdgcn_tbuffer_load: { 4757 MemSDNode *M = cast<MemSDNode>(Op); 4758 SDValue Ops[] = { 4759 Op.getOperand(0), // Chain 4760 Op.getOperand(2), // rsrc 4761 Op.getOperand(3), // vindex 4762 Op.getOperand(4), // voffset 4763 Op.getOperand(5), // soffset 4764 Op.getOperand(6), // offset 4765 Op.getOperand(7), // dfmt 4766 Op.getOperand(8), // nfmt 4767 Op.getOperand(9), // glc 4768 Op.getOperand(10) // slc 4769 }; 4770 4771 EVT VT = Op.getValueType(); 4772 4773 return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 4774 Op->getVTList(), Ops, VT, M->getMemOperand()); 4775 } 4776 case Intrinsic::amdgcn_buffer_atomic_swap: 4777 case Intrinsic::amdgcn_buffer_atomic_add: 4778 case Intrinsic::amdgcn_buffer_atomic_sub: 4779 case Intrinsic::amdgcn_buffer_atomic_smin: 4780 case Intrinsic::amdgcn_buffer_atomic_umin: 4781 case Intrinsic::amdgcn_buffer_atomic_smax: 4782 case Intrinsic::amdgcn_buffer_atomic_umax: 4783 case Intrinsic::amdgcn_buffer_atomic_and: 4784 case Intrinsic::amdgcn_buffer_atomic_or: 4785 case Intrinsic::amdgcn_buffer_atomic_xor: { 4786 SDValue Ops[] = { 4787 Op.getOperand(0), // Chain 4788 Op.getOperand(2), // vdata 4789 Op.getOperand(3), // rsrc 4790 Op.getOperand(4), // vindex 4791 Op.getOperand(5), // offset 4792 Op.getOperand(6) // slc 4793 }; 4794 EVT VT = Op.getValueType(); 4795 4796 auto *M = cast<MemSDNode>(Op); 4797 unsigned Opcode = 0; 4798 4799 switch (IntrID) { 4800 case Intrinsic::amdgcn_buffer_atomic_swap: 4801 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 4802 break; 4803 case Intrinsic::amdgcn_buffer_atomic_add: 4804 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 4805 break; 4806 case Intrinsic::amdgcn_buffer_atomic_sub: 4807 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 4808 break; 4809 case Intrinsic::amdgcn_buffer_atomic_smin: 4810 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 4811 break; 4812 case Intrinsic::amdgcn_buffer_atomic_umin: 4813 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 4814 break; 4815 case Intrinsic::amdgcn_buffer_atomic_smax: 4816 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 4817 break; 4818 case Intrinsic::amdgcn_buffer_atomic_umax: 4819 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 4820 break; 4821 case Intrinsic::amdgcn_buffer_atomic_and: 4822 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 4823 break; 4824 case Intrinsic::amdgcn_buffer_atomic_or: 4825 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 4826 break; 4827 case Intrinsic::amdgcn_buffer_atomic_xor: 4828 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 4829 break; 4830 default: 4831 llvm_unreachable("unhandled atomic opcode"); 4832 } 4833 4834 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 4835 M->getMemOperand()); 4836 } 4837 4838 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 4839 SDValue Ops[] = { 4840 Op.getOperand(0), // Chain 4841 Op.getOperand(2), // src 4842 Op.getOperand(3), // cmp 4843 Op.getOperand(4), // rsrc 4844 Op.getOperand(5), // vindex 4845 Op.getOperand(6), // offset 4846 Op.getOperand(7) // slc 4847 }; 4848 EVT VT = Op.getValueType(); 4849 auto *M = cast<MemSDNode>(Op); 4850 4851 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 4852 Op->getVTList(), Ops, VT, M->getMemOperand()); 4853 } 4854 4855 // Basic sample. 4856 case Intrinsic::amdgcn_image_sample: 4857 case Intrinsic::amdgcn_image_sample_cl: 4858 case Intrinsic::amdgcn_image_sample_d: 4859 case Intrinsic::amdgcn_image_sample_d_cl: 4860 case Intrinsic::amdgcn_image_sample_l: 4861 case Intrinsic::amdgcn_image_sample_b: 4862 case Intrinsic::amdgcn_image_sample_b_cl: 4863 case Intrinsic::amdgcn_image_sample_lz: 4864 case Intrinsic::amdgcn_image_sample_cd: 4865 case Intrinsic::amdgcn_image_sample_cd_cl: 4866 4867 // Sample with comparison. 4868 case Intrinsic::amdgcn_image_sample_c: 4869 case Intrinsic::amdgcn_image_sample_c_cl: 4870 case Intrinsic::amdgcn_image_sample_c_d: 4871 case Intrinsic::amdgcn_image_sample_c_d_cl: 4872 case Intrinsic::amdgcn_image_sample_c_l: 4873 case Intrinsic::amdgcn_image_sample_c_b: 4874 case Intrinsic::amdgcn_image_sample_c_b_cl: 4875 case Intrinsic::amdgcn_image_sample_c_lz: 4876 case Intrinsic::amdgcn_image_sample_c_cd: 4877 case Intrinsic::amdgcn_image_sample_c_cd_cl: 4878 4879 // Sample with offsets. 4880 case Intrinsic::amdgcn_image_sample_o: 4881 case Intrinsic::amdgcn_image_sample_cl_o: 4882 case Intrinsic::amdgcn_image_sample_d_o: 4883 case Intrinsic::amdgcn_image_sample_d_cl_o: 4884 case Intrinsic::amdgcn_image_sample_l_o: 4885 case Intrinsic::amdgcn_image_sample_b_o: 4886 case Intrinsic::amdgcn_image_sample_b_cl_o: 4887 case Intrinsic::amdgcn_image_sample_lz_o: 4888 case Intrinsic::amdgcn_image_sample_cd_o: 4889 case Intrinsic::amdgcn_image_sample_cd_cl_o: 4890 4891 // Sample with comparison and offsets. 4892 case Intrinsic::amdgcn_image_sample_c_o: 4893 case Intrinsic::amdgcn_image_sample_c_cl_o: 4894 case Intrinsic::amdgcn_image_sample_c_d_o: 4895 case Intrinsic::amdgcn_image_sample_c_d_cl_o: 4896 case Intrinsic::amdgcn_image_sample_c_l_o: 4897 case Intrinsic::amdgcn_image_sample_c_b_o: 4898 case Intrinsic::amdgcn_image_sample_c_b_cl_o: 4899 case Intrinsic::amdgcn_image_sample_c_lz_o: 4900 case Intrinsic::amdgcn_image_sample_c_cd_o: 4901 case Intrinsic::amdgcn_image_sample_c_cd_cl_o: { 4902 // Replace dmask with everything disabled with undef. 4903 const ConstantSDNode *DMask = dyn_cast<ConstantSDNode>(Op.getOperand(5)); 4904 if (!DMask || DMask->isNullValue()) { 4905 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 4906 return DAG.getMergeValues({ Undef, Op.getOperand(0) }, SDLoc(Op)); 4907 } 4908 4909 return SDValue(); 4910 } 4911 default: 4912 return SDValue(); 4913 } 4914 } 4915 4916 SDValue SITargetLowering::handleD16VData(SDValue VData, 4917 SelectionDAG &DAG) const { 4918 EVT StoreVT = VData.getValueType(); 4919 SDLoc DL(VData); 4920 4921 if (StoreVT.isVector()) { 4922 assert ((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 4923 if (!Subtarget->hasUnpackedD16VMem()) { 4924 if (!isTypeLegal(StoreVT)) { 4925 // If Target supports packed vmem, we just need to workaround 4926 // the illegal type by casting to an equivalent one. 4927 EVT EquivStoreVT = getEquivalentMemType(*DAG.getContext(), StoreVT); 4928 return DAG.getNode(ISD::BITCAST, DL, EquivStoreVT, VData); 4929 } 4930 } else { // We need to unpack the packed data to store. 4931 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 4932 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 4933 EVT EquivStoreVT = (StoreVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32; 4934 return DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 4935 } 4936 } 4937 // No change for f16 and legal vector D16 types. 4938 return VData; 4939 } 4940 4941 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4942 SelectionDAG &DAG) const { 4943 SDLoc DL(Op); 4944 SDValue Chain = Op.getOperand(0); 4945 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 4946 MachineFunction &MF = DAG.getMachineFunction(); 4947 4948 switch (IntrinsicID) { 4949 case Intrinsic::amdgcn_exp: { 4950 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4951 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4952 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 4953 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 4954 4955 const SDValue Ops[] = { 4956 Chain, 4957 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4958 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4959 Op.getOperand(4), // src0 4960 Op.getOperand(5), // src1 4961 Op.getOperand(6), // src2 4962 Op.getOperand(7), // src3 4963 DAG.getTargetConstant(0, DL, MVT::i1), // compr 4964 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4965 }; 4966 4967 unsigned Opc = Done->isNullValue() ? 4968 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4969 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4970 } 4971 case Intrinsic::amdgcn_exp_compr: { 4972 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 4973 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 4974 SDValue Src0 = Op.getOperand(4); 4975 SDValue Src1 = Op.getOperand(5); 4976 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 4977 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 4978 4979 SDValue Undef = DAG.getUNDEF(MVT::f32); 4980 const SDValue Ops[] = { 4981 Chain, 4982 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 4983 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 4984 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 4985 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 4986 Undef, // src2 4987 Undef, // src3 4988 DAG.getTargetConstant(1, DL, MVT::i1), // compr 4989 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 4990 }; 4991 4992 unsigned Opc = Done->isNullValue() ? 4993 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 4994 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 4995 } 4996 case Intrinsic::amdgcn_s_sendmsg: 4997 case Intrinsic::amdgcn_s_sendmsghalt: { 4998 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 4999 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 5000 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 5001 SDValue Glue = Chain.getValue(1); 5002 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 5003 Op.getOperand(2), Glue); 5004 } 5005 case Intrinsic::amdgcn_init_exec: { 5006 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 5007 Op.getOperand(2)); 5008 } 5009 case Intrinsic::amdgcn_init_exec_from_input: { 5010 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 5011 Op.getOperand(2), Op.getOperand(3)); 5012 } 5013 case AMDGPUIntrinsic::AMDGPU_kill: { 5014 SDValue Src = Op.getOperand(2); 5015 if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) { 5016 if (!K->isNegative()) 5017 return Chain; 5018 5019 SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32); 5020 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne); 5021 } 5022 5023 SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src); 5024 return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast); 5025 } 5026 case Intrinsic::amdgcn_s_barrier: { 5027 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 5028 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 5029 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 5030 if (WGSize <= ST.getWavefrontSize()) 5031 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 5032 Op.getOperand(0)), 0); 5033 } 5034 return SDValue(); 5035 }; 5036 case AMDGPUIntrinsic::SI_tbuffer_store: { 5037 5038 // Extract vindex and voffset from vaddr as appropriate 5039 const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10)); 5040 const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11)); 5041 SDValue VAddr = Op.getOperand(5); 5042 5043 SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32); 5044 5045 assert(!(OffEn->isOne() && IdxEn->isOne()) && 5046 "Legacy intrinsic doesn't support both offset and index - use new version"); 5047 5048 SDValue VIndex = IdxEn->isOne() ? VAddr : Zero; 5049 SDValue VOffset = OffEn->isOne() ? VAddr : Zero; 5050 5051 // Deal with the vec-3 case 5052 const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4)); 5053 auto Opcode = NumChannels->getZExtValue() == 3 ? 5054 AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT; 5055 5056 SDValue Ops[] = { 5057 Chain, 5058 Op.getOperand(3), // vdata 5059 Op.getOperand(2), // rsrc 5060 VIndex, 5061 VOffset, 5062 Op.getOperand(6), // soffset 5063 Op.getOperand(7), // inst_offset 5064 Op.getOperand(8), // dfmt 5065 Op.getOperand(9), // nfmt 5066 Op.getOperand(12), // glc 5067 Op.getOperand(13), // slc 5068 }; 5069 5070 assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 && 5071 "Value of tfe other than zero is unsupported"); 5072 5073 EVT VT = Op.getOperand(3).getValueType(); 5074 MachineMemOperand *MMO = MF.getMachineMemOperand( 5075 MachinePointerInfo(), 5076 MachineMemOperand::MOStore, 5077 VT.getStoreSize(), 4); 5078 return DAG.getMemIntrinsicNode(Opcode, DL, 5079 Op->getVTList(), Ops, VT, MMO); 5080 } 5081 5082 case Intrinsic::amdgcn_tbuffer_store: { 5083 SDValue VData = Op.getOperand(2); 5084 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5085 if (IsD16) 5086 VData = handleD16VData(VData, DAG); 5087 SDValue Ops[] = { 5088 Chain, 5089 VData, // vdata 5090 Op.getOperand(3), // rsrc 5091 Op.getOperand(4), // vindex 5092 Op.getOperand(5), // voffset 5093 Op.getOperand(6), // soffset 5094 Op.getOperand(7), // offset 5095 Op.getOperand(8), // dfmt 5096 Op.getOperand(9), // nfmt 5097 Op.getOperand(10), // glc 5098 Op.getOperand(11) // slc 5099 }; 5100 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 5101 AMDGPUISD::TBUFFER_STORE_FORMAT; 5102 MemSDNode *M = cast<MemSDNode>(Op); 5103 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5104 M->getMemoryVT(), M->getMemOperand()); 5105 } 5106 5107 case Intrinsic::amdgcn_buffer_store: 5108 case Intrinsic::amdgcn_buffer_store_format: { 5109 SDValue VData = Op.getOperand(2); 5110 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5111 if (IsD16) 5112 VData = handleD16VData(VData, DAG); 5113 SDValue Ops[] = { 5114 Chain, 5115 VData, // vdata 5116 Op.getOperand(3), // rsrc 5117 Op.getOperand(4), // vindex 5118 Op.getOperand(5), // offset 5119 Op.getOperand(6), // glc 5120 Op.getOperand(7) // slc 5121 }; 5122 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 5123 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 5124 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 5125 MemSDNode *M = cast<MemSDNode>(Op); 5126 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5127 M->getMemoryVT(), M->getMemOperand()); 5128 } 5129 5130 case Intrinsic::amdgcn_image_store: 5131 case Intrinsic::amdgcn_image_store_mip: { 5132 SDValue VData = Op.getOperand(2); 5133 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 5134 if (IsD16) 5135 VData = handleD16VData(VData, DAG); 5136 SDValue Ops[] = { 5137 Chain, // Chain 5138 VData, // vdata 5139 Op.getOperand(3), // vaddr 5140 Op.getOperand(4), // rsrc 5141 Op.getOperand(5), // dmask 5142 Op.getOperand(6), // glc 5143 Op.getOperand(7), // slc 5144 Op.getOperand(8), // lwe 5145 Op.getOperand(9) // da 5146 }; 5147 unsigned Opc = (IntrinsicID==Intrinsic::amdgcn_image_store) ? 5148 AMDGPUISD::IMAGE_STORE : AMDGPUISD::IMAGE_STORE_MIP; 5149 MemSDNode *M = cast<MemSDNode>(Op); 5150 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 5151 M->getMemoryVT(), M->getMemOperand()); 5152 } 5153 5154 default: { 5155 const AMDGPU::D16ImageDimIntrinsic *D16ImageDimIntr = 5156 AMDGPU::lookupD16ImageDimIntrinsicByIntr(IntrinsicID); 5157 if (D16ImageDimIntr) { 5158 SDValue VData = Op.getOperand(2); 5159 EVT StoreVT = VData.getValueType(); 5160 if ((StoreVT == MVT::v2f16 && !isTypeLegal(StoreVT)) || 5161 StoreVT == MVT::v4f16) { 5162 VData = handleD16VData(VData, DAG); 5163 5164 SmallVector<SDValue, 12> Ops; 5165 for (auto Value : Op.getNode()->op_values()) 5166 Ops.push_back(Value); 5167 Ops[1] = DAG.getConstant(D16ImageDimIntr->D16HelperIntr, DL, MVT::i32); 5168 Ops[2] = VData; 5169 5170 MemSDNode *M = cast<MemSDNode>(Op); 5171 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Op->getVTList(), 5172 Ops, M->getMemoryVT(), 5173 M->getMemOperand()); 5174 } 5175 } 5176 5177 return Op; 5178 } 5179 } 5180 } 5181 5182 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 5183 SDLoc DL(Op); 5184 LoadSDNode *Load = cast<LoadSDNode>(Op); 5185 ISD::LoadExtType ExtType = Load->getExtensionType(); 5186 EVT MemVT = Load->getMemoryVT(); 5187 5188 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 5189 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 5190 return SDValue(); 5191 5192 // FIXME: Copied from PPC 5193 // First, load into 32 bits, then truncate to 1 bit. 5194 5195 SDValue Chain = Load->getChain(); 5196 SDValue BasePtr = Load->getBasePtr(); 5197 MachineMemOperand *MMO = Load->getMemOperand(); 5198 5199 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 5200 5201 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 5202 BasePtr, RealMemVT, MMO); 5203 5204 SDValue Ops[] = { 5205 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 5206 NewLD.getValue(1) 5207 }; 5208 5209 return DAG.getMergeValues(Ops, DL); 5210 } 5211 5212 if (!MemVT.isVector()) 5213 return SDValue(); 5214 5215 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 5216 "Custom lowering for non-i32 vectors hasn't been implemented."); 5217 5218 unsigned Alignment = Load->getAlignment(); 5219 unsigned AS = Load->getAddressSpace(); 5220 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 5221 AS, Alignment)) { 5222 SDValue Ops[2]; 5223 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 5224 return DAG.getMergeValues(Ops, DL); 5225 } 5226 5227 MachineFunction &MF = DAG.getMachineFunction(); 5228 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 5229 // If there is a possibilty that flat instruction access scratch memory 5230 // then we need to use the same legalization rules we use for private. 5231 if (AS == AMDGPUASI.FLAT_ADDRESS) 5232 AS = MFI->hasFlatScratchInit() ? 5233 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 5234 5235 unsigned NumElements = MemVT.getVectorNumElements(); 5236 5237 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 5238 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) { 5239 if (!Op->isDivergent() && Alignment >= 4) 5240 return SDValue(); 5241 // Non-uniform loads will be selected to MUBUF instructions, so they 5242 // have the same legalization requirements as global and private 5243 // loads. 5244 // 5245 } 5246 5247 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 5248 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT || 5249 AS == AMDGPUASI.GLOBAL_ADDRESS) { 5250 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 5251 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 5252 Alignment >= 4) 5253 return SDValue(); 5254 // Non-uniform loads will be selected to MUBUF instructions, so they 5255 // have the same legalization requirements as global and private 5256 // loads. 5257 // 5258 } 5259 if (AS == AMDGPUASI.CONSTANT_ADDRESS || 5260 AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT || 5261 AS == AMDGPUASI.GLOBAL_ADDRESS || 5262 AS == AMDGPUASI.FLAT_ADDRESS) { 5263 if (NumElements > 4) 5264 return SplitVectorLoad(Op, DAG); 5265 // v4 loads are supported for private and global memory. 5266 return SDValue(); 5267 } 5268 if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 5269 // Depending on the setting of the private_element_size field in the 5270 // resource descriptor, we can only make private accesses up to a certain 5271 // size. 5272 switch (Subtarget->getMaxPrivateElementSize()) { 5273 case 4: 5274 return scalarizeVectorLoad(Load, DAG); 5275 case 8: 5276 if (NumElements > 2) 5277 return SplitVectorLoad(Op, DAG); 5278 return SDValue(); 5279 case 16: 5280 // Same as global/flat 5281 if (NumElements > 4) 5282 return SplitVectorLoad(Op, DAG); 5283 return SDValue(); 5284 default: 5285 llvm_unreachable("unsupported private_element_size"); 5286 } 5287 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 5288 // Use ds_read_b128 if possible. 5289 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 5290 MemVT.getStoreSize() == 16) 5291 return SDValue(); 5292 5293 if (NumElements > 2) 5294 return SplitVectorLoad(Op, DAG); 5295 } 5296 return SDValue(); 5297 } 5298 5299 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 5300 if (Op.getValueType() != MVT::i64) 5301 return SDValue(); 5302 5303 SDLoc DL(Op); 5304 SDValue Cond = Op.getOperand(0); 5305 5306 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 5307 SDValue One = DAG.getConstant(1, DL, MVT::i32); 5308 5309 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 5310 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 5311 5312 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 5313 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 5314 5315 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 5316 5317 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 5318 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 5319 5320 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 5321 5322 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 5323 return DAG.getNode(ISD::BITCAST, DL, MVT::i64, Res); 5324 } 5325 5326 // Catch division cases where we can use shortcuts with rcp and rsq 5327 // instructions. 5328 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 5329 SelectionDAG &DAG) const { 5330 SDLoc SL(Op); 5331 SDValue LHS = Op.getOperand(0); 5332 SDValue RHS = Op.getOperand(1); 5333 EVT VT = Op.getValueType(); 5334 const SDNodeFlags Flags = Op->getFlags(); 5335 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 5336 5337 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 5338 return SDValue(); 5339 5340 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 5341 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 5342 if (CLHS->isExactlyValue(1.0)) { 5343 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 5344 // the CI documentation has a worst case error of 1 ulp. 5345 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 5346 // use it as long as we aren't trying to use denormals. 5347 // 5348 // v_rcp_f16 and v_rsq_f16 DO support denormals. 5349 5350 // 1.0 / sqrt(x) -> rsq(x) 5351 5352 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 5353 // error seems really high at 2^29 ULP. 5354 if (RHS.getOpcode() == ISD::FSQRT) 5355 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 5356 5357 // 1.0 / x -> rcp(x) 5358 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 5359 } 5360 5361 // Same as for 1.0, but expand the sign out of the constant. 5362 if (CLHS->isExactlyValue(-1.0)) { 5363 // -1.0 / x -> rcp (fneg x) 5364 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 5365 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 5366 } 5367 } 5368 } 5369 5370 if (Unsafe) { 5371 // Turn into multiply by the reciprocal. 5372 // x / y -> x * (1.0 / y) 5373 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 5374 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 5375 } 5376 5377 return SDValue(); 5378 } 5379 5380 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 5381 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 5382 if (GlueChain->getNumValues() <= 1) { 5383 return DAG.getNode(Opcode, SL, VT, A, B); 5384 } 5385 5386 assert(GlueChain->getNumValues() == 3); 5387 5388 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 5389 switch (Opcode) { 5390 default: llvm_unreachable("no chain equivalent for opcode"); 5391 case ISD::FMUL: 5392 Opcode = AMDGPUISD::FMUL_W_CHAIN; 5393 break; 5394 } 5395 5396 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 5397 GlueChain.getValue(2)); 5398 } 5399 5400 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 5401 EVT VT, SDValue A, SDValue B, SDValue C, 5402 SDValue GlueChain) { 5403 if (GlueChain->getNumValues() <= 1) { 5404 return DAG.getNode(Opcode, SL, VT, A, B, C); 5405 } 5406 5407 assert(GlueChain->getNumValues() == 3); 5408 5409 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 5410 switch (Opcode) { 5411 default: llvm_unreachable("no chain equivalent for opcode"); 5412 case ISD::FMA: 5413 Opcode = AMDGPUISD::FMA_W_CHAIN; 5414 break; 5415 } 5416 5417 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 5418 GlueChain.getValue(2)); 5419 } 5420 5421 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 5422 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 5423 return FastLowered; 5424 5425 SDLoc SL(Op); 5426 SDValue Src0 = Op.getOperand(0); 5427 SDValue Src1 = Op.getOperand(1); 5428 5429 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 5430 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 5431 5432 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 5433 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 5434 5435 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 5436 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 5437 5438 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 5439 } 5440 5441 // Faster 2.5 ULP division that does not support denormals. 5442 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 5443 SDLoc SL(Op); 5444 SDValue LHS = Op.getOperand(1); 5445 SDValue RHS = Op.getOperand(2); 5446 5447 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 5448 5449 const APFloat K0Val(BitsToFloat(0x6f800000)); 5450 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 5451 5452 const APFloat K1Val(BitsToFloat(0x2f800000)); 5453 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 5454 5455 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 5456 5457 EVT SetCCVT = 5458 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 5459 5460 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 5461 5462 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 5463 5464 // TODO: Should this propagate fast-math-flags? 5465 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 5466 5467 // rcp does not support denormals. 5468 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 5469 5470 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 5471 5472 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 5473 } 5474 5475 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 5476 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 5477 return FastLowered; 5478 5479 SDLoc SL(Op); 5480 SDValue LHS = Op.getOperand(0); 5481 SDValue RHS = Op.getOperand(1); 5482 5483 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 5484 5485 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 5486 5487 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 5488 RHS, RHS, LHS); 5489 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 5490 LHS, RHS, LHS); 5491 5492 // Denominator is scaled to not be denormal, so using rcp is ok. 5493 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 5494 DenominatorScaled); 5495 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 5496 DenominatorScaled); 5497 5498 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 5499 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 5500 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 5501 5502 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 5503 5504 if (!Subtarget->hasFP32Denormals()) { 5505 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 5506 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 5507 SL, MVT::i32); 5508 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 5509 DAG.getEntryNode(), 5510 EnableDenormValue, BitField); 5511 SDValue Ops[3] = { 5512 NegDivScale0, 5513 EnableDenorm.getValue(0), 5514 EnableDenorm.getValue(1) 5515 }; 5516 5517 NegDivScale0 = DAG.getMergeValues(Ops, SL); 5518 } 5519 5520 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 5521 ApproxRcp, One, NegDivScale0); 5522 5523 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 5524 ApproxRcp, Fma0); 5525 5526 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 5527 Fma1, Fma1); 5528 5529 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 5530 NumeratorScaled, Mul); 5531 5532 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 5533 5534 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 5535 NumeratorScaled, Fma3); 5536 5537 if (!Subtarget->hasFP32Denormals()) { 5538 const SDValue DisableDenormValue = 5539 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 5540 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 5541 Fma4.getValue(1), 5542 DisableDenormValue, 5543 BitField, 5544 Fma4.getValue(2)); 5545 5546 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 5547 DisableDenorm, DAG.getRoot()); 5548 DAG.setRoot(OutputChain); 5549 } 5550 5551 SDValue Scale = NumeratorScaled.getValue(1); 5552 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 5553 Fma4, Fma1, Fma3, Scale); 5554 5555 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 5556 } 5557 5558 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 5559 if (DAG.getTarget().Options.UnsafeFPMath) 5560 return lowerFastUnsafeFDIV(Op, DAG); 5561 5562 SDLoc SL(Op); 5563 SDValue X = Op.getOperand(0); 5564 SDValue Y = Op.getOperand(1); 5565 5566 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 5567 5568 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 5569 5570 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 5571 5572 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 5573 5574 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 5575 5576 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 5577 5578 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 5579 5580 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 5581 5582 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 5583 5584 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 5585 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 5586 5587 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 5588 NegDivScale0, Mul, DivScale1); 5589 5590 SDValue Scale; 5591 5592 if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) { 5593 // Workaround a hardware bug on SI where the condition output from div_scale 5594 // is not usable. 5595 5596 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 5597 5598 // Figure out if the scale to use for div_fmas. 5599 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 5600 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 5601 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 5602 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 5603 5604 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 5605 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 5606 5607 SDValue Scale0Hi 5608 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 5609 SDValue Scale1Hi 5610 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 5611 5612 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 5613 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 5614 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 5615 } else { 5616 Scale = DivScale1.getValue(1); 5617 } 5618 5619 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 5620 Fma4, Fma3, Mul, Scale); 5621 5622 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 5623 } 5624 5625 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 5626 EVT VT = Op.getValueType(); 5627 5628 if (VT == MVT::f32) 5629 return LowerFDIV32(Op, DAG); 5630 5631 if (VT == MVT::f64) 5632 return LowerFDIV64(Op, DAG); 5633 5634 if (VT == MVT::f16) 5635 return LowerFDIV16(Op, DAG); 5636 5637 llvm_unreachable("Unexpected type for fdiv"); 5638 } 5639 5640 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 5641 SDLoc DL(Op); 5642 StoreSDNode *Store = cast<StoreSDNode>(Op); 5643 EVT VT = Store->getMemoryVT(); 5644 5645 if (VT == MVT::i1) { 5646 return DAG.getTruncStore(Store->getChain(), DL, 5647 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 5648 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 5649 } 5650 5651 assert(VT.isVector() && 5652 Store->getValue().getValueType().getScalarType() == MVT::i32); 5653 5654 unsigned AS = Store->getAddressSpace(); 5655 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 5656 AS, Store->getAlignment())) { 5657 return expandUnalignedStore(Store, DAG); 5658 } 5659 5660 MachineFunction &MF = DAG.getMachineFunction(); 5661 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 5662 // If there is a possibilty that flat instruction access scratch memory 5663 // then we need to use the same legalization rules we use for private. 5664 if (AS == AMDGPUASI.FLAT_ADDRESS) 5665 AS = MFI->hasFlatScratchInit() ? 5666 AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS; 5667 5668 unsigned NumElements = VT.getVectorNumElements(); 5669 if (AS == AMDGPUASI.GLOBAL_ADDRESS || 5670 AS == AMDGPUASI.FLAT_ADDRESS) { 5671 if (NumElements > 4) 5672 return SplitVectorStore(Op, DAG); 5673 return SDValue(); 5674 } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) { 5675 switch (Subtarget->getMaxPrivateElementSize()) { 5676 case 4: 5677 return scalarizeVectorStore(Store, DAG); 5678 case 8: 5679 if (NumElements > 2) 5680 return SplitVectorStore(Op, DAG); 5681 return SDValue(); 5682 case 16: 5683 if (NumElements > 4) 5684 return SplitVectorStore(Op, DAG); 5685 return SDValue(); 5686 default: 5687 llvm_unreachable("unsupported private_element_size"); 5688 } 5689 } else if (AS == AMDGPUASI.LOCAL_ADDRESS) { 5690 // Use ds_write_b128 if possible. 5691 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 5692 VT.getStoreSize() == 16) 5693 return SDValue(); 5694 5695 if (NumElements > 2) 5696 return SplitVectorStore(Op, DAG); 5697 return SDValue(); 5698 } else { 5699 llvm_unreachable("unhandled address space"); 5700 } 5701 } 5702 5703 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 5704 SDLoc DL(Op); 5705 EVT VT = Op.getValueType(); 5706 SDValue Arg = Op.getOperand(0); 5707 // TODO: Should this propagate fast-math-flags? 5708 SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT, 5709 DAG.getNode(ISD::FMUL, DL, VT, Arg, 5710 DAG.getConstantFP(0.5/M_PI, DL, 5711 VT))); 5712 5713 switch (Op.getOpcode()) { 5714 case ISD::FCOS: 5715 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart); 5716 case ISD::FSIN: 5717 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart); 5718 default: 5719 llvm_unreachable("Wrong trig opcode"); 5720 } 5721 } 5722 5723 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 5724 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 5725 assert(AtomicNode->isCompareAndSwap()); 5726 unsigned AS = AtomicNode->getAddressSpace(); 5727 5728 // No custom lowering required for local address space 5729 if (!isFlatGlobalAddrSpace(AS, AMDGPUASI)) 5730 return Op; 5731 5732 // Non-local address space requires custom lowering for atomic compare 5733 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 5734 SDLoc DL(Op); 5735 SDValue ChainIn = Op.getOperand(0); 5736 SDValue Addr = Op.getOperand(1); 5737 SDValue Old = Op.getOperand(2); 5738 SDValue New = Op.getOperand(3); 5739 EVT VT = Op.getValueType(); 5740 MVT SimpleVT = VT.getSimpleVT(); 5741 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 5742 5743 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 5744 SDValue Ops[] = { ChainIn, Addr, NewOld }; 5745 5746 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 5747 Ops, VT, AtomicNode->getMemOperand()); 5748 } 5749 5750 //===----------------------------------------------------------------------===// 5751 // Custom DAG optimizations 5752 //===----------------------------------------------------------------------===// 5753 5754 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 5755 DAGCombinerInfo &DCI) const { 5756 EVT VT = N->getValueType(0); 5757 EVT ScalarVT = VT.getScalarType(); 5758 if (ScalarVT != MVT::f32) 5759 return SDValue(); 5760 5761 SelectionDAG &DAG = DCI.DAG; 5762 SDLoc DL(N); 5763 5764 SDValue Src = N->getOperand(0); 5765 EVT SrcVT = Src.getValueType(); 5766 5767 // TODO: We could try to match extracting the higher bytes, which would be 5768 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 5769 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 5770 // about in practice. 5771 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 5772 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 5773 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 5774 DCI.AddToWorklist(Cvt.getNode()); 5775 return Cvt; 5776 } 5777 } 5778 5779 return SDValue(); 5780 } 5781 5782 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 5783 5784 // This is a variant of 5785 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 5786 // 5787 // The normal DAG combiner will do this, but only if the add has one use since 5788 // that would increase the number of instructions. 5789 // 5790 // This prevents us from seeing a constant offset that can be folded into a 5791 // memory instruction's addressing mode. If we know the resulting add offset of 5792 // a pointer can be folded into an addressing offset, we can replace the pointer 5793 // operand with the add of new constant offset. This eliminates one of the uses, 5794 // and may allow the remaining use to also be simplified. 5795 // 5796 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 5797 unsigned AddrSpace, 5798 EVT MemVT, 5799 DAGCombinerInfo &DCI) const { 5800 SDValue N0 = N->getOperand(0); 5801 SDValue N1 = N->getOperand(1); 5802 5803 // We only do this to handle cases where it's profitable when there are 5804 // multiple uses of the add, so defer to the standard combine. 5805 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 5806 N0->hasOneUse()) 5807 return SDValue(); 5808 5809 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 5810 if (!CN1) 5811 return SDValue(); 5812 5813 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 5814 if (!CAdd) 5815 return SDValue(); 5816 5817 // If the resulting offset is too large, we can't fold it into the addressing 5818 // mode offset. 5819 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 5820 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 5821 5822 AddrMode AM; 5823 AM.HasBaseReg = true; 5824 AM.BaseOffs = Offset.getSExtValue(); 5825 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 5826 return SDValue(); 5827 5828 SelectionDAG &DAG = DCI.DAG; 5829 SDLoc SL(N); 5830 EVT VT = N->getValueType(0); 5831 5832 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 5833 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 5834 5835 SDNodeFlags Flags; 5836 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 5837 (N0.getOpcode() == ISD::OR || 5838 N0->getFlags().hasNoUnsignedWrap())); 5839 5840 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 5841 } 5842 5843 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 5844 DAGCombinerInfo &DCI) const { 5845 SDValue Ptr = N->getBasePtr(); 5846 SelectionDAG &DAG = DCI.DAG; 5847 SDLoc SL(N); 5848 5849 // TODO: We could also do this for multiplies. 5850 if (Ptr.getOpcode() == ISD::SHL) { 5851 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 5852 N->getMemoryVT(), DCI); 5853 if (NewPtr) { 5854 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 5855 5856 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 5857 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 5858 } 5859 } 5860 5861 return SDValue(); 5862 } 5863 5864 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 5865 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 5866 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 5867 (Opc == ISD::XOR && Val == 0); 5868 } 5869 5870 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 5871 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 5872 // integer combine opportunities since most 64-bit operations are decomposed 5873 // this way. TODO: We won't want this for SALU especially if it is an inline 5874 // immediate. 5875 SDValue SITargetLowering::splitBinaryBitConstantOp( 5876 DAGCombinerInfo &DCI, 5877 const SDLoc &SL, 5878 unsigned Opc, SDValue LHS, 5879 const ConstantSDNode *CRHS) const { 5880 uint64_t Val = CRHS->getZExtValue(); 5881 uint32_t ValLo = Lo_32(Val); 5882 uint32_t ValHi = Hi_32(Val); 5883 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 5884 5885 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 5886 bitOpWithConstantIsReducible(Opc, ValHi)) || 5887 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 5888 // If we need to materialize a 64-bit immediate, it will be split up later 5889 // anyway. Avoid creating the harder to understand 64-bit immediate 5890 // materialization. 5891 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 5892 } 5893 5894 return SDValue(); 5895 } 5896 5897 // Returns true if argument is a boolean value which is not serialized into 5898 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 5899 static bool isBoolSGPR(SDValue V) { 5900 if (V.getValueType() != MVT::i1) 5901 return false; 5902 switch (V.getOpcode()) { 5903 default: break; 5904 case ISD::SETCC: 5905 case ISD::AND: 5906 case ISD::OR: 5907 case ISD::XOR: 5908 case AMDGPUISD::FP_CLASS: 5909 return true; 5910 } 5911 return false; 5912 } 5913 5914 SDValue SITargetLowering::performAndCombine(SDNode *N, 5915 DAGCombinerInfo &DCI) const { 5916 if (DCI.isBeforeLegalize()) 5917 return SDValue(); 5918 5919 SelectionDAG &DAG = DCI.DAG; 5920 EVT VT = N->getValueType(0); 5921 SDValue LHS = N->getOperand(0); 5922 SDValue RHS = N->getOperand(1); 5923 5924 5925 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 5926 if (VT == MVT::i64 && CRHS) { 5927 if (SDValue Split 5928 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 5929 return Split; 5930 } 5931 5932 if (CRHS && VT == MVT::i32) { 5933 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 5934 // nb = number of trailing zeroes in mask 5935 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 5936 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 5937 uint64_t Mask = CRHS->getZExtValue(); 5938 unsigned Bits = countPopulation(Mask); 5939 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 5940 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 5941 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 5942 unsigned Shift = CShift->getZExtValue(); 5943 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 5944 unsigned Offset = NB + Shift; 5945 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 5946 SDLoc SL(N); 5947 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 5948 LHS->getOperand(0), 5949 DAG.getConstant(Offset, SL, MVT::i32), 5950 DAG.getConstant(Bits, SL, MVT::i32)); 5951 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 5952 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 5953 DAG.getValueType(NarrowVT)); 5954 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 5955 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 5956 return Shl; 5957 } 5958 } 5959 } 5960 } 5961 5962 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 5963 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 5964 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 5965 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 5966 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 5967 5968 SDValue X = LHS.getOperand(0); 5969 SDValue Y = RHS.getOperand(0); 5970 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 5971 return SDValue(); 5972 5973 if (LCC == ISD::SETO) { 5974 if (X != LHS.getOperand(1)) 5975 return SDValue(); 5976 5977 if (RCC == ISD::SETUNE) { 5978 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 5979 if (!C1 || !C1->isInfinity() || C1->isNegative()) 5980 return SDValue(); 5981 5982 const uint32_t Mask = SIInstrFlags::N_NORMAL | 5983 SIInstrFlags::N_SUBNORMAL | 5984 SIInstrFlags::N_ZERO | 5985 SIInstrFlags::P_ZERO | 5986 SIInstrFlags::P_SUBNORMAL | 5987 SIInstrFlags::P_NORMAL; 5988 5989 static_assert(((~(SIInstrFlags::S_NAN | 5990 SIInstrFlags::Q_NAN | 5991 SIInstrFlags::N_INFINITY | 5992 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 5993 "mask not equal"); 5994 5995 SDLoc DL(N); 5996 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 5997 X, DAG.getConstant(Mask, DL, MVT::i32)); 5998 } 5999 } 6000 } 6001 6002 if (VT == MVT::i32 && 6003 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 6004 // and x, (sext cc from i1) => select cc, x, 0 6005 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 6006 std::swap(LHS, RHS); 6007 if (isBoolSGPR(RHS.getOperand(0))) 6008 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 6009 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 6010 } 6011 6012 return SDValue(); 6013 } 6014 6015 SDValue SITargetLowering::performOrCombine(SDNode *N, 6016 DAGCombinerInfo &DCI) const { 6017 SelectionDAG &DAG = DCI.DAG; 6018 SDValue LHS = N->getOperand(0); 6019 SDValue RHS = N->getOperand(1); 6020 6021 EVT VT = N->getValueType(0); 6022 if (VT == MVT::i1) { 6023 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 6024 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 6025 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 6026 SDValue Src = LHS.getOperand(0); 6027 if (Src != RHS.getOperand(0)) 6028 return SDValue(); 6029 6030 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6031 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 6032 if (!CLHS || !CRHS) 6033 return SDValue(); 6034 6035 // Only 10 bits are used. 6036 static const uint32_t MaxMask = 0x3ff; 6037 6038 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 6039 SDLoc DL(N); 6040 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 6041 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 6042 } 6043 6044 return SDValue(); 6045 } 6046 6047 if (VT != MVT::i64) 6048 return SDValue(); 6049 6050 // TODO: This could be a generic combine with a predicate for extracting the 6051 // high half of an integer being free. 6052 6053 // (or i64:x, (zero_extend i32:y)) -> 6054 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 6055 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 6056 RHS.getOpcode() != ISD::ZERO_EXTEND) 6057 std::swap(LHS, RHS); 6058 6059 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 6060 SDValue ExtSrc = RHS.getOperand(0); 6061 EVT SrcVT = ExtSrc.getValueType(); 6062 if (SrcVT == MVT::i32) { 6063 SDLoc SL(N); 6064 SDValue LowLHS, HiBits; 6065 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 6066 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 6067 6068 DCI.AddToWorklist(LowOr.getNode()); 6069 DCI.AddToWorklist(HiBits.getNode()); 6070 6071 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 6072 LowOr, HiBits); 6073 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 6074 } 6075 } 6076 6077 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6078 if (CRHS) { 6079 if (SDValue Split 6080 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 6081 return Split; 6082 } 6083 6084 return SDValue(); 6085 } 6086 6087 SDValue SITargetLowering::performXorCombine(SDNode *N, 6088 DAGCombinerInfo &DCI) const { 6089 EVT VT = N->getValueType(0); 6090 if (VT != MVT::i64) 6091 return SDValue(); 6092 6093 SDValue LHS = N->getOperand(0); 6094 SDValue RHS = N->getOperand(1); 6095 6096 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 6097 if (CRHS) { 6098 if (SDValue Split 6099 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 6100 return Split; 6101 } 6102 6103 return SDValue(); 6104 } 6105 6106 // Instructions that will be lowered with a final instruction that zeros the 6107 // high result bits. 6108 // XXX - probably only need to list legal operations. 6109 static bool fp16SrcZerosHighBits(unsigned Opc) { 6110 switch (Opc) { 6111 case ISD::FADD: 6112 case ISD::FSUB: 6113 case ISD::FMUL: 6114 case ISD::FDIV: 6115 case ISD::FREM: 6116 case ISD::FMA: 6117 case ISD::FMAD: 6118 case ISD::FCANONICALIZE: 6119 case ISD::FP_ROUND: 6120 case ISD::UINT_TO_FP: 6121 case ISD::SINT_TO_FP: 6122 case ISD::FABS: 6123 // Fabs is lowered to a bit operation, but it's an and which will clear the 6124 // high bits anyway. 6125 case ISD::FSQRT: 6126 case ISD::FSIN: 6127 case ISD::FCOS: 6128 case ISD::FPOWI: 6129 case ISD::FPOW: 6130 case ISD::FLOG: 6131 case ISD::FLOG2: 6132 case ISD::FLOG10: 6133 case ISD::FEXP: 6134 case ISD::FEXP2: 6135 case ISD::FCEIL: 6136 case ISD::FTRUNC: 6137 case ISD::FRINT: 6138 case ISD::FNEARBYINT: 6139 case ISD::FROUND: 6140 case ISD::FFLOOR: 6141 case ISD::FMINNUM: 6142 case ISD::FMAXNUM: 6143 case AMDGPUISD::FRACT: 6144 case AMDGPUISD::CLAMP: 6145 case AMDGPUISD::COS_HW: 6146 case AMDGPUISD::SIN_HW: 6147 case AMDGPUISD::FMIN3: 6148 case AMDGPUISD::FMAX3: 6149 case AMDGPUISD::FMED3: 6150 case AMDGPUISD::FMAD_FTZ: 6151 case AMDGPUISD::RCP: 6152 case AMDGPUISD::RSQ: 6153 case AMDGPUISD::LDEXP: 6154 return true; 6155 default: 6156 // fcopysign, select and others may be lowered to 32-bit bit operations 6157 // which don't zero the high bits. 6158 return false; 6159 } 6160 } 6161 6162 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 6163 DAGCombinerInfo &DCI) const { 6164 if (!Subtarget->has16BitInsts() || 6165 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6166 return SDValue(); 6167 6168 EVT VT = N->getValueType(0); 6169 if (VT != MVT::i32) 6170 return SDValue(); 6171 6172 SDValue Src = N->getOperand(0); 6173 if (Src.getValueType() != MVT::i16) 6174 return SDValue(); 6175 6176 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 6177 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 6178 if (Src.getOpcode() == ISD::BITCAST) { 6179 SDValue BCSrc = Src.getOperand(0); 6180 if (BCSrc.getValueType() == MVT::f16 && 6181 fp16SrcZerosHighBits(BCSrc.getOpcode())) 6182 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 6183 } 6184 6185 return SDValue(); 6186 } 6187 6188 SDValue SITargetLowering::performClassCombine(SDNode *N, 6189 DAGCombinerInfo &DCI) const { 6190 SelectionDAG &DAG = DCI.DAG; 6191 SDValue Mask = N->getOperand(1); 6192 6193 // fp_class x, 0 -> false 6194 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 6195 if (CMask->isNullValue()) 6196 return DAG.getConstant(0, SDLoc(N), MVT::i1); 6197 } 6198 6199 if (N->getOperand(0).isUndef()) 6200 return DAG.getUNDEF(MVT::i1); 6201 6202 return SDValue(); 6203 } 6204 6205 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) { 6206 if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions()) 6207 return true; 6208 6209 return DAG.isKnownNeverNaN(Op); 6210 } 6211 6212 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op, 6213 const SISubtarget *ST, unsigned MaxDepth=5) { 6214 // If source is a result of another standard FP operation it is already in 6215 // canonical form. 6216 6217 switch (Op.getOpcode()) { 6218 default: 6219 break; 6220 6221 // These will flush denorms if required. 6222 case ISD::FADD: 6223 case ISD::FSUB: 6224 case ISD::FMUL: 6225 case ISD::FSQRT: 6226 case ISD::FCEIL: 6227 case ISD::FFLOOR: 6228 case ISD::FMA: 6229 case ISD::FMAD: 6230 6231 case ISD::FCANONICALIZE: 6232 return true; 6233 6234 case ISD::FP_ROUND: 6235 return Op.getValueType().getScalarType() != MVT::f16 || 6236 ST->hasFP16Denormals(); 6237 6238 case ISD::FP_EXTEND: 6239 return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 || 6240 ST->hasFP16Denormals(); 6241 6242 case ISD::FP16_TO_FP: 6243 case ISD::FP_TO_FP16: 6244 return ST->hasFP16Denormals(); 6245 6246 // It can/will be lowered or combined as a bit operation. 6247 // Need to check their input recursively to handle. 6248 case ISD::FNEG: 6249 case ISD::FABS: 6250 return (MaxDepth > 0) && 6251 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1); 6252 6253 case ISD::FSIN: 6254 case ISD::FCOS: 6255 case ISD::FSINCOS: 6256 return Op.getValueType().getScalarType() != MVT::f16; 6257 6258 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. 6259 // For such targets need to check their input recursively. 6260 case ISD::FMINNUM: 6261 case ISD::FMAXNUM: 6262 case ISD::FMINNAN: 6263 case ISD::FMAXNAN: 6264 6265 if (ST->supportsMinMaxDenormModes() && 6266 DAG.isKnownNeverNaN(Op.getOperand(0)) && 6267 DAG.isKnownNeverNaN(Op.getOperand(1))) 6268 return true; 6269 6270 return (MaxDepth > 0) && 6271 isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) && 6272 isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1); 6273 6274 case ISD::ConstantFP: { 6275 auto F = cast<ConstantFPSDNode>(Op)->getValueAPF(); 6276 return !F.isDenormal() && !(F.isNaN() && F.isSignaling()); 6277 } 6278 } 6279 return false; 6280 } 6281 6282 // Constant fold canonicalize. 6283 SDValue SITargetLowering::performFCanonicalizeCombine( 6284 SDNode *N, 6285 DAGCombinerInfo &DCI) const { 6286 SelectionDAG &DAG = DCI.DAG; 6287 ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0)); 6288 6289 if (!CFP) { 6290 SDValue N0 = N->getOperand(0); 6291 EVT VT = N0.getValueType().getScalarType(); 6292 auto ST = getSubtarget(); 6293 6294 if (((VT == MVT::f32 && ST->hasFP32Denormals()) || 6295 (VT == MVT::f64 && ST->hasFP64Denormals()) || 6296 (VT == MVT::f16 && ST->hasFP16Denormals())) && 6297 DAG.isKnownNeverNaN(N0)) 6298 return N0; 6299 6300 bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction()); 6301 6302 if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) && 6303 isCanonicalized(DAG, N0, ST)) 6304 return N0; 6305 6306 return SDValue(); 6307 } 6308 6309 const APFloat &C = CFP->getValueAPF(); 6310 6311 // Flush denormals to 0 if not enabled. 6312 if (C.isDenormal()) { 6313 EVT VT = N->getValueType(0); 6314 EVT SVT = VT.getScalarType(); 6315 if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals()) 6316 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6317 6318 if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals()) 6319 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6320 6321 if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals()) 6322 return DAG.getConstantFP(0.0, SDLoc(N), VT); 6323 } 6324 6325 if (C.isNaN()) { 6326 EVT VT = N->getValueType(0); 6327 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 6328 if (C.isSignaling()) { 6329 // Quiet a signaling NaN. 6330 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 6331 } 6332 6333 // Make sure it is the canonical NaN bitpattern. 6334 // 6335 // TODO: Can we use -1 as the canonical NaN value since it's an inline 6336 // immediate? 6337 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 6338 return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT); 6339 } 6340 6341 return N->getOperand(0); 6342 } 6343 6344 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 6345 switch (Opc) { 6346 case ISD::FMAXNUM: 6347 return AMDGPUISD::FMAX3; 6348 case ISD::SMAX: 6349 return AMDGPUISD::SMAX3; 6350 case ISD::UMAX: 6351 return AMDGPUISD::UMAX3; 6352 case ISD::FMINNUM: 6353 return AMDGPUISD::FMIN3; 6354 case ISD::SMIN: 6355 return AMDGPUISD::SMIN3; 6356 case ISD::UMIN: 6357 return AMDGPUISD::UMIN3; 6358 default: 6359 llvm_unreachable("Not a min/max opcode"); 6360 } 6361 } 6362 6363 SDValue SITargetLowering::performIntMed3ImmCombine( 6364 SelectionDAG &DAG, const SDLoc &SL, 6365 SDValue Op0, SDValue Op1, bool Signed) const { 6366 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 6367 if (!K1) 6368 return SDValue(); 6369 6370 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 6371 if (!K0) 6372 return SDValue(); 6373 6374 if (Signed) { 6375 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 6376 return SDValue(); 6377 } else { 6378 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 6379 return SDValue(); 6380 } 6381 6382 EVT VT = K0->getValueType(0); 6383 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 6384 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 6385 return DAG.getNode(Med3Opc, SL, VT, 6386 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 6387 } 6388 6389 // If there isn't a 16-bit med3 operation, convert to 32-bit. 6390 MVT NVT = MVT::i32; 6391 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 6392 6393 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 6394 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 6395 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 6396 6397 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 6398 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 6399 } 6400 6401 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 6402 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 6403 return C; 6404 6405 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 6406 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 6407 return C; 6408 } 6409 6410 return nullptr; 6411 } 6412 6413 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 6414 const SDLoc &SL, 6415 SDValue Op0, 6416 SDValue Op1) const { 6417 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 6418 if (!K1) 6419 return SDValue(); 6420 6421 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 6422 if (!K0) 6423 return SDValue(); 6424 6425 // Ordered >= (although NaN inputs should have folded away by now). 6426 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 6427 if (Cmp == APFloat::cmpGreaterThan) 6428 return SDValue(); 6429 6430 // TODO: Check IEEE bit enabled? 6431 EVT VT = Op0.getValueType(); 6432 if (Subtarget->enableDX10Clamp()) { 6433 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 6434 // hardware fmed3 behavior converting to a min. 6435 // FIXME: Should this be allowing -0.0? 6436 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 6437 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 6438 } 6439 6440 // med3 for f16 is only available on gfx9+, and not available for v2f16. 6441 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 6442 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 6443 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 6444 // then give the other result, which is different from med3 with a NaN 6445 // input. 6446 SDValue Var = Op0.getOperand(0); 6447 if (!isKnownNeverSNan(DAG, Var)) 6448 return SDValue(); 6449 6450 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 6451 Var, SDValue(K0, 0), SDValue(K1, 0)); 6452 } 6453 6454 return SDValue(); 6455 } 6456 6457 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 6458 DAGCombinerInfo &DCI) const { 6459 SelectionDAG &DAG = DCI.DAG; 6460 6461 EVT VT = N->getValueType(0); 6462 unsigned Opc = N->getOpcode(); 6463 SDValue Op0 = N->getOperand(0); 6464 SDValue Op1 = N->getOperand(1); 6465 6466 // Only do this if the inner op has one use since this will just increases 6467 // register pressure for no benefit. 6468 6469 6470 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 6471 !VT.isVector() && VT != MVT::f64 && 6472 ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) { 6473 // max(max(a, b), c) -> max3(a, b, c) 6474 // min(min(a, b), c) -> min3(a, b, c) 6475 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 6476 SDLoc DL(N); 6477 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 6478 DL, 6479 N->getValueType(0), 6480 Op0.getOperand(0), 6481 Op0.getOperand(1), 6482 Op1); 6483 } 6484 6485 // Try commuted. 6486 // max(a, max(b, c)) -> max3(a, b, c) 6487 // min(a, min(b, c)) -> min3(a, b, c) 6488 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 6489 SDLoc DL(N); 6490 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 6491 DL, 6492 N->getValueType(0), 6493 Op0, 6494 Op1.getOperand(0), 6495 Op1.getOperand(1)); 6496 } 6497 } 6498 6499 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 6500 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 6501 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 6502 return Med3; 6503 } 6504 6505 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 6506 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 6507 return Med3; 6508 } 6509 6510 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 6511 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 6512 (Opc == AMDGPUISD::FMIN_LEGACY && 6513 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 6514 (VT == MVT::f32 || VT == MVT::f64 || 6515 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 6516 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 6517 Op0.hasOneUse()) { 6518 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 6519 return Res; 6520 } 6521 6522 return SDValue(); 6523 } 6524 6525 static bool isClampZeroToOne(SDValue A, SDValue B) { 6526 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 6527 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 6528 // FIXME: Should this be allowing -0.0? 6529 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 6530 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 6531 } 6532 } 6533 6534 return false; 6535 } 6536 6537 // FIXME: Should only worry about snans for version with chain. 6538 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 6539 DAGCombinerInfo &DCI) const { 6540 EVT VT = N->getValueType(0); 6541 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 6542 // NaNs. With a NaN input, the order of the operands may change the result. 6543 6544 SelectionDAG &DAG = DCI.DAG; 6545 SDLoc SL(N); 6546 6547 SDValue Src0 = N->getOperand(0); 6548 SDValue Src1 = N->getOperand(1); 6549 SDValue Src2 = N->getOperand(2); 6550 6551 if (isClampZeroToOne(Src0, Src1)) { 6552 // const_a, const_b, x -> clamp is safe in all cases including signaling 6553 // nans. 6554 // FIXME: Should this be allowing -0.0? 6555 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 6556 } 6557 6558 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 6559 // handling no dx10-clamp? 6560 if (Subtarget->enableDX10Clamp()) { 6561 // If NaNs is clamped to 0, we are free to reorder the inputs. 6562 6563 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 6564 std::swap(Src0, Src1); 6565 6566 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 6567 std::swap(Src1, Src2); 6568 6569 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 6570 std::swap(Src0, Src1); 6571 6572 if (isClampZeroToOne(Src1, Src2)) 6573 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 6574 } 6575 6576 return SDValue(); 6577 } 6578 6579 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 6580 DAGCombinerInfo &DCI) const { 6581 SDValue Src0 = N->getOperand(0); 6582 SDValue Src1 = N->getOperand(1); 6583 if (Src0.isUndef() && Src1.isUndef()) 6584 return DCI.DAG.getUNDEF(N->getValueType(0)); 6585 return SDValue(); 6586 } 6587 6588 SDValue SITargetLowering::performExtractVectorEltCombine( 6589 SDNode *N, DAGCombinerInfo &DCI) const { 6590 SDValue Vec = N->getOperand(0); 6591 6592 SelectionDAG &DAG = DCI.DAG; 6593 if ((Vec.getOpcode() == ISD::FNEG || 6594 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 6595 SDLoc SL(N); 6596 EVT EltVT = N->getValueType(0); 6597 SDValue Idx = N->getOperand(1); 6598 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6599 Vec.getOperand(0), Idx); 6600 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 6601 } 6602 6603 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 6604 // => 6605 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 6606 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 6607 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 6608 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 6609 SDLoc SL(N); 6610 EVT EltVT = N->getValueType(0); 6611 SDValue Idx = N->getOperand(1); 6612 unsigned Opc = Vec.getOpcode(); 6613 6614 switch(Opc) { 6615 default: 6616 return SDValue(); 6617 // TODO: Support other binary operations. 6618 case ISD::FADD: 6619 case ISD::ADD: 6620 case ISD::UMIN: 6621 case ISD::UMAX: 6622 case ISD::SMIN: 6623 case ISD::SMAX: 6624 case ISD::FMAXNUM: 6625 case ISD::FMINNUM: 6626 return DAG.getNode(Opc, SL, EltVT, 6627 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6628 Vec.getOperand(0), Idx), 6629 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 6630 Vec.getOperand(1), Idx)); 6631 } 6632 } 6633 return SDValue(); 6634 } 6635 6636 static bool convertBuildVectorCastElt(SelectionDAG &DAG, 6637 SDValue &Lo, SDValue &Hi) { 6638 if (Hi.getOpcode() == ISD::BITCAST && 6639 Hi.getOperand(0).getValueType() == MVT::f16 && 6640 (isa<ConstantSDNode>(Lo) || Lo.isUndef())) { 6641 Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo); 6642 Hi = Hi.getOperand(0); 6643 return true; 6644 } 6645 6646 return false; 6647 } 6648 6649 SDValue SITargetLowering::performBuildVectorCombine( 6650 SDNode *N, DAGCombinerInfo &DCI) const { 6651 SDLoc SL(N); 6652 6653 if (!isTypeLegal(MVT::v2i16)) 6654 return SDValue(); 6655 SelectionDAG &DAG = DCI.DAG; 6656 EVT VT = N->getValueType(0); 6657 6658 if (VT == MVT::v2i16) { 6659 SDValue Lo = N->getOperand(0); 6660 SDValue Hi = N->getOperand(1); 6661 6662 // v2i16 build_vector (const|undef), (bitcast f16:$x) 6663 // -> bitcast (v2f16 build_vector const|undef, $x 6664 if (convertBuildVectorCastElt(DAG, Lo, Hi)) { 6665 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi }); 6666 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 6667 } 6668 6669 if (convertBuildVectorCastElt(DAG, Hi, Lo)) { 6670 SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo }); 6671 return DAG.getNode(ISD::BITCAST, SL, VT, NewVec); 6672 } 6673 } 6674 6675 return SDValue(); 6676 } 6677 6678 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 6679 const SDNode *N0, 6680 const SDNode *N1) const { 6681 EVT VT = N0->getValueType(0); 6682 6683 // Only do this if we are not trying to support denormals. v_mad_f32 does not 6684 // support denormals ever. 6685 if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 6686 (VT == MVT::f16 && !Subtarget->hasFP16Denormals())) 6687 return ISD::FMAD; 6688 6689 const TargetOptions &Options = DAG.getTarget().Options; 6690 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 6691 (N0->getFlags().hasAllowContract() && 6692 N1->getFlags().hasAllowContract())) && 6693 isFMAFasterThanFMulAndFAdd(VT)) { 6694 return ISD::FMA; 6695 } 6696 6697 return 0; 6698 } 6699 6700 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 6701 EVT VT, 6702 SDValue N0, SDValue N1, SDValue N2, 6703 bool Signed) { 6704 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 6705 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 6706 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 6707 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 6708 } 6709 6710 SDValue SITargetLowering::performAddCombine(SDNode *N, 6711 DAGCombinerInfo &DCI) const { 6712 SelectionDAG &DAG = DCI.DAG; 6713 EVT VT = N->getValueType(0); 6714 SDLoc SL(N); 6715 SDValue LHS = N->getOperand(0); 6716 SDValue RHS = N->getOperand(1); 6717 6718 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 6719 && Subtarget->hasMad64_32() && 6720 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 6721 VT.getScalarSizeInBits() <= 64) { 6722 if (LHS.getOpcode() != ISD::MUL) 6723 std::swap(LHS, RHS); 6724 6725 SDValue MulLHS = LHS.getOperand(0); 6726 SDValue MulRHS = LHS.getOperand(1); 6727 SDValue AddRHS = RHS; 6728 6729 // TODO: Maybe restrict if SGPR inputs. 6730 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 6731 numBitsUnsigned(MulRHS, DAG) <= 32) { 6732 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 6733 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 6734 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 6735 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 6736 } 6737 6738 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 6739 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 6740 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 6741 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 6742 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 6743 } 6744 6745 return SDValue(); 6746 } 6747 6748 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 6749 return SDValue(); 6750 6751 // add x, zext (setcc) => addcarry x, 0, setcc 6752 // add x, sext (setcc) => subcarry x, 0, setcc 6753 unsigned Opc = LHS.getOpcode(); 6754 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 6755 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 6756 std::swap(RHS, LHS); 6757 6758 Opc = RHS.getOpcode(); 6759 switch (Opc) { 6760 default: break; 6761 case ISD::ZERO_EXTEND: 6762 case ISD::SIGN_EXTEND: 6763 case ISD::ANY_EXTEND: { 6764 auto Cond = RHS.getOperand(0); 6765 if (!isBoolSGPR(Cond)) 6766 break; 6767 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 6768 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 6769 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 6770 return DAG.getNode(Opc, SL, VTList, Args); 6771 } 6772 case ISD::ADDCARRY: { 6773 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 6774 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 6775 if (!C || C->getZExtValue() != 0) break; 6776 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 6777 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 6778 } 6779 } 6780 return SDValue(); 6781 } 6782 6783 SDValue SITargetLowering::performSubCombine(SDNode *N, 6784 DAGCombinerInfo &DCI) const { 6785 SelectionDAG &DAG = DCI.DAG; 6786 EVT VT = N->getValueType(0); 6787 6788 if (VT != MVT::i32) 6789 return SDValue(); 6790 6791 SDLoc SL(N); 6792 SDValue LHS = N->getOperand(0); 6793 SDValue RHS = N->getOperand(1); 6794 6795 unsigned Opc = LHS.getOpcode(); 6796 if (Opc != ISD::SUBCARRY) 6797 std::swap(RHS, LHS); 6798 6799 if (LHS.getOpcode() == ISD::SUBCARRY) { 6800 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 6801 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 6802 if (!C || C->getZExtValue() != 0) 6803 return SDValue(); 6804 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 6805 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 6806 } 6807 return SDValue(); 6808 } 6809 6810 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 6811 DAGCombinerInfo &DCI) const { 6812 6813 if (N->getValueType(0) != MVT::i32) 6814 return SDValue(); 6815 6816 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 6817 if (!C || C->getZExtValue() != 0) 6818 return SDValue(); 6819 6820 SelectionDAG &DAG = DCI.DAG; 6821 SDValue LHS = N->getOperand(0); 6822 6823 // addcarry (add x, y), 0, cc => addcarry x, y, cc 6824 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 6825 unsigned LHSOpc = LHS.getOpcode(); 6826 unsigned Opc = N->getOpcode(); 6827 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 6828 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 6829 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 6830 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 6831 } 6832 return SDValue(); 6833 } 6834 6835 SDValue SITargetLowering::performFAddCombine(SDNode *N, 6836 DAGCombinerInfo &DCI) const { 6837 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6838 return SDValue(); 6839 6840 SelectionDAG &DAG = DCI.DAG; 6841 EVT VT = N->getValueType(0); 6842 6843 SDLoc SL(N); 6844 SDValue LHS = N->getOperand(0); 6845 SDValue RHS = N->getOperand(1); 6846 6847 // These should really be instruction patterns, but writing patterns with 6848 // source modiifiers is a pain. 6849 6850 // fadd (fadd (a, a), b) -> mad 2.0, a, b 6851 if (LHS.getOpcode() == ISD::FADD) { 6852 SDValue A = LHS.getOperand(0); 6853 if (A == LHS.getOperand(1)) { 6854 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6855 if (FusedOp != 0) { 6856 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6857 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 6858 } 6859 } 6860 } 6861 6862 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 6863 if (RHS.getOpcode() == ISD::FADD) { 6864 SDValue A = RHS.getOperand(0); 6865 if (A == RHS.getOperand(1)) { 6866 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6867 if (FusedOp != 0) { 6868 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6869 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 6870 } 6871 } 6872 } 6873 6874 return SDValue(); 6875 } 6876 6877 SDValue SITargetLowering::performFSubCombine(SDNode *N, 6878 DAGCombinerInfo &DCI) const { 6879 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 6880 return SDValue(); 6881 6882 SelectionDAG &DAG = DCI.DAG; 6883 SDLoc SL(N); 6884 EVT VT = N->getValueType(0); 6885 assert(!VT.isVector()); 6886 6887 // Try to get the fneg to fold into the source modifier. This undoes generic 6888 // DAG combines and folds them into the mad. 6889 // 6890 // Only do this if we are not trying to support denormals. v_mad_f32 does 6891 // not support denormals ever. 6892 SDValue LHS = N->getOperand(0); 6893 SDValue RHS = N->getOperand(1); 6894 if (LHS.getOpcode() == ISD::FADD) { 6895 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 6896 SDValue A = LHS.getOperand(0); 6897 if (A == LHS.getOperand(1)) { 6898 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 6899 if (FusedOp != 0){ 6900 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 6901 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 6902 6903 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 6904 } 6905 } 6906 } 6907 6908 if (RHS.getOpcode() == ISD::FADD) { 6909 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 6910 6911 SDValue A = RHS.getOperand(0); 6912 if (A == RHS.getOperand(1)) { 6913 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 6914 if (FusedOp != 0){ 6915 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 6916 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 6917 } 6918 } 6919 } 6920 6921 return SDValue(); 6922 } 6923 6924 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 6925 DAGCombinerInfo &DCI) const { 6926 SelectionDAG &DAG = DCI.DAG; 6927 SDLoc SL(N); 6928 6929 SDValue LHS = N->getOperand(0); 6930 SDValue RHS = N->getOperand(1); 6931 EVT VT = LHS.getValueType(); 6932 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 6933 6934 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 6935 if (!CRHS) { 6936 CRHS = dyn_cast<ConstantSDNode>(LHS); 6937 if (CRHS) { 6938 std::swap(LHS, RHS); 6939 CC = getSetCCSwappedOperands(CC); 6940 } 6941 } 6942 6943 if (CRHS && VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 6944 isBoolSGPR(LHS.getOperand(0))) { 6945 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 6946 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 6947 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 6948 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 6949 if ((CRHS->isAllOnesValue() && 6950 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 6951 (CRHS->isNullValue() && 6952 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 6953 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 6954 DAG.getConstant(-1, SL, MVT::i1)); 6955 if ((CRHS->isAllOnesValue() && 6956 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 6957 (CRHS->isNullValue() && 6958 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 6959 return LHS.getOperand(0); 6960 } 6961 6962 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 6963 VT != MVT::f16)) 6964 return SDValue(); 6965 6966 // Match isinf pattern 6967 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 6968 if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) { 6969 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 6970 if (!CRHS) 6971 return SDValue(); 6972 6973 const APFloat &APF = CRHS->getValueAPF(); 6974 if (APF.isInfinity() && !APF.isNegative()) { 6975 unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY; 6976 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 6977 DAG.getConstant(Mask, SL, MVT::i32)); 6978 } 6979 } 6980 6981 return SDValue(); 6982 } 6983 6984 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 6985 DAGCombinerInfo &DCI) const { 6986 SelectionDAG &DAG = DCI.DAG; 6987 SDLoc SL(N); 6988 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 6989 6990 SDValue Src = N->getOperand(0); 6991 SDValue Srl = N->getOperand(0); 6992 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 6993 Srl = Srl.getOperand(0); 6994 6995 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 6996 if (Srl.getOpcode() == ISD::SRL) { 6997 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 6998 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 6999 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 7000 7001 if (const ConstantSDNode *C = 7002 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 7003 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 7004 EVT(MVT::i32)); 7005 7006 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 7007 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 7008 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 7009 MVT::f32, Srl); 7010 } 7011 } 7012 } 7013 7014 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 7015 7016 KnownBits Known; 7017 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 7018 !DCI.isBeforeLegalizeOps()); 7019 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7020 if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) || 7021 TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 7022 DCI.CommitTargetLoweringOpt(TLO); 7023 } 7024 7025 return SDValue(); 7026 } 7027 7028 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 7029 DAGCombinerInfo &DCI) const { 7030 switch (N->getOpcode()) { 7031 default: 7032 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 7033 case ISD::ADD: 7034 return performAddCombine(N, DCI); 7035 case ISD::SUB: 7036 return performSubCombine(N, DCI); 7037 case ISD::ADDCARRY: 7038 case ISD::SUBCARRY: 7039 return performAddCarrySubCarryCombine(N, DCI); 7040 case ISD::FADD: 7041 return performFAddCombine(N, DCI); 7042 case ISD::FSUB: 7043 return performFSubCombine(N, DCI); 7044 case ISD::SETCC: 7045 return performSetCCCombine(N, DCI); 7046 case ISD::FMAXNUM: 7047 case ISD::FMINNUM: 7048 case ISD::SMAX: 7049 case ISD::SMIN: 7050 case ISD::UMAX: 7051 case ISD::UMIN: 7052 case AMDGPUISD::FMIN_LEGACY: 7053 case AMDGPUISD::FMAX_LEGACY: { 7054 if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG && 7055 getTargetMachine().getOptLevel() > CodeGenOpt::None) 7056 return performMinMaxCombine(N, DCI); 7057 break; 7058 } 7059 case ISD::LOAD: 7060 case ISD::STORE: 7061 case ISD::ATOMIC_LOAD: 7062 case ISD::ATOMIC_STORE: 7063 case ISD::ATOMIC_CMP_SWAP: 7064 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 7065 case ISD::ATOMIC_SWAP: 7066 case ISD::ATOMIC_LOAD_ADD: 7067 case ISD::ATOMIC_LOAD_SUB: 7068 case ISD::ATOMIC_LOAD_AND: 7069 case ISD::ATOMIC_LOAD_OR: 7070 case ISD::ATOMIC_LOAD_XOR: 7071 case ISD::ATOMIC_LOAD_NAND: 7072 case ISD::ATOMIC_LOAD_MIN: 7073 case ISD::ATOMIC_LOAD_MAX: 7074 case ISD::ATOMIC_LOAD_UMIN: 7075 case ISD::ATOMIC_LOAD_UMAX: 7076 case AMDGPUISD::ATOMIC_INC: 7077 case AMDGPUISD::ATOMIC_DEC: 7078 case AMDGPUISD::ATOMIC_LOAD_FADD: 7079 case AMDGPUISD::ATOMIC_LOAD_FMIN: 7080 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 7081 if (DCI.isBeforeLegalize()) 7082 break; 7083 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 7084 case ISD::AND: 7085 return performAndCombine(N, DCI); 7086 case ISD::OR: 7087 return performOrCombine(N, DCI); 7088 case ISD::XOR: 7089 return performXorCombine(N, DCI); 7090 case ISD::ZERO_EXTEND: 7091 return performZeroExtendCombine(N, DCI); 7092 case AMDGPUISD::FP_CLASS: 7093 return performClassCombine(N, DCI); 7094 case ISD::FCANONICALIZE: 7095 return performFCanonicalizeCombine(N, DCI); 7096 case AMDGPUISD::FRACT: 7097 case AMDGPUISD::RCP: 7098 case AMDGPUISD::RSQ: 7099 case AMDGPUISD::RCP_LEGACY: 7100 case AMDGPUISD::RSQ_LEGACY: 7101 case AMDGPUISD::RSQ_CLAMP: 7102 case AMDGPUISD::LDEXP: { 7103 SDValue Src = N->getOperand(0); 7104 if (Src.isUndef()) 7105 return Src; 7106 break; 7107 } 7108 case ISD::SINT_TO_FP: 7109 case ISD::UINT_TO_FP: 7110 return performUCharToFloatCombine(N, DCI); 7111 case AMDGPUISD::CVT_F32_UBYTE0: 7112 case AMDGPUISD::CVT_F32_UBYTE1: 7113 case AMDGPUISD::CVT_F32_UBYTE2: 7114 case AMDGPUISD::CVT_F32_UBYTE3: 7115 return performCvtF32UByteNCombine(N, DCI); 7116 case AMDGPUISD::FMED3: 7117 return performFMed3Combine(N, DCI); 7118 case AMDGPUISD::CVT_PKRTZ_F16_F32: 7119 return performCvtPkRTZCombine(N, DCI); 7120 case ISD::SCALAR_TO_VECTOR: { 7121 SelectionDAG &DAG = DCI.DAG; 7122 EVT VT = N->getValueType(0); 7123 7124 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 7125 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 7126 SDLoc SL(N); 7127 SDValue Src = N->getOperand(0); 7128 EVT EltVT = Src.getValueType(); 7129 if (EltVT == MVT::f16) 7130 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 7131 7132 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 7133 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 7134 } 7135 7136 break; 7137 } 7138 case ISD::EXTRACT_VECTOR_ELT: 7139 return performExtractVectorEltCombine(N, DCI); 7140 case ISD::BUILD_VECTOR: 7141 return performBuildVectorCombine(N, DCI); 7142 } 7143 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 7144 } 7145 7146 /// Helper function for adjustWritemask 7147 static unsigned SubIdx2Lane(unsigned Idx) { 7148 switch (Idx) { 7149 default: return 0; 7150 case AMDGPU::sub0: return 0; 7151 case AMDGPU::sub1: return 1; 7152 case AMDGPU::sub2: return 2; 7153 case AMDGPU::sub3: return 3; 7154 } 7155 } 7156 7157 /// Adjust the writemask of MIMG instructions 7158 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 7159 SelectionDAG &DAG) const { 7160 SDNode *Users[4] = { nullptr }; 7161 unsigned Lane = 0; 7162 unsigned DmaskIdx = (Node->getNumOperands() - Node->getNumValues() == 9) ? 2 : 3; 7163 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 7164 unsigned NewDmask = 0; 7165 bool HasChain = Node->getNumValues() > 1; 7166 7167 if (OldDmask == 0) { 7168 // These are folded out, but on the chance it happens don't assert. 7169 return Node; 7170 } 7171 7172 // Try to figure out the used register components 7173 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 7174 I != E; ++I) { 7175 7176 // Don't look at users of the chain. 7177 if (I.getUse().getResNo() != 0) 7178 continue; 7179 7180 // Abort if we can't understand the usage 7181 if (!I->isMachineOpcode() || 7182 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 7183 return Node; 7184 7185 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 7186 // Note that subregs are packed, i.e. Lane==0 is the first bit set 7187 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 7188 // set, etc. 7189 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 7190 7191 // Set which texture component corresponds to the lane. 7192 unsigned Comp; 7193 for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) { 7194 Comp = countTrailingZeros(Dmask); 7195 Dmask &= ~(1 << Comp); 7196 } 7197 7198 // Abort if we have more than one user per component 7199 if (Users[Lane]) 7200 return Node; 7201 7202 Users[Lane] = *I; 7203 NewDmask |= 1 << Comp; 7204 } 7205 7206 // Abort if there's no change 7207 if (NewDmask == OldDmask) 7208 return Node; 7209 7210 unsigned BitsSet = countPopulation(NewDmask); 7211 7212 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7213 int NewOpcode = AMDGPU::getMaskedMIMGOp(*TII, 7214 Node->getMachineOpcode(), BitsSet); 7215 assert(NewOpcode != -1 && 7216 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 7217 "failed to find equivalent MIMG op"); 7218 7219 // Adjust the writemask in the node 7220 SmallVector<SDValue, 12> Ops; 7221 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 7222 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 7223 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 7224 7225 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 7226 7227 MVT ResultVT = BitsSet == 1 ? 7228 SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet); 7229 SDVTList NewVTList = HasChain ? 7230 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 7231 7232 7233 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 7234 NewVTList, Ops); 7235 7236 if (HasChain) { 7237 // Update chain. 7238 NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end()); 7239 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 7240 } 7241 7242 if (BitsSet == 1) { 7243 assert(Node->hasNUsesOfValue(1, 0)); 7244 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 7245 SDLoc(Node), Users[Lane]->getValueType(0), 7246 SDValue(NewNode, 0)); 7247 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 7248 return nullptr; 7249 } 7250 7251 // Update the users of the node with the new indices 7252 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) { 7253 SDNode *User = Users[i]; 7254 if (!User) 7255 continue; 7256 7257 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 7258 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 7259 7260 switch (Idx) { 7261 default: break; 7262 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 7263 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 7264 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 7265 } 7266 } 7267 7268 DAG.RemoveDeadNode(Node); 7269 return nullptr; 7270 } 7271 7272 static bool isFrameIndexOp(SDValue Op) { 7273 if (Op.getOpcode() == ISD::AssertZext) 7274 Op = Op.getOperand(0); 7275 7276 return isa<FrameIndexSDNode>(Op); 7277 } 7278 7279 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 7280 /// with frame index operands. 7281 /// LLVM assumes that inputs are to these instructions are registers. 7282 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 7283 SelectionDAG &DAG) const { 7284 if (Node->getOpcode() == ISD::CopyToReg) { 7285 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 7286 SDValue SrcVal = Node->getOperand(2); 7287 7288 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 7289 // to try understanding copies to physical registers. 7290 if (SrcVal.getValueType() == MVT::i1 && 7291 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 7292 SDLoc SL(Node); 7293 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 7294 SDValue VReg = DAG.getRegister( 7295 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 7296 7297 SDNode *Glued = Node->getGluedNode(); 7298 SDValue ToVReg 7299 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 7300 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 7301 SDValue ToResultReg 7302 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 7303 VReg, ToVReg.getValue(1)); 7304 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 7305 DAG.RemoveDeadNode(Node); 7306 return ToResultReg.getNode(); 7307 } 7308 } 7309 7310 SmallVector<SDValue, 8> Ops; 7311 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 7312 if (!isFrameIndexOp(Node->getOperand(i))) { 7313 Ops.push_back(Node->getOperand(i)); 7314 continue; 7315 } 7316 7317 SDLoc DL(Node); 7318 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 7319 Node->getOperand(i).getValueType(), 7320 Node->getOperand(i)), 0)); 7321 } 7322 7323 return DAG.UpdateNodeOperands(Node, Ops); 7324 } 7325 7326 /// Fold the instructions after selecting them. 7327 /// Returns null if users were already updated. 7328 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 7329 SelectionDAG &DAG) const { 7330 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7331 unsigned Opcode = Node->getMachineOpcode(); 7332 7333 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 7334 !TII->isGather4(Opcode) && !TII->isD16(Opcode)) { 7335 return adjustWritemask(Node, DAG); 7336 } 7337 7338 if (Opcode == AMDGPU::INSERT_SUBREG || 7339 Opcode == AMDGPU::REG_SEQUENCE) { 7340 legalizeTargetIndependentNode(Node, DAG); 7341 return Node; 7342 } 7343 7344 switch (Opcode) { 7345 case AMDGPU::V_DIV_SCALE_F32: 7346 case AMDGPU::V_DIV_SCALE_F64: { 7347 // Satisfy the operand register constraint when one of the inputs is 7348 // undefined. Ordinarily each undef value will have its own implicit_def of 7349 // a vreg, so force these to use a single register. 7350 SDValue Src0 = Node->getOperand(0); 7351 SDValue Src1 = Node->getOperand(1); 7352 SDValue Src2 = Node->getOperand(2); 7353 7354 if ((Src0.isMachineOpcode() && 7355 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 7356 (Src0 == Src1 || Src0 == Src2)) 7357 break; 7358 7359 MVT VT = Src0.getValueType().getSimpleVT(); 7360 const TargetRegisterClass *RC = getRegClassFor(VT); 7361 7362 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 7363 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 7364 7365 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 7366 UndefReg, Src0, SDValue()); 7367 7368 // src0 must be the same register as src1 or src2, even if the value is 7369 // undefined, so make sure we don't violate this constraint. 7370 if (Src0.isMachineOpcode() && 7371 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 7372 if (Src1.isMachineOpcode() && 7373 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 7374 Src0 = Src1; 7375 else if (Src2.isMachineOpcode() && 7376 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 7377 Src0 = Src2; 7378 else { 7379 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 7380 Src0 = UndefReg; 7381 Src1 = UndefReg; 7382 } 7383 } else 7384 break; 7385 7386 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 7387 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 7388 Ops.push_back(Node->getOperand(I)); 7389 7390 Ops.push_back(ImpDef.getValue(1)); 7391 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 7392 } 7393 default: 7394 break; 7395 } 7396 7397 return Node; 7398 } 7399 7400 /// Assign the register class depending on the number of 7401 /// bits set in the writemask 7402 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 7403 SDNode *Node) const { 7404 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7405 7406 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 7407 7408 if (TII->isVOP3(MI.getOpcode())) { 7409 // Make sure constant bus requirements are respected. 7410 TII->legalizeOperandsVOP3(MRI, MI); 7411 return; 7412 } 7413 7414 // Replace unused atomics with the no return version. 7415 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 7416 if (NoRetAtomicOp != -1) { 7417 if (!Node->hasAnyUseOfValue(0)) { 7418 MI.setDesc(TII->get(NoRetAtomicOp)); 7419 MI.RemoveOperand(0); 7420 return; 7421 } 7422 7423 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 7424 // instruction, because the return type of these instructions is a vec2 of 7425 // the memory type, so it can be tied to the input operand. 7426 // This means these instructions always have a use, so we need to add a 7427 // special case to check if the atomic has only one extract_subreg use, 7428 // which itself has no uses. 7429 if ((Node->hasNUsesOfValue(1, 0) && 7430 Node->use_begin()->isMachineOpcode() && 7431 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 7432 !Node->use_begin()->hasAnyUseOfValue(0))) { 7433 unsigned Def = MI.getOperand(0).getReg(); 7434 7435 // Change this into a noret atomic. 7436 MI.setDesc(TII->get(NoRetAtomicOp)); 7437 MI.RemoveOperand(0); 7438 7439 // If we only remove the def operand from the atomic instruction, the 7440 // extract_subreg will be left with a use of a vreg without a def. 7441 // So we need to insert an implicit_def to avoid machine verifier 7442 // errors. 7443 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 7444 TII->get(AMDGPU::IMPLICIT_DEF), Def); 7445 } 7446 return; 7447 } 7448 } 7449 7450 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 7451 uint64_t Val) { 7452 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 7453 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 7454 } 7455 7456 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 7457 const SDLoc &DL, 7458 SDValue Ptr) const { 7459 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7460 7461 // Build the half of the subregister with the constants before building the 7462 // full 128-bit register. If we are building multiple resource descriptors, 7463 // this will allow CSEing of the 2-component register. 7464 const SDValue Ops0[] = { 7465 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 7466 buildSMovImm32(DAG, DL, 0), 7467 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 7468 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 7469 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 7470 }; 7471 7472 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 7473 MVT::v2i32, Ops0), 0); 7474 7475 // Combine the constants and the pointer. 7476 const SDValue Ops1[] = { 7477 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 7478 Ptr, 7479 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 7480 SubRegHi, 7481 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 7482 }; 7483 7484 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 7485 } 7486 7487 /// Return a resource descriptor with the 'Add TID' bit enabled 7488 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 7489 /// of the resource descriptor) to create an offset, which is added to 7490 /// the resource pointer. 7491 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 7492 SDValue Ptr, uint32_t RsrcDword1, 7493 uint64_t RsrcDword2And3) const { 7494 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 7495 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 7496 if (RsrcDword1) { 7497 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 7498 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 7499 0); 7500 } 7501 7502 SDValue DataLo = buildSMovImm32(DAG, DL, 7503 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 7504 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 7505 7506 const SDValue Ops[] = { 7507 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 7508 PtrLo, 7509 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 7510 PtrHi, 7511 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 7512 DataLo, 7513 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 7514 DataHi, 7515 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 7516 }; 7517 7518 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 7519 } 7520 7521 //===----------------------------------------------------------------------===// 7522 // SI Inline Assembly Support 7523 //===----------------------------------------------------------------------===// 7524 7525 std::pair<unsigned, const TargetRegisterClass *> 7526 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 7527 StringRef Constraint, 7528 MVT VT) const { 7529 if (!isTypeLegal(VT)) 7530 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7531 7532 if (Constraint.size() == 1) { 7533 switch (Constraint[0]) { 7534 case 's': 7535 case 'r': 7536 switch (VT.getSizeInBits()) { 7537 default: 7538 return std::make_pair(0U, nullptr); 7539 case 32: 7540 case 16: 7541 return std::make_pair(0U, &AMDGPU::SReg_32_XM0RegClass); 7542 case 64: 7543 return std::make_pair(0U, &AMDGPU::SGPR_64RegClass); 7544 case 128: 7545 return std::make_pair(0U, &AMDGPU::SReg_128RegClass); 7546 case 256: 7547 return std::make_pair(0U, &AMDGPU::SReg_256RegClass); 7548 case 512: 7549 return std::make_pair(0U, &AMDGPU::SReg_512RegClass); 7550 } 7551 7552 case 'v': 7553 switch (VT.getSizeInBits()) { 7554 default: 7555 return std::make_pair(0U, nullptr); 7556 case 32: 7557 case 16: 7558 return std::make_pair(0U, &AMDGPU::VGPR_32RegClass); 7559 case 64: 7560 return std::make_pair(0U, &AMDGPU::VReg_64RegClass); 7561 case 96: 7562 return std::make_pair(0U, &AMDGPU::VReg_96RegClass); 7563 case 128: 7564 return std::make_pair(0U, &AMDGPU::VReg_128RegClass); 7565 case 256: 7566 return std::make_pair(0U, &AMDGPU::VReg_256RegClass); 7567 case 512: 7568 return std::make_pair(0U, &AMDGPU::VReg_512RegClass); 7569 } 7570 } 7571 } 7572 7573 if (Constraint.size() > 1) { 7574 const TargetRegisterClass *RC = nullptr; 7575 if (Constraint[1] == 'v') { 7576 RC = &AMDGPU::VGPR_32RegClass; 7577 } else if (Constraint[1] == 's') { 7578 RC = &AMDGPU::SGPR_32RegClass; 7579 } 7580 7581 if (RC) { 7582 uint32_t Idx; 7583 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 7584 if (!Failed && Idx < RC->getNumRegs()) 7585 return std::make_pair(RC->getRegister(Idx), RC); 7586 } 7587 } 7588 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 7589 } 7590 7591 SITargetLowering::ConstraintType 7592 SITargetLowering::getConstraintType(StringRef Constraint) const { 7593 if (Constraint.size() == 1) { 7594 switch (Constraint[0]) { 7595 default: break; 7596 case 's': 7597 case 'v': 7598 return C_RegisterClass; 7599 } 7600 } 7601 return TargetLowering::getConstraintType(Constraint); 7602 } 7603 7604 // Figure out which registers should be reserved for stack access. Only after 7605 // the function is legalized do we know all of the non-spill stack objects or if 7606 // calls are present. 7607 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 7608 MachineRegisterInfo &MRI = MF.getRegInfo(); 7609 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 7610 const MachineFrameInfo &MFI = MF.getFrameInfo(); 7611 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 7612 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 7613 7614 if (Info->isEntryFunction()) { 7615 // Callable functions have fixed registers used for stack access. 7616 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 7617 } 7618 7619 // We have to assume the SP is needed in case there are calls in the function 7620 // during lowering. Calls are only detected after the function is 7621 // lowered. We're about to reserve registers, so don't bother using it if we 7622 // aren't really going to use it. 7623 bool NeedSP = !Info->isEntryFunction() || 7624 MFI.hasVarSizedObjects() || 7625 MFI.hasCalls(); 7626 7627 if (NeedSP) { 7628 unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF); 7629 Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg); 7630 7631 assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg()); 7632 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 7633 Info->getStackPtrOffsetReg())); 7634 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 7635 } 7636 7637 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 7638 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 7639 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 7640 Info->getScratchWaveOffsetReg()); 7641 7642 TargetLoweringBase::finalizeLowering(MF); 7643 } 7644 7645 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 7646 KnownBits &Known, 7647 const APInt &DemandedElts, 7648 const SelectionDAG &DAG, 7649 unsigned Depth) const { 7650 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 7651 DAG, Depth); 7652 7653 if (getSubtarget()->enableHugePrivateBuffer()) 7654 return; 7655 7656 // Technically it may be possible to have a dispatch with a single workitem 7657 // that uses the full private memory size, but that's not really useful. We 7658 // can't use vaddr in MUBUF instructions if we don't know the address 7659 // calculation won't overflow, so assume the sign bit is never set. 7660 Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits); 7661 } 7662