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