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