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