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<bool> DisableLoopAlignment( 97 "amdgpu-disable-loop-alignment", 98 cl::desc("Do not align and prefetch loops"), 99 cl::init(false)); 100 101 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 102 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 103 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 104 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 105 return AMDGPU::SGPR0 + Reg; 106 } 107 } 108 llvm_unreachable("Cannot allocate sgpr"); 109 } 110 111 SITargetLowering::SITargetLowering(const TargetMachine &TM, 112 const GCNSubtarget &STI) 113 : AMDGPUTargetLowering(TM, STI), 114 Subtarget(&STI) { 115 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 116 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 117 118 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 119 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 120 121 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 122 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 123 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 124 125 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 126 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 127 128 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 129 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 130 131 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 132 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 133 134 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 135 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 136 137 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 138 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 139 140 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 141 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 142 143 if (Subtarget->has16BitInsts()) { 144 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 145 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 146 147 // Unless there are also VOP3P operations, not operations are really legal. 148 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 149 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 150 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 151 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 152 } 153 154 computeRegisterProperties(Subtarget->getRegisterInfo()); 155 156 // We need to custom lower vector stores from local memory 157 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 158 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 159 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 160 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 161 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::i1, Custom); 164 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 165 166 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 167 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 168 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 169 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 170 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 172 setOperationAction(ISD::STORE, MVT::i1, Custom); 173 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 174 175 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 176 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 177 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 178 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 179 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 180 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 181 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 182 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 183 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 184 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 185 186 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 187 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 188 189 setOperationAction(ISD::SELECT, MVT::i1, Promote); 190 setOperationAction(ISD::SELECT, MVT::i64, Custom); 191 setOperationAction(ISD::SELECT, MVT::f64, Promote); 192 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 193 194 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 195 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 196 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 197 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 198 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 199 200 setOperationAction(ISD::SETCC, MVT::i1, Promote); 201 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 202 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 203 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 204 205 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 206 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 207 208 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 209 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 215 216 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 217 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 218 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 219 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 220 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 221 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 222 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 223 224 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 225 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 226 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 227 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 228 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 229 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 230 231 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 232 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 233 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 234 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 235 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 236 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 237 238 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 239 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 240 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 241 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 242 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 243 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 244 245 setOperationAction(ISD::UADDO, MVT::i32, Legal); 246 setOperationAction(ISD::USUBO, MVT::i32, Legal); 247 248 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 249 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 250 251 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 252 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 253 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 254 255 #if 0 256 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 257 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 258 #endif 259 260 // We only support LOAD/STORE and vector manipulation ops for vectors 261 // with > 4 elements. 262 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 263 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) { 264 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 265 switch (Op) { 266 case ISD::LOAD: 267 case ISD::STORE: 268 case ISD::BUILD_VECTOR: 269 case ISD::BITCAST: 270 case ISD::EXTRACT_VECTOR_ELT: 271 case ISD::INSERT_VECTOR_ELT: 272 case ISD::INSERT_SUBVECTOR: 273 case ISD::EXTRACT_SUBVECTOR: 274 case ISD::SCALAR_TO_VECTOR: 275 break; 276 case ISD::CONCAT_VECTORS: 277 setOperationAction(Op, VT, Custom); 278 break; 279 default: 280 setOperationAction(Op, VT, Expand); 281 break; 282 } 283 } 284 } 285 286 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 287 288 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 289 // is expanded to avoid having two separate loops in case the index is a VGPR. 290 291 // Most operations are naturally 32-bit vector operations. We only support 292 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 293 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 294 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 295 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 296 297 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 298 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 299 300 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 301 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 302 303 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 305 } 306 307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 311 312 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 314 315 // Avoid stack access for these. 316 // TODO: Generalize to more vector types. 317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 321 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 331 332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 336 337 // Deal with vec3 vector operations when widened to vec4. 338 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Expand); 339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Expand); 340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Expand); 341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Expand); 342 343 // Deal with vec5 vector operations when widened to vec8. 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Expand); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Expand); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Expand); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Expand); 348 349 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 350 // and output demarshalling 351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 353 354 // We can't return success/failure, only the old value, 355 // let LLVM add the comparison 356 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 358 359 if (Subtarget->hasFlatAddressSpace()) { 360 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 361 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 362 } 363 364 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 365 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 366 367 // On SI this is s_memtime and s_memrealtime on VI. 368 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 369 setOperationAction(ISD::TRAP, MVT::Other, Custom); 370 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 371 372 if (Subtarget->has16BitInsts()) { 373 setOperationAction(ISD::FLOG, MVT::f16, Custom); 374 setOperationAction(ISD::FEXP, MVT::f16, Custom); 375 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 376 } 377 378 // v_mad_f32 does not support denormals according to some sources. 379 if (!Subtarget->hasFP32Denormals()) 380 setOperationAction(ISD::FMAD, MVT::f32, Legal); 381 382 if (!Subtarget->hasBFI()) { 383 // fcopysign can be done in a single instruction with BFI. 384 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 385 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 386 } 387 388 if (!Subtarget->hasBCNT(32)) 389 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 390 391 if (!Subtarget->hasBCNT(64)) 392 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 393 394 if (Subtarget->hasFFBH()) 395 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 396 397 if (Subtarget->hasFFBL()) 398 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 399 400 // We only really have 32-bit BFE instructions (and 16-bit on VI). 401 // 402 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 403 // effort to match them now. We want this to be false for i64 cases when the 404 // extraction isn't restricted to the upper or lower half. Ideally we would 405 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 406 // span the midpoint are probably relatively rare, so don't worry about them 407 // for now. 408 if (Subtarget->hasBFE()) 409 setHasExtractBitsInsn(true); 410 411 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 412 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 413 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 414 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 415 416 417 // These are really only legal for ieee_mode functions. We should be avoiding 418 // them for functions that don't have ieee_mode enabled, so just say they are 419 // legal. 420 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 421 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 422 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 423 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 424 425 426 if (Subtarget->haveRoundOpsF64()) { 427 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 428 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 429 setOperationAction(ISD::FRINT, MVT::f64, Legal); 430 } else { 431 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 432 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 433 setOperationAction(ISD::FRINT, MVT::f64, Custom); 434 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 435 } 436 437 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 438 439 setOperationAction(ISD::FSIN, MVT::f32, Custom); 440 setOperationAction(ISD::FCOS, MVT::f32, Custom); 441 setOperationAction(ISD::FDIV, MVT::f32, Custom); 442 setOperationAction(ISD::FDIV, MVT::f64, Custom); 443 444 if (Subtarget->has16BitInsts()) { 445 setOperationAction(ISD::Constant, MVT::i16, Legal); 446 447 setOperationAction(ISD::SMIN, MVT::i16, Legal); 448 setOperationAction(ISD::SMAX, MVT::i16, Legal); 449 450 setOperationAction(ISD::UMIN, MVT::i16, Legal); 451 setOperationAction(ISD::UMAX, MVT::i16, Legal); 452 453 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 454 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 455 456 setOperationAction(ISD::ROTR, MVT::i16, Promote); 457 setOperationAction(ISD::ROTL, MVT::i16, Promote); 458 459 setOperationAction(ISD::SDIV, MVT::i16, Promote); 460 setOperationAction(ISD::UDIV, MVT::i16, Promote); 461 setOperationAction(ISD::SREM, MVT::i16, Promote); 462 setOperationAction(ISD::UREM, MVT::i16, Promote); 463 464 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 465 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 466 467 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 468 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 469 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 470 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 471 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 472 473 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 474 475 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 476 477 setOperationAction(ISD::LOAD, MVT::i16, Custom); 478 479 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 480 481 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 482 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 483 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 484 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 485 486 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 487 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 488 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 489 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 490 491 // F16 - Constant Actions. 492 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 493 494 // F16 - Load/Store Actions. 495 setOperationAction(ISD::LOAD, MVT::f16, Promote); 496 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 497 setOperationAction(ISD::STORE, MVT::f16, Promote); 498 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 499 500 // F16 - VOP1 Actions. 501 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 502 setOperationAction(ISD::FCOS, MVT::f16, Promote); 503 setOperationAction(ISD::FSIN, MVT::f16, Promote); 504 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 505 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 506 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 507 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 508 setOperationAction(ISD::FROUND, MVT::f16, Custom); 509 510 // F16 - VOP2 Actions. 511 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 512 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 513 514 setOperationAction(ISD::FDIV, MVT::f16, Custom); 515 516 // F16 - VOP3 Actions. 517 setOperationAction(ISD::FMA, MVT::f16, Legal); 518 if (!Subtarget->hasFP16Denormals() && STI.hasMadF16()) 519 setOperationAction(ISD::FMAD, MVT::f16, Legal); 520 521 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 522 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 523 switch (Op) { 524 case ISD::LOAD: 525 case ISD::STORE: 526 case ISD::BUILD_VECTOR: 527 case ISD::BITCAST: 528 case ISD::EXTRACT_VECTOR_ELT: 529 case ISD::INSERT_VECTOR_ELT: 530 case ISD::INSERT_SUBVECTOR: 531 case ISD::EXTRACT_SUBVECTOR: 532 case ISD::SCALAR_TO_VECTOR: 533 break; 534 case ISD::CONCAT_VECTORS: 535 setOperationAction(Op, VT, Custom); 536 break; 537 default: 538 setOperationAction(Op, VT, Expand); 539 break; 540 } 541 } 542 } 543 544 // XXX - Do these do anything? Vector constants turn into build_vector. 545 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 546 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 547 548 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 549 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 550 551 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 552 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 553 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 554 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 555 556 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 557 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 558 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 559 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 560 561 setOperationAction(ISD::AND, MVT::v2i16, Promote); 562 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 563 setOperationAction(ISD::OR, MVT::v2i16, Promote); 564 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 565 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 566 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 567 568 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 569 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 570 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 571 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 572 573 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 574 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 575 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 576 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 577 578 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 579 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 580 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 581 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 582 583 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 584 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 585 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 586 587 if (!Subtarget->hasVOP3PInsts()) { 588 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 589 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 590 } 591 592 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 593 // This isn't really legal, but this avoids the legalizer unrolling it (and 594 // allows matching fneg (fabs x) patterns) 595 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 596 597 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 598 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 599 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 600 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 601 602 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 603 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 604 605 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 606 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 607 } 608 609 if (Subtarget->hasVOP3PInsts()) { 610 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 611 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 612 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 613 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 614 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 615 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 616 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 617 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 618 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 619 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 620 621 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 622 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 623 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 624 625 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 626 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 627 628 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 629 630 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 631 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 632 633 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 634 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 635 636 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 637 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 638 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 639 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 640 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 641 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 642 643 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 644 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 645 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 646 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 647 648 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 649 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 650 651 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 652 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 653 654 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 655 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 656 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 657 658 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 659 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 660 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 661 } 662 663 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 664 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 665 666 if (Subtarget->has16BitInsts()) { 667 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 668 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 669 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 670 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 671 } else { 672 // Legalization hack. 673 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 674 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 675 676 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 677 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 678 } 679 680 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 681 setOperationAction(ISD::SELECT, VT, Custom); 682 } 683 684 setTargetDAGCombine(ISD::ADD); 685 setTargetDAGCombine(ISD::ADDCARRY); 686 setTargetDAGCombine(ISD::SUB); 687 setTargetDAGCombine(ISD::SUBCARRY); 688 setTargetDAGCombine(ISD::FADD); 689 setTargetDAGCombine(ISD::FSUB); 690 setTargetDAGCombine(ISD::FMINNUM); 691 setTargetDAGCombine(ISD::FMAXNUM); 692 setTargetDAGCombine(ISD::FMINNUM_IEEE); 693 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 694 setTargetDAGCombine(ISD::FMA); 695 setTargetDAGCombine(ISD::SMIN); 696 setTargetDAGCombine(ISD::SMAX); 697 setTargetDAGCombine(ISD::UMIN); 698 setTargetDAGCombine(ISD::UMAX); 699 setTargetDAGCombine(ISD::SETCC); 700 setTargetDAGCombine(ISD::AND); 701 setTargetDAGCombine(ISD::OR); 702 setTargetDAGCombine(ISD::XOR); 703 setTargetDAGCombine(ISD::SINT_TO_FP); 704 setTargetDAGCombine(ISD::UINT_TO_FP); 705 setTargetDAGCombine(ISD::FCANONICALIZE); 706 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 707 setTargetDAGCombine(ISD::ZERO_EXTEND); 708 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 709 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 710 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 711 712 // All memory operations. Some folding on the pointer operand is done to help 713 // matching the constant offsets in the addressing modes. 714 setTargetDAGCombine(ISD::LOAD); 715 setTargetDAGCombine(ISD::STORE); 716 setTargetDAGCombine(ISD::ATOMIC_LOAD); 717 setTargetDAGCombine(ISD::ATOMIC_STORE); 718 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 719 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 720 setTargetDAGCombine(ISD::ATOMIC_SWAP); 721 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 722 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 723 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 724 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 725 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 726 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 727 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 728 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 729 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 730 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 731 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 732 733 setSchedulingPreference(Sched::RegPressure); 734 } 735 736 const GCNSubtarget *SITargetLowering::getSubtarget() const { 737 return Subtarget; 738 } 739 740 //===----------------------------------------------------------------------===// 741 // TargetLowering queries 742 //===----------------------------------------------------------------------===// 743 744 // v_mad_mix* support a conversion from f16 to f32. 745 // 746 // There is only one special case when denormals are enabled we don't currently, 747 // where this is OK to use. 748 bool SITargetLowering::isFPExtFoldable(unsigned Opcode, 749 EVT DestVT, EVT SrcVT) const { 750 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 751 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 752 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() && 753 SrcVT.getScalarType() == MVT::f16; 754 } 755 756 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 757 // SI has some legal vector types, but no legal vector operations. Say no 758 // shuffles are legal in order to prefer scalarizing some vector operations. 759 return false; 760 } 761 762 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 763 CallingConv::ID CC, 764 EVT VT) const { 765 // TODO: Consider splitting all arguments into 32-bit pieces. 766 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 767 EVT ScalarVT = VT.getScalarType(); 768 unsigned Size = ScalarVT.getSizeInBits(); 769 if (Size == 32) 770 return ScalarVT.getSimpleVT(); 771 772 if (Size == 64) 773 return MVT::i32; 774 775 if (Size == 16 && Subtarget->has16BitInsts()) 776 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 777 } 778 779 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 780 } 781 782 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 783 CallingConv::ID CC, 784 EVT VT) const { 785 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 786 unsigned NumElts = VT.getVectorNumElements(); 787 EVT ScalarVT = VT.getScalarType(); 788 unsigned Size = ScalarVT.getSizeInBits(); 789 790 if (Size == 32) 791 return NumElts; 792 793 if (Size == 64) 794 return 2 * NumElts; 795 796 if (Size == 16 && Subtarget->has16BitInsts()) 797 return (VT.getVectorNumElements() + 1) / 2; 798 } 799 800 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 801 } 802 803 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 804 LLVMContext &Context, CallingConv::ID CC, 805 EVT VT, EVT &IntermediateVT, 806 unsigned &NumIntermediates, MVT &RegisterVT) const { 807 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 808 unsigned NumElts = VT.getVectorNumElements(); 809 EVT ScalarVT = VT.getScalarType(); 810 unsigned Size = ScalarVT.getSizeInBits(); 811 if (Size == 32) { 812 RegisterVT = ScalarVT.getSimpleVT(); 813 IntermediateVT = RegisterVT; 814 NumIntermediates = NumElts; 815 return NumIntermediates; 816 } 817 818 if (Size == 64) { 819 RegisterVT = MVT::i32; 820 IntermediateVT = RegisterVT; 821 NumIntermediates = 2 * NumElts; 822 return NumIntermediates; 823 } 824 825 // FIXME: We should fix the ABI to be the same on targets without 16-bit 826 // support, but unless we can properly handle 3-vectors, it will be still be 827 // inconsistent. 828 if (Size == 16 && Subtarget->has16BitInsts()) { 829 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 830 IntermediateVT = RegisterVT; 831 NumIntermediates = (NumElts + 1) / 2; 832 return NumIntermediates; 833 } 834 } 835 836 return TargetLowering::getVectorTypeBreakdownForCallingConv( 837 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 838 } 839 840 static MVT memVTFromAggregate(Type *Ty) { 841 // Only limited forms of aggregate type currently expected. 842 assert(Ty->isStructTy() && "Expected struct type"); 843 844 845 Type *ElementType = nullptr; 846 unsigned NumElts; 847 if (Ty->getContainedType(0)->isVectorTy()) { 848 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 849 ElementType = VecComponent->getElementType(); 850 NumElts = VecComponent->getNumElements(); 851 } else { 852 ElementType = Ty->getContainedType(0); 853 NumElts = 1; 854 } 855 856 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 857 858 // Calculate the size of the memVT type from the aggregate 859 unsigned Pow2Elts = 0; 860 unsigned ElementSize; 861 switch (ElementType->getTypeID()) { 862 default: 863 llvm_unreachable("Unknown type!"); 864 case Type::IntegerTyID: 865 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 866 break; 867 case Type::HalfTyID: 868 ElementSize = 16; 869 break; 870 case Type::FloatTyID: 871 ElementSize = 32; 872 break; 873 } 874 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 875 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 876 877 return MVT::getVectorVT(MVT::getVT(ElementType, false), 878 Pow2Elts); 879 } 880 881 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 882 const CallInst &CI, 883 MachineFunction &MF, 884 unsigned IntrID) const { 885 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 886 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 887 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 888 (Intrinsic::ID)IntrID); 889 if (Attr.hasFnAttribute(Attribute::ReadNone)) 890 return false; 891 892 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 893 894 if (RsrcIntr->IsImage) { 895 Info.ptrVal = MFI->getImagePSV( 896 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 897 CI.getArgOperand(RsrcIntr->RsrcArg)); 898 Info.align = 0; 899 } else { 900 Info.ptrVal = MFI->getBufferPSV( 901 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 902 CI.getArgOperand(RsrcIntr->RsrcArg)); 903 } 904 905 Info.flags = MachineMemOperand::MODereferenceable; 906 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 907 Info.opc = ISD::INTRINSIC_W_CHAIN; 908 Info.memVT = MVT::getVT(CI.getType(), true); 909 if (Info.memVT == MVT::Other) { 910 // Some intrinsics return an aggregate type - special case to work out 911 // the correct memVT 912 Info.memVT = memVTFromAggregate(CI.getType()); 913 } 914 Info.flags |= MachineMemOperand::MOLoad; 915 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 916 Info.opc = ISD::INTRINSIC_VOID; 917 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 918 Info.flags |= MachineMemOperand::MOStore; 919 } else { 920 // Atomic 921 Info.opc = ISD::INTRINSIC_W_CHAIN; 922 Info.memVT = MVT::getVT(CI.getType()); 923 Info.flags = MachineMemOperand::MOLoad | 924 MachineMemOperand::MOStore | 925 MachineMemOperand::MODereferenceable; 926 927 // XXX - Should this be volatile without known ordering? 928 Info.flags |= MachineMemOperand::MOVolatile; 929 } 930 return true; 931 } 932 933 switch (IntrID) { 934 case Intrinsic::amdgcn_atomic_inc: 935 case Intrinsic::amdgcn_atomic_dec: 936 case Intrinsic::amdgcn_ds_ordered_add: 937 case Intrinsic::amdgcn_ds_ordered_swap: 938 case Intrinsic::amdgcn_ds_fadd: 939 case Intrinsic::amdgcn_ds_fmin: 940 case Intrinsic::amdgcn_ds_fmax: { 941 Info.opc = ISD::INTRINSIC_W_CHAIN; 942 Info.memVT = MVT::getVT(CI.getType()); 943 Info.ptrVal = CI.getOperand(0); 944 Info.align = 0; 945 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 946 947 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 948 if (!Vol->isZero()) 949 Info.flags |= MachineMemOperand::MOVolatile; 950 951 return true; 952 } 953 case Intrinsic::amdgcn_ds_append: 954 case Intrinsic::amdgcn_ds_consume: { 955 Info.opc = ISD::INTRINSIC_W_CHAIN; 956 Info.memVT = MVT::getVT(CI.getType()); 957 Info.ptrVal = CI.getOperand(0); 958 Info.align = 0; 959 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 960 961 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 962 if (!Vol->isZero()) 963 Info.flags |= MachineMemOperand::MOVolatile; 964 965 return true; 966 } 967 case Intrinsic::amdgcn_ds_gws_init: 968 case Intrinsic::amdgcn_ds_gws_barrier: 969 case Intrinsic::amdgcn_ds_gws_sema_v: 970 case Intrinsic::amdgcn_ds_gws_sema_br: 971 case Intrinsic::amdgcn_ds_gws_sema_p: 972 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 973 Info.opc = ISD::INTRINSIC_VOID; 974 975 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 976 Info.ptrVal = 977 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 978 979 // This is an abstract access, but we need to specify a type and size. 980 Info.memVT = MVT::i32; 981 Info.size = 4; 982 Info.align = 4; 983 984 Info.flags = MachineMemOperand::MOStore; 985 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 986 Info.flags = MachineMemOperand::MOLoad; 987 return true; 988 } 989 default: 990 return false; 991 } 992 } 993 994 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 995 SmallVectorImpl<Value*> &Ops, 996 Type *&AccessTy) const { 997 switch (II->getIntrinsicID()) { 998 case Intrinsic::amdgcn_atomic_inc: 999 case Intrinsic::amdgcn_atomic_dec: 1000 case Intrinsic::amdgcn_ds_ordered_add: 1001 case Intrinsic::amdgcn_ds_ordered_swap: 1002 case Intrinsic::amdgcn_ds_fadd: 1003 case Intrinsic::amdgcn_ds_fmin: 1004 case Intrinsic::amdgcn_ds_fmax: { 1005 Value *Ptr = II->getArgOperand(0); 1006 AccessTy = II->getType(); 1007 Ops.push_back(Ptr); 1008 return true; 1009 } 1010 default: 1011 return false; 1012 } 1013 } 1014 1015 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1016 if (!Subtarget->hasFlatInstOffsets()) { 1017 // Flat instructions do not have offsets, and only have the register 1018 // address. 1019 return AM.BaseOffs == 0 && AM.Scale == 0; 1020 } 1021 1022 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 1023 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 1024 1025 // GFX10 shrinked signed offset to 12 bits. When using regular flat 1026 // instructions, the sign bit is also ignored and is treated as 11-bit 1027 // unsigned offset. 1028 1029 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 1030 return isUInt<11>(AM.BaseOffs) && AM.Scale == 0; 1031 1032 // Just r + i 1033 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 1034 } 1035 1036 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1037 if (Subtarget->hasFlatGlobalInsts()) 1038 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 1039 1040 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1041 // Assume the we will use FLAT for all global memory accesses 1042 // on VI. 1043 // FIXME: This assumption is currently wrong. On VI we still use 1044 // MUBUF instructions for the r + i addressing mode. As currently 1045 // implemented, the MUBUF instructions only work on buffer < 4GB. 1046 // It may be possible to support > 4GB buffers with MUBUF instructions, 1047 // by setting the stride value in the resource descriptor which would 1048 // increase the size limit to (stride * 4GB). However, this is risky, 1049 // because it has never been validated. 1050 return isLegalFlatAddressingMode(AM); 1051 } 1052 1053 return isLegalMUBUFAddressingMode(AM); 1054 } 1055 1056 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1057 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1058 // additionally can do r + r + i with addr64. 32-bit has more addressing 1059 // mode options. Depending on the resource constant, it can also do 1060 // (i64 r0) + (i32 r1) * (i14 i). 1061 // 1062 // Private arrays end up using a scratch buffer most of the time, so also 1063 // assume those use MUBUF instructions. Scratch loads / stores are currently 1064 // implemented as mubuf instructions with offen bit set, so slightly 1065 // different than the normal addr64. 1066 if (!isUInt<12>(AM.BaseOffs)) 1067 return false; 1068 1069 // FIXME: Since we can split immediate into soffset and immediate offset, 1070 // would it make sense to allow any immediate? 1071 1072 switch (AM.Scale) { 1073 case 0: // r + i or just i, depending on HasBaseReg. 1074 return true; 1075 case 1: 1076 return true; // We have r + r or r + i. 1077 case 2: 1078 if (AM.HasBaseReg) { 1079 // Reject 2 * r + r. 1080 return false; 1081 } 1082 1083 // Allow 2 * r as r + r 1084 // Or 2 * r + i is allowed as r + r + i. 1085 return true; 1086 default: // Don't allow n * r 1087 return false; 1088 } 1089 } 1090 1091 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1092 const AddrMode &AM, Type *Ty, 1093 unsigned AS, Instruction *I) const { 1094 // No global is ever allowed as a base. 1095 if (AM.BaseGV) 1096 return false; 1097 1098 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1099 return isLegalGlobalAddressingMode(AM); 1100 1101 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1102 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1103 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1104 // If the offset isn't a multiple of 4, it probably isn't going to be 1105 // correctly aligned. 1106 // FIXME: Can we get the real alignment here? 1107 if (AM.BaseOffs % 4 != 0) 1108 return isLegalMUBUFAddressingMode(AM); 1109 1110 // There are no SMRD extloads, so if we have to do a small type access we 1111 // will use a MUBUF load. 1112 // FIXME?: We also need to do this if unaligned, but we don't know the 1113 // alignment here. 1114 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1115 return isLegalGlobalAddressingMode(AM); 1116 1117 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1118 // SMRD instructions have an 8-bit, dword offset on SI. 1119 if (!isUInt<8>(AM.BaseOffs / 4)) 1120 return false; 1121 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1122 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1123 // in 8-bits, it can use a smaller encoding. 1124 if (!isUInt<32>(AM.BaseOffs / 4)) 1125 return false; 1126 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1127 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1128 if (!isUInt<20>(AM.BaseOffs)) 1129 return false; 1130 } else 1131 llvm_unreachable("unhandled generation"); 1132 1133 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1134 return true; 1135 1136 if (AM.Scale == 1 && AM.HasBaseReg) 1137 return true; 1138 1139 return false; 1140 1141 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1142 return isLegalMUBUFAddressingMode(AM); 1143 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1144 AS == AMDGPUAS::REGION_ADDRESS) { 1145 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1146 // field. 1147 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1148 // an 8-bit dword offset but we don't know the alignment here. 1149 if (!isUInt<16>(AM.BaseOffs)) 1150 return false; 1151 1152 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1153 return true; 1154 1155 if (AM.Scale == 1 && AM.HasBaseReg) 1156 return true; 1157 1158 return false; 1159 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1160 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1161 // For an unknown address space, this usually means that this is for some 1162 // reason being used for pure arithmetic, and not based on some addressing 1163 // computation. We don't have instructions that compute pointers with any 1164 // addressing modes, so treat them as having no offset like flat 1165 // instructions. 1166 return isLegalFlatAddressingMode(AM); 1167 } else { 1168 llvm_unreachable("unhandled address space"); 1169 } 1170 } 1171 1172 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1173 const SelectionDAG &DAG) const { 1174 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1175 return (MemVT.getSizeInBits() <= 4 * 32); 1176 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1177 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1178 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1179 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1180 return (MemVT.getSizeInBits() <= 2 * 32); 1181 } 1182 return true; 1183 } 1184 1185 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1186 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1187 bool *IsFast) const { 1188 if (IsFast) 1189 *IsFast = false; 1190 1191 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1192 // which isn't a simple VT. 1193 // Until MVT is extended to handle this, simply check for the size and 1194 // rely on the condition below: allow accesses if the size is a multiple of 4. 1195 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1196 VT.getStoreSize() > 16)) { 1197 return false; 1198 } 1199 1200 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1201 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1202 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1203 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1204 // with adjacent offsets. 1205 bool AlignedBy4 = (Align % 4 == 0); 1206 if (IsFast) 1207 *IsFast = AlignedBy4; 1208 1209 return AlignedBy4; 1210 } 1211 1212 // FIXME: We have to be conservative here and assume that flat operations 1213 // will access scratch. If we had access to the IR function, then we 1214 // could determine if any private memory was used in the function. 1215 if (!Subtarget->hasUnalignedScratchAccess() && 1216 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1217 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1218 bool AlignedBy4 = Align >= 4; 1219 if (IsFast) 1220 *IsFast = AlignedBy4; 1221 1222 return AlignedBy4; 1223 } 1224 1225 if (Subtarget->hasUnalignedBufferAccess()) { 1226 // If we have an uniform constant load, it still requires using a slow 1227 // buffer instruction if unaligned. 1228 if (IsFast) { 1229 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1230 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1231 (Align % 4 == 0) : true; 1232 } 1233 1234 return true; 1235 } 1236 1237 // Smaller than dword value must be aligned. 1238 if (VT.bitsLT(MVT::i32)) 1239 return false; 1240 1241 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1242 // byte-address are ignored, thus forcing Dword alignment. 1243 // This applies to private, global, and constant memory. 1244 if (IsFast) 1245 *IsFast = true; 1246 1247 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 1248 } 1249 1250 EVT SITargetLowering::getOptimalMemOpType( 1251 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1252 bool ZeroMemset, bool MemcpyStrSrc, 1253 const AttributeList &FuncAttributes) const { 1254 // FIXME: Should account for address space here. 1255 1256 // The default fallback uses the private pointer size as a guess for a type to 1257 // use. Make sure we switch these to 64-bit accesses. 1258 1259 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1260 return MVT::v4i32; 1261 1262 if (Size >= 8 && DstAlign >= 4) 1263 return MVT::v2i32; 1264 1265 // Use the default. 1266 return MVT::Other; 1267 } 1268 1269 static bool isFlatGlobalAddrSpace(unsigned AS) { 1270 return AS == AMDGPUAS::GLOBAL_ADDRESS || 1271 AS == AMDGPUAS::FLAT_ADDRESS || 1272 AS == AMDGPUAS::CONSTANT_ADDRESS || 1273 AS > AMDGPUAS::MAX_AMDGPU_ADDRESS; 1274 } 1275 1276 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1277 unsigned DestAS) const { 1278 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1279 } 1280 1281 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1282 const MemSDNode *MemNode = cast<MemSDNode>(N); 1283 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1284 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1285 return I && I->getMetadata("amdgpu.noclobber"); 1286 } 1287 1288 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1289 unsigned DestAS) const { 1290 // Flat -> private/local is a simple truncate. 1291 // Flat -> global is no-op 1292 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1293 return true; 1294 1295 return isNoopAddrSpaceCast(SrcAS, DestAS); 1296 } 1297 1298 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1299 const MemSDNode *MemNode = cast<MemSDNode>(N); 1300 1301 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1302 } 1303 1304 TargetLoweringBase::LegalizeTypeAction 1305 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1306 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1307 return TypeSplitVector; 1308 1309 return TargetLoweringBase::getPreferredVectorAction(VT); 1310 } 1311 1312 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1313 Type *Ty) const { 1314 // FIXME: Could be smarter if called for vector constants. 1315 return true; 1316 } 1317 1318 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1319 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1320 switch (Op) { 1321 case ISD::LOAD: 1322 case ISD::STORE: 1323 1324 // These operations are done with 32-bit instructions anyway. 1325 case ISD::AND: 1326 case ISD::OR: 1327 case ISD::XOR: 1328 case ISD::SELECT: 1329 // TODO: Extensions? 1330 return true; 1331 default: 1332 return false; 1333 } 1334 } 1335 1336 // SimplifySetCC uses this function to determine whether or not it should 1337 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1338 if (VT == MVT::i1 && Op == ISD::SETCC) 1339 return false; 1340 1341 return TargetLowering::isTypeDesirableForOp(Op, VT); 1342 } 1343 1344 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1345 const SDLoc &SL, 1346 SDValue Chain, 1347 uint64_t Offset) const { 1348 const DataLayout &DL = DAG.getDataLayout(); 1349 MachineFunction &MF = DAG.getMachineFunction(); 1350 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1351 1352 const ArgDescriptor *InputPtrReg; 1353 const TargetRegisterClass *RC; 1354 1355 std::tie(InputPtrReg, RC) 1356 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1357 1358 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1359 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1360 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1361 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1362 1363 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1364 } 1365 1366 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1367 const SDLoc &SL) const { 1368 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1369 FIRST_IMPLICIT); 1370 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1371 } 1372 1373 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1374 const SDLoc &SL, SDValue Val, 1375 bool Signed, 1376 const ISD::InputArg *Arg) const { 1377 // First, if it is a widened vector, narrow it. 1378 if (VT.isVector() && 1379 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1380 EVT NarrowedVT = 1381 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1382 VT.getVectorNumElements()); 1383 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1384 DAG.getConstant(0, SL, MVT::i32)); 1385 } 1386 1387 // Then convert the vector elements or scalar value. 1388 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1389 VT.bitsLT(MemVT)) { 1390 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1391 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1392 } 1393 1394 if (MemVT.isFloatingPoint()) 1395 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1396 else if (Signed) 1397 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1398 else 1399 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1400 1401 return Val; 1402 } 1403 1404 SDValue SITargetLowering::lowerKernargMemParameter( 1405 SelectionDAG &DAG, EVT VT, EVT MemVT, 1406 const SDLoc &SL, SDValue Chain, 1407 uint64_t Offset, unsigned Align, bool Signed, 1408 const ISD::InputArg *Arg) const { 1409 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1410 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1411 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1412 1413 // Try to avoid using an extload by loading earlier than the argument address, 1414 // and extracting the relevant bits. The load should hopefully be merged with 1415 // the previous argument. 1416 if (MemVT.getStoreSize() < 4 && Align < 4) { 1417 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1418 int64_t AlignDownOffset = alignDown(Offset, 4); 1419 int64_t OffsetDiff = Offset - AlignDownOffset; 1420 1421 EVT IntVT = MemVT.changeTypeToInteger(); 1422 1423 // TODO: If we passed in the base kernel offset we could have a better 1424 // alignment than 4, but we don't really need it. 1425 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1426 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1427 MachineMemOperand::MODereferenceable | 1428 MachineMemOperand::MOInvariant); 1429 1430 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1431 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1432 1433 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1434 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1435 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1436 1437 1438 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1439 } 1440 1441 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1442 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1443 MachineMemOperand::MODereferenceable | 1444 MachineMemOperand::MOInvariant); 1445 1446 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1447 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1448 } 1449 1450 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1451 const SDLoc &SL, SDValue Chain, 1452 const ISD::InputArg &Arg) const { 1453 MachineFunction &MF = DAG.getMachineFunction(); 1454 MachineFrameInfo &MFI = MF.getFrameInfo(); 1455 1456 if (Arg.Flags.isByVal()) { 1457 unsigned Size = Arg.Flags.getByValSize(); 1458 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1459 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1460 } 1461 1462 unsigned ArgOffset = VA.getLocMemOffset(); 1463 unsigned ArgSize = VA.getValVT().getStoreSize(); 1464 1465 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1466 1467 // Create load nodes to retrieve arguments from the stack. 1468 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1469 SDValue ArgValue; 1470 1471 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1472 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1473 MVT MemVT = VA.getValVT(); 1474 1475 switch (VA.getLocInfo()) { 1476 default: 1477 break; 1478 case CCValAssign::BCvt: 1479 MemVT = VA.getLocVT(); 1480 break; 1481 case CCValAssign::SExt: 1482 ExtType = ISD::SEXTLOAD; 1483 break; 1484 case CCValAssign::ZExt: 1485 ExtType = ISD::ZEXTLOAD; 1486 break; 1487 case CCValAssign::AExt: 1488 ExtType = ISD::EXTLOAD; 1489 break; 1490 } 1491 1492 ArgValue = DAG.getExtLoad( 1493 ExtType, SL, VA.getLocVT(), Chain, FIN, 1494 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1495 MemVT); 1496 return ArgValue; 1497 } 1498 1499 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1500 const SIMachineFunctionInfo &MFI, 1501 EVT VT, 1502 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1503 const ArgDescriptor *Reg; 1504 const TargetRegisterClass *RC; 1505 1506 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1507 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1508 } 1509 1510 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1511 CallingConv::ID CallConv, 1512 ArrayRef<ISD::InputArg> Ins, 1513 BitVector &Skipped, 1514 FunctionType *FType, 1515 SIMachineFunctionInfo *Info) { 1516 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1517 const ISD::InputArg *Arg = &Ins[I]; 1518 1519 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1520 "vector type argument should have been split"); 1521 1522 // First check if it's a PS input addr. 1523 if (CallConv == CallingConv::AMDGPU_PS && 1524 !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) { 1525 1526 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1527 1528 // Inconveniently only the first part of the split is marked as isSplit, 1529 // so skip to the end. We only want to increment PSInputNum once for the 1530 // entire split argument. 1531 if (Arg->Flags.isSplit()) { 1532 while (!Arg->Flags.isSplitEnd()) { 1533 assert(!Arg->VT.isVector() && 1534 "unexpected vector split in ps argument type"); 1535 if (!SkipArg) 1536 Splits.push_back(*Arg); 1537 Arg = &Ins[++I]; 1538 } 1539 } 1540 1541 if (SkipArg) { 1542 // We can safely skip PS inputs. 1543 Skipped.set(Arg->getOrigArgIndex()); 1544 ++PSInputNum; 1545 continue; 1546 } 1547 1548 Info->markPSInputAllocated(PSInputNum); 1549 if (Arg->Used) 1550 Info->markPSInputEnabled(PSInputNum); 1551 1552 ++PSInputNum; 1553 } 1554 1555 Splits.push_back(*Arg); 1556 } 1557 } 1558 1559 // Allocate special inputs passed in VGPRs. 1560 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1561 MachineFunction &MF, 1562 const SIRegisterInfo &TRI, 1563 SIMachineFunctionInfo &Info) { 1564 if (Info.hasWorkItemIDX()) { 1565 unsigned Reg = AMDGPU::VGPR0; 1566 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1567 1568 CCInfo.AllocateReg(Reg); 1569 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1570 } 1571 1572 if (Info.hasWorkItemIDY()) { 1573 unsigned Reg = AMDGPU::VGPR1; 1574 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1575 1576 CCInfo.AllocateReg(Reg); 1577 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1578 } 1579 1580 if (Info.hasWorkItemIDZ()) { 1581 unsigned Reg = AMDGPU::VGPR2; 1582 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1583 1584 CCInfo.AllocateReg(Reg); 1585 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1586 } 1587 } 1588 1589 // Try to allocate a VGPR at the end of the argument list, or if no argument 1590 // VGPRs are left allocating a stack slot. 1591 // If \p Mask is is given it indicates bitfield position in the register. 1592 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1593 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1594 ArgDescriptor Arg = ArgDescriptor()) { 1595 if (Arg.isSet()) 1596 return ArgDescriptor::createArg(Arg, Mask); 1597 1598 ArrayRef<MCPhysReg> ArgVGPRs 1599 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1600 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1601 if (RegIdx == ArgVGPRs.size()) { 1602 // Spill to stack required. 1603 int64_t Offset = CCInfo.AllocateStack(4, 4); 1604 1605 return ArgDescriptor::createStack(Offset, Mask); 1606 } 1607 1608 unsigned Reg = ArgVGPRs[RegIdx]; 1609 Reg = CCInfo.AllocateReg(Reg); 1610 assert(Reg != AMDGPU::NoRegister); 1611 1612 MachineFunction &MF = CCInfo.getMachineFunction(); 1613 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1614 return ArgDescriptor::createRegister(Reg, Mask); 1615 } 1616 1617 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1618 const TargetRegisterClass *RC, 1619 unsigned NumArgRegs) { 1620 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1621 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1622 if (RegIdx == ArgSGPRs.size()) 1623 report_fatal_error("ran out of SGPRs for arguments"); 1624 1625 unsigned Reg = ArgSGPRs[RegIdx]; 1626 Reg = CCInfo.AllocateReg(Reg); 1627 assert(Reg != AMDGPU::NoRegister); 1628 1629 MachineFunction &MF = CCInfo.getMachineFunction(); 1630 MF.addLiveIn(Reg, RC); 1631 return ArgDescriptor::createRegister(Reg); 1632 } 1633 1634 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1635 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1636 } 1637 1638 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1639 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1640 } 1641 1642 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1643 MachineFunction &MF, 1644 const SIRegisterInfo &TRI, 1645 SIMachineFunctionInfo &Info) { 1646 const unsigned Mask = 0x3ff; 1647 ArgDescriptor Arg; 1648 1649 if (Info.hasWorkItemIDX()) { 1650 Arg = allocateVGPR32Input(CCInfo, Mask); 1651 Info.setWorkItemIDX(Arg); 1652 } 1653 1654 if (Info.hasWorkItemIDY()) { 1655 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1656 Info.setWorkItemIDY(Arg); 1657 } 1658 1659 if (Info.hasWorkItemIDZ()) 1660 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1661 } 1662 1663 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1664 MachineFunction &MF, 1665 const SIRegisterInfo &TRI, 1666 SIMachineFunctionInfo &Info) { 1667 auto &ArgInfo = Info.getArgInfo(); 1668 1669 // TODO: Unify handling with private memory pointers. 1670 1671 if (Info.hasDispatchPtr()) 1672 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1673 1674 if (Info.hasQueuePtr()) 1675 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1676 1677 if (Info.hasKernargSegmentPtr()) 1678 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1679 1680 if (Info.hasDispatchID()) 1681 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1682 1683 // flat_scratch_init is not applicable for non-kernel functions. 1684 1685 if (Info.hasWorkGroupIDX()) 1686 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1687 1688 if (Info.hasWorkGroupIDY()) 1689 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1690 1691 if (Info.hasWorkGroupIDZ()) 1692 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1693 1694 if (Info.hasImplicitArgPtr()) 1695 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1696 } 1697 1698 // Allocate special inputs passed in user SGPRs. 1699 static void allocateHSAUserSGPRs(CCState &CCInfo, 1700 MachineFunction &MF, 1701 const SIRegisterInfo &TRI, 1702 SIMachineFunctionInfo &Info) { 1703 if (Info.hasImplicitBufferPtr()) { 1704 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1705 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1706 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1707 } 1708 1709 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1710 if (Info.hasPrivateSegmentBuffer()) { 1711 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1712 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1713 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1714 } 1715 1716 if (Info.hasDispatchPtr()) { 1717 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1718 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1719 CCInfo.AllocateReg(DispatchPtrReg); 1720 } 1721 1722 if (Info.hasQueuePtr()) { 1723 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1724 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1725 CCInfo.AllocateReg(QueuePtrReg); 1726 } 1727 1728 if (Info.hasKernargSegmentPtr()) { 1729 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1730 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1731 CCInfo.AllocateReg(InputPtrReg); 1732 } 1733 1734 if (Info.hasDispatchID()) { 1735 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1736 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1737 CCInfo.AllocateReg(DispatchIDReg); 1738 } 1739 1740 if (Info.hasFlatScratchInit()) { 1741 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1742 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1743 CCInfo.AllocateReg(FlatScratchInitReg); 1744 } 1745 1746 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1747 // these from the dispatch pointer. 1748 } 1749 1750 // Allocate special input registers that are initialized per-wave. 1751 static void allocateSystemSGPRs(CCState &CCInfo, 1752 MachineFunction &MF, 1753 SIMachineFunctionInfo &Info, 1754 CallingConv::ID CallConv, 1755 bool IsShader) { 1756 if (Info.hasWorkGroupIDX()) { 1757 unsigned Reg = Info.addWorkGroupIDX(); 1758 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1759 CCInfo.AllocateReg(Reg); 1760 } 1761 1762 if (Info.hasWorkGroupIDY()) { 1763 unsigned Reg = Info.addWorkGroupIDY(); 1764 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1765 CCInfo.AllocateReg(Reg); 1766 } 1767 1768 if (Info.hasWorkGroupIDZ()) { 1769 unsigned Reg = Info.addWorkGroupIDZ(); 1770 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1771 CCInfo.AllocateReg(Reg); 1772 } 1773 1774 if (Info.hasWorkGroupInfo()) { 1775 unsigned Reg = Info.addWorkGroupInfo(); 1776 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1777 CCInfo.AllocateReg(Reg); 1778 } 1779 1780 if (Info.hasPrivateSegmentWaveByteOffset()) { 1781 // Scratch wave offset passed in system SGPR. 1782 unsigned PrivateSegmentWaveByteOffsetReg; 1783 1784 if (IsShader) { 1785 PrivateSegmentWaveByteOffsetReg = 1786 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1787 1788 // This is true if the scratch wave byte offset doesn't have a fixed 1789 // location. 1790 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1791 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1792 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1793 } 1794 } else 1795 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1796 1797 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1798 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1799 } 1800 } 1801 1802 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1803 MachineFunction &MF, 1804 const SIRegisterInfo &TRI, 1805 SIMachineFunctionInfo &Info) { 1806 // Now that we've figured out where the scratch register inputs are, see if 1807 // should reserve the arguments and use them directly. 1808 MachineFrameInfo &MFI = MF.getFrameInfo(); 1809 bool HasStackObjects = MFI.hasStackObjects(); 1810 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1811 1812 // Record that we know we have non-spill stack objects so we don't need to 1813 // check all stack objects later. 1814 if (HasStackObjects) 1815 Info.setHasNonSpillStackObjects(true); 1816 1817 // Everything live out of a block is spilled with fast regalloc, so it's 1818 // almost certain that spilling will be required. 1819 if (TM.getOptLevel() == CodeGenOpt::None) 1820 HasStackObjects = true; 1821 1822 // For now assume stack access is needed in any callee functions, so we need 1823 // the scratch registers to pass in. 1824 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1825 1826 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1827 // If we have stack objects, we unquestionably need the private buffer 1828 // resource. For the Code Object V2 ABI, this will be the first 4 user 1829 // SGPR inputs. We can reserve those and use them directly. 1830 1831 unsigned PrivateSegmentBufferReg = 1832 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1833 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1834 } else { 1835 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1836 // We tentatively reserve the last registers (skipping the last registers 1837 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1838 // we'll replace these with the ones immediately after those which were 1839 // really allocated. In the prologue copies will be inserted from the 1840 // argument to these reserved registers. 1841 1842 // Without HSA, relocations are used for the scratch pointer and the 1843 // buffer resource setup is always inserted in the prologue. Scratch wave 1844 // offset is still in an input SGPR. 1845 Info.setScratchRSrcReg(ReservedBufferReg); 1846 } 1847 1848 // hasFP should be accurate for kernels even before the frame is finalized. 1849 if (ST.getFrameLowering()->hasFP(MF)) { 1850 MachineRegisterInfo &MRI = MF.getRegInfo(); 1851 1852 // Try to use s32 as the SP, but move it if it would interfere with input 1853 // arguments. This won't work with calls though. 1854 // 1855 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1856 // registers. 1857 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1858 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1859 } else { 1860 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1861 1862 if (MFI.hasCalls()) 1863 report_fatal_error("call in graphics shader with too many input SGPRs"); 1864 1865 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1866 if (!MRI.isLiveIn(Reg)) { 1867 Info.setStackPtrOffsetReg(Reg); 1868 break; 1869 } 1870 } 1871 1872 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1873 report_fatal_error("failed to find register for SP"); 1874 } 1875 1876 if (MFI.hasCalls()) { 1877 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1878 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1879 } else { 1880 unsigned ReservedOffsetReg = 1881 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1882 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1883 Info.setFrameOffsetReg(ReservedOffsetReg); 1884 } 1885 } else if (RequiresStackAccess) { 1886 assert(!MFI.hasCalls()); 1887 // We know there are accesses and they will be done relative to SP, so just 1888 // pin it to the input. 1889 // 1890 // FIXME: Should not do this if inline asm is reading/writing these 1891 // registers. 1892 unsigned PreloadedSP = Info.getPreloadedReg( 1893 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1894 1895 Info.setStackPtrOffsetReg(PreloadedSP); 1896 Info.setScratchWaveOffsetReg(PreloadedSP); 1897 Info.setFrameOffsetReg(PreloadedSP); 1898 } else { 1899 assert(!MFI.hasCalls()); 1900 1901 // There may not be stack access at all. There may still be spills, or 1902 // access of a constant pointer (in which cases an extra copy will be 1903 // emitted in the prolog). 1904 unsigned ReservedOffsetReg 1905 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1906 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1907 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1908 Info.setFrameOffsetReg(ReservedOffsetReg); 1909 } 1910 } 1911 1912 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1913 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1914 return !Info->isEntryFunction(); 1915 } 1916 1917 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1918 1919 } 1920 1921 void SITargetLowering::insertCopiesSplitCSR( 1922 MachineBasicBlock *Entry, 1923 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1924 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1925 1926 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1927 if (!IStart) 1928 return; 1929 1930 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1931 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1932 MachineBasicBlock::iterator MBBI = Entry->begin(); 1933 for (const MCPhysReg *I = IStart; *I; ++I) { 1934 const TargetRegisterClass *RC = nullptr; 1935 if (AMDGPU::SReg_64RegClass.contains(*I)) 1936 RC = &AMDGPU::SGPR_64RegClass; 1937 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1938 RC = &AMDGPU::SGPR_32RegClass; 1939 else 1940 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1941 1942 unsigned NewVR = MRI->createVirtualRegister(RC); 1943 // Create copy from CSR to a virtual register. 1944 Entry->addLiveIn(*I); 1945 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1946 .addReg(*I); 1947 1948 // Insert the copy-back instructions right before the terminator. 1949 for (auto *Exit : Exits) 1950 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1951 TII->get(TargetOpcode::COPY), *I) 1952 .addReg(NewVR); 1953 } 1954 } 1955 1956 SDValue SITargetLowering::LowerFormalArguments( 1957 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1958 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1959 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1960 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1961 1962 MachineFunction &MF = DAG.getMachineFunction(); 1963 const Function &Fn = MF.getFunction(); 1964 FunctionType *FType = MF.getFunction().getFunctionType(); 1965 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1966 1967 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1968 DiagnosticInfoUnsupported NoGraphicsHSA( 1969 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 1970 DAG.getContext()->diagnose(NoGraphicsHSA); 1971 return DAG.getEntryNode(); 1972 } 1973 1974 SmallVector<ISD::InputArg, 16> Splits; 1975 SmallVector<CCValAssign, 16> ArgLocs; 1976 BitVector Skipped(Ins.size()); 1977 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 1978 *DAG.getContext()); 1979 1980 bool IsShader = AMDGPU::isShader(CallConv); 1981 bool IsKernel = AMDGPU::isKernel(CallConv); 1982 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 1983 1984 if (IsShader) { 1985 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 1986 1987 // At least one interpolation mode must be enabled or else the GPU will 1988 // hang. 1989 // 1990 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 1991 // set PSInputAddr, the user wants to enable some bits after the compilation 1992 // based on run-time states. Since we can't know what the final PSInputEna 1993 // will look like, so we shouldn't do anything here and the user should take 1994 // responsibility for the correct programming. 1995 // 1996 // Otherwise, the following restrictions apply: 1997 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 1998 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 1999 // enabled too. 2000 if (CallConv == CallingConv::AMDGPU_PS) { 2001 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2002 ((Info->getPSInputAddr() & 0xF) == 0 && 2003 Info->isPSInputAllocated(11))) { 2004 CCInfo.AllocateReg(AMDGPU::VGPR0); 2005 CCInfo.AllocateReg(AMDGPU::VGPR1); 2006 Info->markPSInputAllocated(0); 2007 Info->markPSInputEnabled(0); 2008 } 2009 if (Subtarget->isAmdPalOS()) { 2010 // For isAmdPalOS, the user does not enable some bits after compilation 2011 // based on run-time states; the register values being generated here are 2012 // the final ones set in hardware. Therefore we need to apply the 2013 // workaround to PSInputAddr and PSInputEnable together. (The case where 2014 // a bit is set in PSInputAddr but not PSInputEnable is where the 2015 // frontend set up an input arg for a particular interpolation mode, but 2016 // nothing uses that input arg. Really we should have an earlier pass 2017 // that removes such an arg.) 2018 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2019 if ((PsInputBits & 0x7F) == 0 || 2020 ((PsInputBits & 0xF) == 0 && 2021 (PsInputBits >> 11 & 1))) 2022 Info->markPSInputEnabled( 2023 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2024 } 2025 } 2026 2027 assert(!Info->hasDispatchPtr() && 2028 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2029 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2030 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2031 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2032 !Info->hasWorkItemIDZ()); 2033 } else if (IsKernel) { 2034 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2035 } else { 2036 Splits.append(Ins.begin(), Ins.end()); 2037 } 2038 2039 if (IsEntryFunc) { 2040 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2041 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2042 } 2043 2044 if (IsKernel) { 2045 analyzeFormalArgumentsCompute(CCInfo, Ins); 2046 } else { 2047 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2048 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2049 } 2050 2051 SmallVector<SDValue, 16> Chains; 2052 2053 // FIXME: This is the minimum kernel argument alignment. We should improve 2054 // this to the maximum alignment of the arguments. 2055 // 2056 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2057 // kern arg offset. 2058 const unsigned KernelArgBaseAlign = 16; 2059 2060 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2061 const ISD::InputArg &Arg = Ins[i]; 2062 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2063 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2064 continue; 2065 } 2066 2067 CCValAssign &VA = ArgLocs[ArgIdx++]; 2068 MVT VT = VA.getLocVT(); 2069 2070 if (IsEntryFunc && VA.isMemLoc()) { 2071 VT = Ins[i].VT; 2072 EVT MemVT = VA.getLocVT(); 2073 2074 const uint64_t Offset = VA.getLocMemOffset(); 2075 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2076 2077 SDValue Arg = lowerKernargMemParameter( 2078 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2079 Chains.push_back(Arg.getValue(1)); 2080 2081 auto *ParamTy = 2082 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2083 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2084 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2085 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2086 // On SI local pointers are just offsets into LDS, so they are always 2087 // less than 16-bits. On CI and newer they could potentially be 2088 // real pointers, so we can't guarantee their size. 2089 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2090 DAG.getValueType(MVT::i16)); 2091 } 2092 2093 InVals.push_back(Arg); 2094 continue; 2095 } else if (!IsEntryFunc && VA.isMemLoc()) { 2096 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2097 InVals.push_back(Val); 2098 if (!Arg.Flags.isByVal()) 2099 Chains.push_back(Val.getValue(1)); 2100 continue; 2101 } 2102 2103 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2104 2105 unsigned Reg = VA.getLocReg(); 2106 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2107 EVT ValVT = VA.getValVT(); 2108 2109 Reg = MF.addLiveIn(Reg, RC); 2110 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2111 2112 if (Arg.Flags.isSRet()) { 2113 // The return object should be reasonably addressable. 2114 2115 // FIXME: This helps when the return is a real sret. If it is a 2116 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2117 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2118 unsigned NumBits 2119 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2120 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2121 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2122 } 2123 2124 // If this is an 8 or 16-bit value, it is really passed promoted 2125 // to 32 bits. Insert an assert[sz]ext to capture this, then 2126 // truncate to the right size. 2127 switch (VA.getLocInfo()) { 2128 case CCValAssign::Full: 2129 break; 2130 case CCValAssign::BCvt: 2131 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2132 break; 2133 case CCValAssign::SExt: 2134 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2135 DAG.getValueType(ValVT)); 2136 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2137 break; 2138 case CCValAssign::ZExt: 2139 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2140 DAG.getValueType(ValVT)); 2141 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2142 break; 2143 case CCValAssign::AExt: 2144 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2145 break; 2146 default: 2147 llvm_unreachable("Unknown loc info!"); 2148 } 2149 2150 InVals.push_back(Val); 2151 } 2152 2153 if (!IsEntryFunc) { 2154 // Special inputs come after user arguments. 2155 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2156 } 2157 2158 // Start adding system SGPRs. 2159 if (IsEntryFunc) { 2160 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2161 } else { 2162 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2163 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2164 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2165 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2166 } 2167 2168 auto &ArgUsageInfo = 2169 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2170 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2171 2172 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2173 Info->setBytesInStackArgArea(StackArgSize); 2174 2175 return Chains.empty() ? Chain : 2176 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2177 } 2178 2179 // TODO: If return values can't fit in registers, we should return as many as 2180 // possible in registers before passing on stack. 2181 bool SITargetLowering::CanLowerReturn( 2182 CallingConv::ID CallConv, 2183 MachineFunction &MF, bool IsVarArg, 2184 const SmallVectorImpl<ISD::OutputArg> &Outs, 2185 LLVMContext &Context) const { 2186 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2187 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2188 // for shaders. Vector types should be explicitly handled by CC. 2189 if (AMDGPU::isEntryFunctionCC(CallConv)) 2190 return true; 2191 2192 SmallVector<CCValAssign, 16> RVLocs; 2193 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2194 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2195 } 2196 2197 SDValue 2198 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2199 bool isVarArg, 2200 const SmallVectorImpl<ISD::OutputArg> &Outs, 2201 const SmallVectorImpl<SDValue> &OutVals, 2202 const SDLoc &DL, SelectionDAG &DAG) const { 2203 MachineFunction &MF = DAG.getMachineFunction(); 2204 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2205 2206 if (AMDGPU::isKernel(CallConv)) { 2207 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2208 OutVals, DL, DAG); 2209 } 2210 2211 bool IsShader = AMDGPU::isShader(CallConv); 2212 2213 Info->setIfReturnsVoid(Outs.empty()); 2214 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2215 2216 // CCValAssign - represent the assignment of the return value to a location. 2217 SmallVector<CCValAssign, 48> RVLocs; 2218 SmallVector<ISD::OutputArg, 48> Splits; 2219 2220 // CCState - Info about the registers and stack slots. 2221 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2222 *DAG.getContext()); 2223 2224 // Analyze outgoing return values. 2225 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2226 2227 SDValue Flag; 2228 SmallVector<SDValue, 48> RetOps; 2229 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2230 2231 // Add return address for callable functions. 2232 if (!Info->isEntryFunction()) { 2233 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2234 SDValue ReturnAddrReg = CreateLiveInRegister( 2235 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2236 2237 // FIXME: Should be able to use a vreg here, but need a way to prevent it 2238 // from being allcoated to a CSR. 2239 2240 SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2241 MVT::i64); 2242 2243 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag); 2244 Flag = Chain.getValue(1); 2245 2246 RetOps.push_back(PhysReturnAddrReg); 2247 } 2248 2249 // Copy the result values into the output registers. 2250 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2251 ++I, ++RealRVLocIdx) { 2252 CCValAssign &VA = RVLocs[I]; 2253 assert(VA.isRegLoc() && "Can only return in registers!"); 2254 // TODO: Partially return in registers if return values don't fit. 2255 SDValue Arg = OutVals[RealRVLocIdx]; 2256 2257 // Copied from other backends. 2258 switch (VA.getLocInfo()) { 2259 case CCValAssign::Full: 2260 break; 2261 case CCValAssign::BCvt: 2262 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2263 break; 2264 case CCValAssign::SExt: 2265 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2266 break; 2267 case CCValAssign::ZExt: 2268 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2269 break; 2270 case CCValAssign::AExt: 2271 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2272 break; 2273 default: 2274 llvm_unreachable("Unknown loc info!"); 2275 } 2276 2277 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2278 Flag = Chain.getValue(1); 2279 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2280 } 2281 2282 // FIXME: Does sret work properly? 2283 if (!Info->isEntryFunction()) { 2284 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2285 const MCPhysReg *I = 2286 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2287 if (I) { 2288 for (; *I; ++I) { 2289 if (AMDGPU::SReg_64RegClass.contains(*I)) 2290 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2291 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2292 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2293 else 2294 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2295 } 2296 } 2297 } 2298 2299 // Update chain and glue. 2300 RetOps[0] = Chain; 2301 if (Flag.getNode()) 2302 RetOps.push_back(Flag); 2303 2304 unsigned Opc = AMDGPUISD::ENDPGM; 2305 if (!IsWaveEnd) 2306 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2307 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2308 } 2309 2310 SDValue SITargetLowering::LowerCallResult( 2311 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2312 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2313 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2314 SDValue ThisVal) const { 2315 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2316 2317 // Assign locations to each value returned by this call. 2318 SmallVector<CCValAssign, 16> RVLocs; 2319 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2320 *DAG.getContext()); 2321 CCInfo.AnalyzeCallResult(Ins, RetCC); 2322 2323 // Copy all of the result registers out of their specified physreg. 2324 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2325 CCValAssign VA = RVLocs[i]; 2326 SDValue Val; 2327 2328 if (VA.isRegLoc()) { 2329 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2330 Chain = Val.getValue(1); 2331 InFlag = Val.getValue(2); 2332 } else if (VA.isMemLoc()) { 2333 report_fatal_error("TODO: return values in memory"); 2334 } else 2335 llvm_unreachable("unknown argument location type"); 2336 2337 switch (VA.getLocInfo()) { 2338 case CCValAssign::Full: 2339 break; 2340 case CCValAssign::BCvt: 2341 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2342 break; 2343 case CCValAssign::ZExt: 2344 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2345 DAG.getValueType(VA.getValVT())); 2346 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2347 break; 2348 case CCValAssign::SExt: 2349 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2350 DAG.getValueType(VA.getValVT())); 2351 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2352 break; 2353 case CCValAssign::AExt: 2354 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2355 break; 2356 default: 2357 llvm_unreachable("Unknown loc info!"); 2358 } 2359 2360 InVals.push_back(Val); 2361 } 2362 2363 return Chain; 2364 } 2365 2366 // Add code to pass special inputs required depending on used features separate 2367 // from the explicit user arguments present in the IR. 2368 void SITargetLowering::passSpecialInputs( 2369 CallLoweringInfo &CLI, 2370 CCState &CCInfo, 2371 const SIMachineFunctionInfo &Info, 2372 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2373 SmallVectorImpl<SDValue> &MemOpChains, 2374 SDValue Chain) const { 2375 // If we don't have a call site, this was a call inserted by 2376 // legalization. These can never use special inputs. 2377 if (!CLI.CS) 2378 return; 2379 2380 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2381 assert(CalleeFunc); 2382 2383 SelectionDAG &DAG = CLI.DAG; 2384 const SDLoc &DL = CLI.DL; 2385 2386 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2387 2388 auto &ArgUsageInfo = 2389 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2390 const AMDGPUFunctionArgInfo &CalleeArgInfo 2391 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2392 2393 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2394 2395 // TODO: Unify with private memory register handling. This is complicated by 2396 // the fact that at least in kernels, the input argument is not necessarily 2397 // in the same location as the input. 2398 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2399 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2400 AMDGPUFunctionArgInfo::QUEUE_PTR, 2401 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2402 AMDGPUFunctionArgInfo::DISPATCH_ID, 2403 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2404 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2405 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2406 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2407 }; 2408 2409 for (auto InputID : InputRegs) { 2410 const ArgDescriptor *OutgoingArg; 2411 const TargetRegisterClass *ArgRC; 2412 2413 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2414 if (!OutgoingArg) 2415 continue; 2416 2417 const ArgDescriptor *IncomingArg; 2418 const TargetRegisterClass *IncomingArgRC; 2419 std::tie(IncomingArg, IncomingArgRC) 2420 = CallerArgInfo.getPreloadedValue(InputID); 2421 assert(IncomingArgRC == ArgRC); 2422 2423 // All special arguments are ints for now. 2424 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2425 SDValue InputReg; 2426 2427 if (IncomingArg) { 2428 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2429 } else { 2430 // The implicit arg ptr is special because it doesn't have a corresponding 2431 // input for kernels, and is computed from the kernarg segment pointer. 2432 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2433 InputReg = getImplicitArgPtr(DAG, DL); 2434 } 2435 2436 if (OutgoingArg->isRegister()) { 2437 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2438 } else { 2439 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2440 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2441 SpecialArgOffset); 2442 MemOpChains.push_back(ArgStore); 2443 } 2444 } 2445 2446 // Pack workitem IDs into a single register or pass it as is if already 2447 // packed. 2448 const ArgDescriptor *OutgoingArg; 2449 const TargetRegisterClass *ArgRC; 2450 2451 std::tie(OutgoingArg, ArgRC) = 2452 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2453 if (!OutgoingArg) 2454 std::tie(OutgoingArg, ArgRC) = 2455 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2456 if (!OutgoingArg) 2457 std::tie(OutgoingArg, ArgRC) = 2458 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2459 if (!OutgoingArg) 2460 return; 2461 2462 const ArgDescriptor *IncomingArgX 2463 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2464 const ArgDescriptor *IncomingArgY 2465 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2466 const ArgDescriptor *IncomingArgZ 2467 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2468 2469 SDValue InputReg; 2470 SDLoc SL; 2471 2472 // If incoming ids are not packed we need to pack them. 2473 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2474 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2475 2476 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2477 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2478 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2479 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2480 InputReg = InputReg.getNode() ? 2481 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2482 } 2483 2484 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2485 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2486 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2487 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2488 InputReg = InputReg.getNode() ? 2489 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2490 } 2491 2492 if (!InputReg.getNode()) { 2493 // Workitem ids are already packed, any of present incoming arguments 2494 // will carry all required fields. 2495 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2496 IncomingArgX ? *IncomingArgX : 2497 IncomingArgY ? *IncomingArgY : 2498 *IncomingArgZ, ~0u); 2499 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2500 } 2501 2502 if (OutgoingArg->isRegister()) { 2503 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2504 } else { 2505 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2506 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2507 SpecialArgOffset); 2508 MemOpChains.push_back(ArgStore); 2509 } 2510 } 2511 2512 static bool canGuaranteeTCO(CallingConv::ID CC) { 2513 return CC == CallingConv::Fast; 2514 } 2515 2516 /// Return true if we might ever do TCO for calls with this calling convention. 2517 static bool mayTailCallThisCC(CallingConv::ID CC) { 2518 switch (CC) { 2519 case CallingConv::C: 2520 return true; 2521 default: 2522 return canGuaranteeTCO(CC); 2523 } 2524 } 2525 2526 bool SITargetLowering::isEligibleForTailCallOptimization( 2527 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2528 const SmallVectorImpl<ISD::OutputArg> &Outs, 2529 const SmallVectorImpl<SDValue> &OutVals, 2530 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2531 if (!mayTailCallThisCC(CalleeCC)) 2532 return false; 2533 2534 MachineFunction &MF = DAG.getMachineFunction(); 2535 const Function &CallerF = MF.getFunction(); 2536 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2537 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2538 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2539 2540 // Kernels aren't callable, and don't have a live in return address so it 2541 // doesn't make sense to do a tail call with entry functions. 2542 if (!CallerPreserved) 2543 return false; 2544 2545 bool CCMatch = CallerCC == CalleeCC; 2546 2547 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2548 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2549 return true; 2550 return false; 2551 } 2552 2553 // TODO: Can we handle var args? 2554 if (IsVarArg) 2555 return false; 2556 2557 for (const Argument &Arg : CallerF.args()) { 2558 if (Arg.hasByValAttr()) 2559 return false; 2560 } 2561 2562 LLVMContext &Ctx = *DAG.getContext(); 2563 2564 // Check that the call results are passed in the same way. 2565 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2566 CCAssignFnForCall(CalleeCC, IsVarArg), 2567 CCAssignFnForCall(CallerCC, IsVarArg))) 2568 return false; 2569 2570 // The callee has to preserve all registers the caller needs to preserve. 2571 if (!CCMatch) { 2572 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2573 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2574 return false; 2575 } 2576 2577 // Nothing more to check if the callee is taking no arguments. 2578 if (Outs.empty()) 2579 return true; 2580 2581 SmallVector<CCValAssign, 16> ArgLocs; 2582 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2583 2584 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2585 2586 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2587 // If the stack arguments for this call do not fit into our own save area then 2588 // the call cannot be made tail. 2589 // TODO: Is this really necessary? 2590 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2591 return false; 2592 2593 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2594 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2595 } 2596 2597 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2598 if (!CI->isTailCall()) 2599 return false; 2600 2601 const Function *ParentFn = CI->getParent()->getParent(); 2602 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2603 return false; 2604 2605 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2606 return (Attr.getValueAsString() != "true"); 2607 } 2608 2609 // The wave scratch offset register is used as the global base pointer. 2610 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2611 SmallVectorImpl<SDValue> &InVals) const { 2612 SelectionDAG &DAG = CLI.DAG; 2613 const SDLoc &DL = CLI.DL; 2614 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2615 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2616 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2617 SDValue Chain = CLI.Chain; 2618 SDValue Callee = CLI.Callee; 2619 bool &IsTailCall = CLI.IsTailCall; 2620 CallingConv::ID CallConv = CLI.CallConv; 2621 bool IsVarArg = CLI.IsVarArg; 2622 bool IsSibCall = false; 2623 bool IsThisReturn = false; 2624 MachineFunction &MF = DAG.getMachineFunction(); 2625 2626 if (IsVarArg) { 2627 return lowerUnhandledCall(CLI, InVals, 2628 "unsupported call to variadic function "); 2629 } 2630 2631 if (!CLI.CS.getInstruction()) 2632 report_fatal_error("unsupported libcall legalization"); 2633 2634 if (!CLI.CS.getCalledFunction()) { 2635 return lowerUnhandledCall(CLI, InVals, 2636 "unsupported indirect call to function "); 2637 } 2638 2639 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2640 return lowerUnhandledCall(CLI, InVals, 2641 "unsupported required tail call to function "); 2642 } 2643 2644 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2645 // Note the issue is with the CC of the calling function, not of the call 2646 // itself. 2647 return lowerUnhandledCall(CLI, InVals, 2648 "unsupported call from graphics shader of function "); 2649 } 2650 2651 if (IsTailCall) { 2652 IsTailCall = isEligibleForTailCallOptimization( 2653 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2654 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2655 report_fatal_error("failed to perform tail call elimination on a call " 2656 "site marked musttail"); 2657 } 2658 2659 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2660 2661 // A sibling call is one where we're under the usual C ABI and not planning 2662 // to change that but can still do a tail call: 2663 if (!TailCallOpt && IsTailCall) 2664 IsSibCall = true; 2665 2666 if (IsTailCall) 2667 ++NumTailCalls; 2668 } 2669 2670 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2671 2672 // Analyze operands of the call, assigning locations to each operand. 2673 SmallVector<CCValAssign, 16> ArgLocs; 2674 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2675 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2676 2677 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2678 2679 // Get a count of how many bytes are to be pushed on the stack. 2680 unsigned NumBytes = CCInfo.getNextStackOffset(); 2681 2682 if (IsSibCall) { 2683 // Since we're not changing the ABI to make this a tail call, the memory 2684 // operands are already available in the caller's incoming argument space. 2685 NumBytes = 0; 2686 } 2687 2688 // FPDiff is the byte offset of the call's argument area from the callee's. 2689 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2690 // by this amount for a tail call. In a sibling call it must be 0 because the 2691 // caller will deallocate the entire stack and the callee still expects its 2692 // arguments to begin at SP+0. Completely unused for non-tail calls. 2693 int32_t FPDiff = 0; 2694 MachineFrameInfo &MFI = MF.getFrameInfo(); 2695 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2696 2697 SDValue CallerSavedFP; 2698 2699 // Adjust the stack pointer for the new arguments... 2700 // These operations are automatically eliminated by the prolog/epilog pass 2701 if (!IsSibCall) { 2702 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2703 2704 SmallVector<SDValue, 4> CopyFromChains; 2705 2706 // In the HSA case, this should be an identity copy. 2707 SDValue ScratchRSrcReg 2708 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2709 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2710 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2711 2712 if (!Info->isEntryFunction()) { 2713 // Avoid clobbering this function's FP value. In the current convention 2714 // callee will overwrite this, so do save/restore around the call site. 2715 CallerSavedFP = DAG.getCopyFromReg(Chain, DL, 2716 Info->getFrameOffsetReg(), MVT::i32); 2717 CopyFromChains.push_back(CallerSavedFP.getValue(1)); 2718 } 2719 2720 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2721 } 2722 2723 SmallVector<SDValue, 8> MemOpChains; 2724 MVT PtrVT = MVT::i32; 2725 2726 // Walk the register/memloc assignments, inserting copies/loads. 2727 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2728 ++i, ++realArgIdx) { 2729 CCValAssign &VA = ArgLocs[i]; 2730 SDValue Arg = OutVals[realArgIdx]; 2731 2732 // Promote the value if needed. 2733 switch (VA.getLocInfo()) { 2734 case CCValAssign::Full: 2735 break; 2736 case CCValAssign::BCvt: 2737 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2738 break; 2739 case CCValAssign::ZExt: 2740 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2741 break; 2742 case CCValAssign::SExt: 2743 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2744 break; 2745 case CCValAssign::AExt: 2746 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2747 break; 2748 case CCValAssign::FPExt: 2749 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2750 break; 2751 default: 2752 llvm_unreachable("Unknown loc info!"); 2753 } 2754 2755 if (VA.isRegLoc()) { 2756 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2757 } else { 2758 assert(VA.isMemLoc()); 2759 2760 SDValue DstAddr; 2761 MachinePointerInfo DstInfo; 2762 2763 unsigned LocMemOffset = VA.getLocMemOffset(); 2764 int32_t Offset = LocMemOffset; 2765 2766 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2767 unsigned Align = 0; 2768 2769 if (IsTailCall) { 2770 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2771 unsigned OpSize = Flags.isByVal() ? 2772 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2773 2774 // FIXME: We can have better than the minimum byval required alignment. 2775 Align = Flags.isByVal() ? Flags.getByValAlign() : 2776 MinAlign(Subtarget->getStackAlignment(), Offset); 2777 2778 Offset = Offset + FPDiff; 2779 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2780 2781 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2782 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2783 2784 // Make sure any stack arguments overlapping with where we're storing 2785 // are loaded before this eventual operation. Otherwise they'll be 2786 // clobbered. 2787 2788 // FIXME: Why is this really necessary? This seems to just result in a 2789 // lot of code to copy the stack and write them back to the same 2790 // locations, which are supposed to be immutable? 2791 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2792 } else { 2793 DstAddr = PtrOff; 2794 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2795 Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset); 2796 } 2797 2798 if (Outs[i].Flags.isByVal()) { 2799 SDValue SizeNode = 2800 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2801 SDValue Cpy = DAG.getMemcpy( 2802 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2803 /*isVol = */ false, /*AlwaysInline = */ true, 2804 /*isTailCall = */ false, DstInfo, 2805 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2806 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS)))); 2807 2808 MemOpChains.push_back(Cpy); 2809 } else { 2810 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align); 2811 MemOpChains.push_back(Store); 2812 } 2813 } 2814 } 2815 2816 // Copy special input registers after user input arguments. 2817 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2818 2819 if (!MemOpChains.empty()) 2820 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2821 2822 // Build a sequence of copy-to-reg nodes chained together with token chain 2823 // and flag operands which copy the outgoing args into the appropriate regs. 2824 SDValue InFlag; 2825 for (auto &RegToPass : RegsToPass) { 2826 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2827 RegToPass.second, InFlag); 2828 InFlag = Chain.getValue(1); 2829 } 2830 2831 2832 SDValue PhysReturnAddrReg; 2833 if (IsTailCall) { 2834 // Since the return is being combined with the call, we need to pass on the 2835 // return address. 2836 2837 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2838 SDValue ReturnAddrReg = CreateLiveInRegister( 2839 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2840 2841 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2842 MVT::i64); 2843 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2844 InFlag = Chain.getValue(1); 2845 } 2846 2847 // We don't usually want to end the call-sequence here because we would tidy 2848 // the frame up *after* the call, however in the ABI-changing tail-call case 2849 // we've carefully laid out the parameters so that when sp is reset they'll be 2850 // in the correct location. 2851 if (IsTailCall && !IsSibCall) { 2852 Chain = DAG.getCALLSEQ_END(Chain, 2853 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2854 DAG.getTargetConstant(0, DL, MVT::i32), 2855 InFlag, DL); 2856 InFlag = Chain.getValue(1); 2857 } 2858 2859 std::vector<SDValue> Ops; 2860 Ops.push_back(Chain); 2861 Ops.push_back(Callee); 2862 // Add a redundant copy of the callee global which will not be legalized, as 2863 // we need direct access to the callee later. 2864 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2865 const GlobalValue *GV = GSD->getGlobal(); 2866 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2867 2868 if (IsTailCall) { 2869 // Each tail call may have to adjust the stack by a different amount, so 2870 // this information must travel along with the operation for eventual 2871 // consumption by emitEpilogue. 2872 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2873 2874 Ops.push_back(PhysReturnAddrReg); 2875 } 2876 2877 // Add argument registers to the end of the list so that they are known live 2878 // into the call. 2879 for (auto &RegToPass : RegsToPass) { 2880 Ops.push_back(DAG.getRegister(RegToPass.first, 2881 RegToPass.second.getValueType())); 2882 } 2883 2884 // Add a register mask operand representing the call-preserved registers. 2885 2886 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2887 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2888 assert(Mask && "Missing call preserved mask for calling convention"); 2889 Ops.push_back(DAG.getRegisterMask(Mask)); 2890 2891 if (InFlag.getNode()) 2892 Ops.push_back(InFlag); 2893 2894 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2895 2896 // If we're doing a tall call, use a TC_RETURN here rather than an 2897 // actual call instruction. 2898 if (IsTailCall) { 2899 MFI.setHasTailCall(); 2900 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2901 } 2902 2903 // Returns a chain and a flag for retval copy to use. 2904 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2905 Chain = Call.getValue(0); 2906 InFlag = Call.getValue(1); 2907 2908 if (CallerSavedFP) { 2909 SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32); 2910 Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag); 2911 InFlag = Chain.getValue(1); 2912 } 2913 2914 uint64_t CalleePopBytes = NumBytes; 2915 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2916 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2917 InFlag, DL); 2918 if (!Ins.empty()) 2919 InFlag = Chain.getValue(1); 2920 2921 // Handle result values, copying them out of physregs into vregs that we 2922 // return. 2923 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2924 InVals, IsThisReturn, 2925 IsThisReturn ? OutVals[0] : SDValue()); 2926 } 2927 2928 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2929 SelectionDAG &DAG) const { 2930 unsigned Reg = StringSwitch<unsigned>(RegName) 2931 .Case("m0", AMDGPU::M0) 2932 .Case("exec", AMDGPU::EXEC) 2933 .Case("exec_lo", AMDGPU::EXEC_LO) 2934 .Case("exec_hi", AMDGPU::EXEC_HI) 2935 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2936 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2937 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2938 .Default(AMDGPU::NoRegister); 2939 2940 if (Reg == AMDGPU::NoRegister) { 2941 report_fatal_error(Twine("invalid register name \"" 2942 + StringRef(RegName) + "\".")); 2943 2944 } 2945 2946 if (!Subtarget->hasFlatScrRegister() && 2947 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2948 report_fatal_error(Twine("invalid register \"" 2949 + StringRef(RegName) + "\" for subtarget.")); 2950 } 2951 2952 switch (Reg) { 2953 case AMDGPU::M0: 2954 case AMDGPU::EXEC_LO: 2955 case AMDGPU::EXEC_HI: 2956 case AMDGPU::FLAT_SCR_LO: 2957 case AMDGPU::FLAT_SCR_HI: 2958 if (VT.getSizeInBits() == 32) 2959 return Reg; 2960 break; 2961 case AMDGPU::EXEC: 2962 case AMDGPU::FLAT_SCR: 2963 if (VT.getSizeInBits() == 64) 2964 return Reg; 2965 break; 2966 default: 2967 llvm_unreachable("missing register type checking"); 2968 } 2969 2970 report_fatal_error(Twine("invalid type for register \"" 2971 + StringRef(RegName) + "\".")); 2972 } 2973 2974 // If kill is not the last instruction, split the block so kill is always a 2975 // proper terminator. 2976 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2977 MachineBasicBlock *BB) const { 2978 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2979 2980 MachineBasicBlock::iterator SplitPoint(&MI); 2981 ++SplitPoint; 2982 2983 if (SplitPoint == BB->end()) { 2984 // Don't bother with a new block. 2985 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2986 return BB; 2987 } 2988 2989 MachineFunction *MF = BB->getParent(); 2990 MachineBasicBlock *SplitBB 2991 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 2992 2993 MF->insert(++MachineFunction::iterator(BB), SplitBB); 2994 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 2995 2996 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 2997 BB->addSuccessor(SplitBB); 2998 2999 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3000 return SplitBB; 3001 } 3002 3003 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3004 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3005 // be the first instruction in the remainder block. 3006 // 3007 /// \returns { LoopBody, Remainder } 3008 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3009 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3010 MachineFunction *MF = MBB.getParent(); 3011 MachineBasicBlock::iterator I(&MI); 3012 3013 // To insert the loop we need to split the block. Move everything after this 3014 // point to a new block, and insert a new empty block between the two. 3015 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3016 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3017 MachineFunction::iterator MBBI(MBB); 3018 ++MBBI; 3019 3020 MF->insert(MBBI, LoopBB); 3021 MF->insert(MBBI, RemainderBB); 3022 3023 LoopBB->addSuccessor(LoopBB); 3024 LoopBB->addSuccessor(RemainderBB); 3025 3026 // Move the rest of the block into a new block. 3027 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3028 3029 if (InstInLoop) { 3030 auto Next = std::next(I); 3031 3032 // Move instruction to loop body. 3033 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3034 3035 // Move the rest of the block. 3036 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3037 } else { 3038 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3039 } 3040 3041 MBB.addSuccessor(LoopBB); 3042 3043 return std::make_pair(LoopBB, RemainderBB); 3044 } 3045 3046 MachineBasicBlock * 3047 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3048 MachineBasicBlock *BB) const { 3049 const DebugLoc &DL = MI.getDebugLoc(); 3050 3051 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3052 3053 MachineBasicBlock *LoopBB; 3054 MachineBasicBlock *RemainderBB; 3055 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3056 3057 MachineBasicBlock::iterator Prev = std::prev(MI.getIterator()); 3058 3059 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3060 3061 MachineBasicBlock::iterator I = LoopBB->end(); 3062 MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 3063 3064 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3065 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3066 3067 // Clear TRAP_STS.MEM_VIOL 3068 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3069 .addImm(0) 3070 .addImm(EncodedReg); 3071 3072 // This is a pain, but we're not allowed to have physical register live-ins 3073 // yet. Insert a pair of copies if the VGPR0 hack is necessary. 3074 if (Src && TargetRegisterInfo::isPhysicalRegister(Src->getReg())) { 3075 unsigned Data0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3076 BuildMI(*BB, std::next(Prev), DL, TII->get(AMDGPU::COPY), Data0) 3077 .add(*Src); 3078 3079 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::COPY), Src->getReg()) 3080 .addReg(Data0); 3081 3082 MRI.setSimpleHint(Data0, Src->getReg()); 3083 } 3084 3085 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_WAITCNT)) 3086 .addImm(0); 3087 3088 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3089 3090 // Load and check TRAP_STS.MEM_VIOL 3091 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3092 .addImm(EncodedReg); 3093 3094 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3095 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3096 .addReg(Reg, RegState::Kill) 3097 .addImm(0); 3098 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3099 .addMBB(LoopBB); 3100 3101 return RemainderBB; 3102 } 3103 3104 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3105 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3106 // will only do one iteration. In the worst case, this will loop 64 times. 3107 // 3108 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3109 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3110 const SIInstrInfo *TII, 3111 MachineRegisterInfo &MRI, 3112 MachineBasicBlock &OrigBB, 3113 MachineBasicBlock &LoopBB, 3114 const DebugLoc &DL, 3115 const MachineOperand &IdxReg, 3116 unsigned InitReg, 3117 unsigned ResultReg, 3118 unsigned PhiReg, 3119 unsigned InitSaveExecReg, 3120 int Offset, 3121 bool UseGPRIdxMode, 3122 bool IsIndirectSrc) { 3123 MachineFunction *MF = OrigBB.getParent(); 3124 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3125 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3126 MachineBasicBlock::iterator I = LoopBB.begin(); 3127 3128 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3129 unsigned PhiExec = MRI.createVirtualRegister(BoolRC); 3130 unsigned NewExec = MRI.createVirtualRegister(BoolRC); 3131 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3132 unsigned CondReg = MRI.createVirtualRegister(BoolRC); 3133 3134 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3135 .addReg(InitReg) 3136 .addMBB(&OrigBB) 3137 .addReg(ResultReg) 3138 .addMBB(&LoopBB); 3139 3140 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3141 .addReg(InitSaveExecReg) 3142 .addMBB(&OrigBB) 3143 .addReg(NewExec) 3144 .addMBB(&LoopBB); 3145 3146 // Read the next variant <- also loop target. 3147 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3148 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3149 3150 // Compare the just read M0 value to all possible Idx values. 3151 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3152 .addReg(CurrentIdxReg) 3153 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3154 3155 // Update EXEC, save the original EXEC value to VCC. 3156 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3157 : AMDGPU::S_AND_SAVEEXEC_B64), 3158 NewExec) 3159 .addReg(CondReg, RegState::Kill); 3160 3161 MRI.setSimpleHint(NewExec, CondReg); 3162 3163 if (UseGPRIdxMode) { 3164 unsigned IdxReg; 3165 if (Offset == 0) { 3166 IdxReg = CurrentIdxReg; 3167 } else { 3168 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3169 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3170 .addReg(CurrentIdxReg, RegState::Kill) 3171 .addImm(Offset); 3172 } 3173 unsigned IdxMode = IsIndirectSrc ? 3174 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3175 MachineInstr *SetOn = 3176 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3177 .addReg(IdxReg, RegState::Kill) 3178 .addImm(IdxMode); 3179 SetOn->getOperand(3).setIsUndef(); 3180 } else { 3181 // Move index from VCC into M0 3182 if (Offset == 0) { 3183 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3184 .addReg(CurrentIdxReg, RegState::Kill); 3185 } else { 3186 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3187 .addReg(CurrentIdxReg, RegState::Kill) 3188 .addImm(Offset); 3189 } 3190 } 3191 3192 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3193 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3194 MachineInstr *InsertPt = 3195 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3196 : AMDGPU::S_XOR_B64_term), Exec) 3197 .addReg(Exec) 3198 .addReg(NewExec); 3199 3200 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3201 // s_cbranch_scc0? 3202 3203 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3204 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3205 .addMBB(&LoopBB); 3206 3207 return InsertPt->getIterator(); 3208 } 3209 3210 // This has slightly sub-optimal regalloc when the source vector is killed by 3211 // the read. The register allocator does not understand that the kill is 3212 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3213 // subregister from it, using 1 more VGPR than necessary. This was saved when 3214 // this was expanded after register allocation. 3215 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3216 MachineBasicBlock &MBB, 3217 MachineInstr &MI, 3218 unsigned InitResultReg, 3219 unsigned PhiReg, 3220 int Offset, 3221 bool UseGPRIdxMode, 3222 bool IsIndirectSrc) { 3223 MachineFunction *MF = MBB.getParent(); 3224 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3225 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3226 MachineRegisterInfo &MRI = MF->getRegInfo(); 3227 const DebugLoc &DL = MI.getDebugLoc(); 3228 MachineBasicBlock::iterator I(&MI); 3229 3230 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3231 unsigned DstReg = MI.getOperand(0).getReg(); 3232 unsigned SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3233 unsigned TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3234 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3235 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3236 3237 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3238 3239 // Save the EXEC mask 3240 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3241 .addReg(Exec); 3242 3243 MachineBasicBlock *LoopBB; 3244 MachineBasicBlock *RemainderBB; 3245 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3246 3247 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3248 3249 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3250 InitResultReg, DstReg, PhiReg, TmpExec, 3251 Offset, UseGPRIdxMode, IsIndirectSrc); 3252 3253 MachineBasicBlock::iterator First = RemainderBB->begin(); 3254 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3255 .addReg(SaveExec); 3256 3257 return InsPt; 3258 } 3259 3260 // Returns subreg index, offset 3261 static std::pair<unsigned, int> 3262 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3263 const TargetRegisterClass *SuperRC, 3264 unsigned VecReg, 3265 int Offset) { 3266 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3267 3268 // Skip out of bounds offsets, or else we would end up using an undefined 3269 // register. 3270 if (Offset >= NumElts || Offset < 0) 3271 return std::make_pair(AMDGPU::sub0, Offset); 3272 3273 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3274 } 3275 3276 // Return true if the index is an SGPR and was set. 3277 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3278 MachineRegisterInfo &MRI, 3279 MachineInstr &MI, 3280 int Offset, 3281 bool UseGPRIdxMode, 3282 bool IsIndirectSrc) { 3283 MachineBasicBlock *MBB = MI.getParent(); 3284 const DebugLoc &DL = MI.getDebugLoc(); 3285 MachineBasicBlock::iterator I(&MI); 3286 3287 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3288 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3289 3290 assert(Idx->getReg() != AMDGPU::NoRegister); 3291 3292 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3293 return false; 3294 3295 if (UseGPRIdxMode) { 3296 unsigned IdxMode = IsIndirectSrc ? 3297 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3298 if (Offset == 0) { 3299 MachineInstr *SetOn = 3300 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3301 .add(*Idx) 3302 .addImm(IdxMode); 3303 3304 SetOn->getOperand(3).setIsUndef(); 3305 } else { 3306 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3307 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3308 .add(*Idx) 3309 .addImm(Offset); 3310 MachineInstr *SetOn = 3311 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3312 .addReg(Tmp, RegState::Kill) 3313 .addImm(IdxMode); 3314 3315 SetOn->getOperand(3).setIsUndef(); 3316 } 3317 3318 return true; 3319 } 3320 3321 if (Offset == 0) { 3322 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3323 .add(*Idx); 3324 } else { 3325 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3326 .add(*Idx) 3327 .addImm(Offset); 3328 } 3329 3330 return true; 3331 } 3332 3333 // Control flow needs to be inserted if indexing with a VGPR. 3334 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3335 MachineBasicBlock &MBB, 3336 const GCNSubtarget &ST) { 3337 const SIInstrInfo *TII = ST.getInstrInfo(); 3338 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3339 MachineFunction *MF = MBB.getParent(); 3340 MachineRegisterInfo &MRI = MF->getRegInfo(); 3341 3342 unsigned Dst = MI.getOperand(0).getReg(); 3343 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3344 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3345 3346 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3347 3348 unsigned SubReg; 3349 std::tie(SubReg, Offset) 3350 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3351 3352 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3353 3354 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3355 MachineBasicBlock::iterator I(&MI); 3356 const DebugLoc &DL = MI.getDebugLoc(); 3357 3358 if (UseGPRIdxMode) { 3359 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3360 // to avoid interfering with other uses, so probably requires a new 3361 // optimization pass. 3362 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3363 .addReg(SrcReg, RegState::Undef, SubReg) 3364 .addReg(SrcReg, RegState::Implicit) 3365 .addReg(AMDGPU::M0, RegState::Implicit); 3366 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3367 } else { 3368 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3369 .addReg(SrcReg, RegState::Undef, SubReg) 3370 .addReg(SrcReg, RegState::Implicit); 3371 } 3372 3373 MI.eraseFromParent(); 3374 3375 return &MBB; 3376 } 3377 3378 const DebugLoc &DL = MI.getDebugLoc(); 3379 MachineBasicBlock::iterator I(&MI); 3380 3381 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3382 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3383 3384 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3385 3386 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3387 Offset, UseGPRIdxMode, true); 3388 MachineBasicBlock *LoopBB = InsPt->getParent(); 3389 3390 if (UseGPRIdxMode) { 3391 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3392 .addReg(SrcReg, RegState::Undef, SubReg) 3393 .addReg(SrcReg, RegState::Implicit) 3394 .addReg(AMDGPU::M0, RegState::Implicit); 3395 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3396 } else { 3397 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3398 .addReg(SrcReg, RegState::Undef, SubReg) 3399 .addReg(SrcReg, RegState::Implicit); 3400 } 3401 3402 MI.eraseFromParent(); 3403 3404 return LoopBB; 3405 } 3406 3407 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3408 const TargetRegisterClass *VecRC) { 3409 switch (TRI.getRegSizeInBits(*VecRC)) { 3410 case 32: // 4 bytes 3411 return AMDGPU::V_MOVRELD_B32_V1; 3412 case 64: // 8 bytes 3413 return AMDGPU::V_MOVRELD_B32_V2; 3414 case 128: // 16 bytes 3415 return AMDGPU::V_MOVRELD_B32_V4; 3416 case 256: // 32 bytes 3417 return AMDGPU::V_MOVRELD_B32_V8; 3418 case 512: // 64 bytes 3419 return AMDGPU::V_MOVRELD_B32_V16; 3420 default: 3421 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3422 } 3423 } 3424 3425 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3426 MachineBasicBlock &MBB, 3427 const GCNSubtarget &ST) { 3428 const SIInstrInfo *TII = ST.getInstrInfo(); 3429 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3430 MachineFunction *MF = MBB.getParent(); 3431 MachineRegisterInfo &MRI = MF->getRegInfo(); 3432 3433 unsigned Dst = MI.getOperand(0).getReg(); 3434 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3435 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3436 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3437 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3438 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3439 3440 // This can be an immediate, but will be folded later. 3441 assert(Val->getReg()); 3442 3443 unsigned SubReg; 3444 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3445 SrcVec->getReg(), 3446 Offset); 3447 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3448 3449 if (Idx->getReg() == AMDGPU::NoRegister) { 3450 MachineBasicBlock::iterator I(&MI); 3451 const DebugLoc &DL = MI.getDebugLoc(); 3452 3453 assert(Offset == 0); 3454 3455 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3456 .add(*SrcVec) 3457 .add(*Val) 3458 .addImm(SubReg); 3459 3460 MI.eraseFromParent(); 3461 return &MBB; 3462 } 3463 3464 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3465 MachineBasicBlock::iterator I(&MI); 3466 const DebugLoc &DL = MI.getDebugLoc(); 3467 3468 if (UseGPRIdxMode) { 3469 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3470 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3471 .add(*Val) 3472 .addReg(Dst, RegState::ImplicitDefine) 3473 .addReg(SrcVec->getReg(), RegState::Implicit) 3474 .addReg(AMDGPU::M0, RegState::Implicit); 3475 3476 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3477 } else { 3478 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3479 3480 BuildMI(MBB, I, DL, MovRelDesc) 3481 .addReg(Dst, RegState::Define) 3482 .addReg(SrcVec->getReg()) 3483 .add(*Val) 3484 .addImm(SubReg - AMDGPU::sub0); 3485 } 3486 3487 MI.eraseFromParent(); 3488 return &MBB; 3489 } 3490 3491 if (Val->isReg()) 3492 MRI.clearKillFlags(Val->getReg()); 3493 3494 const DebugLoc &DL = MI.getDebugLoc(); 3495 3496 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 3497 3498 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3499 Offset, UseGPRIdxMode, false); 3500 MachineBasicBlock *LoopBB = InsPt->getParent(); 3501 3502 if (UseGPRIdxMode) { 3503 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3504 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3505 .add(*Val) // src0 3506 .addReg(Dst, RegState::ImplicitDefine) 3507 .addReg(PhiReg, RegState::Implicit) 3508 .addReg(AMDGPU::M0, RegState::Implicit); 3509 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3510 } else { 3511 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3512 3513 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3514 .addReg(Dst, RegState::Define) 3515 .addReg(PhiReg) 3516 .add(*Val) 3517 .addImm(SubReg - AMDGPU::sub0); 3518 } 3519 3520 MI.eraseFromParent(); 3521 3522 return LoopBB; 3523 } 3524 3525 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3526 MachineInstr &MI, MachineBasicBlock *BB) const { 3527 3528 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3529 MachineFunction *MF = BB->getParent(); 3530 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3531 3532 if (TII->isMIMG(MI)) { 3533 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3534 report_fatal_error("missing mem operand from MIMG instruction"); 3535 } 3536 // Add a memoperand for mimg instructions so that they aren't assumed to 3537 // be ordered memory instuctions. 3538 3539 return BB; 3540 } 3541 3542 switch (MI.getOpcode()) { 3543 case AMDGPU::S_ADD_U64_PSEUDO: 3544 case AMDGPU::S_SUB_U64_PSEUDO: { 3545 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3546 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3547 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3548 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3549 const DebugLoc &DL = MI.getDebugLoc(); 3550 3551 MachineOperand &Dest = MI.getOperand(0); 3552 MachineOperand &Src0 = MI.getOperand(1); 3553 MachineOperand &Src1 = MI.getOperand(2); 3554 3555 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3556 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3557 3558 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3559 Src0, BoolRC, AMDGPU::sub0, 3560 &AMDGPU::SReg_32_XM0RegClass); 3561 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3562 Src0, BoolRC, AMDGPU::sub1, 3563 &AMDGPU::SReg_32_XM0RegClass); 3564 3565 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3566 Src1, BoolRC, AMDGPU::sub0, 3567 &AMDGPU::SReg_32_XM0RegClass); 3568 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3569 Src1, BoolRC, AMDGPU::sub1, 3570 &AMDGPU::SReg_32_XM0RegClass); 3571 3572 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3573 3574 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3575 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3576 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3577 .add(Src0Sub0) 3578 .add(Src1Sub0); 3579 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3580 .add(Src0Sub1) 3581 .add(Src1Sub1); 3582 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3583 .addReg(DestSub0) 3584 .addImm(AMDGPU::sub0) 3585 .addReg(DestSub1) 3586 .addImm(AMDGPU::sub1); 3587 MI.eraseFromParent(); 3588 return BB; 3589 } 3590 case AMDGPU::SI_INIT_M0: { 3591 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3592 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3593 .add(MI.getOperand(0)); 3594 MI.eraseFromParent(); 3595 return BB; 3596 } 3597 case AMDGPU::SI_INIT_EXEC: 3598 // This should be before all vector instructions. 3599 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3600 AMDGPU::EXEC) 3601 .addImm(MI.getOperand(0).getImm()); 3602 MI.eraseFromParent(); 3603 return BB; 3604 3605 case AMDGPU::SI_INIT_EXEC_LO: 3606 // This should be before all vector instructions. 3607 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3608 AMDGPU::EXEC_LO) 3609 .addImm(MI.getOperand(0).getImm()); 3610 MI.eraseFromParent(); 3611 return BB; 3612 3613 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3614 // Extract the thread count from an SGPR input and set EXEC accordingly. 3615 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3616 // 3617 // S_BFE_U32 count, input, {shift, 7} 3618 // S_BFM_B64 exec, count, 0 3619 // S_CMP_EQ_U32 count, 64 3620 // S_CMOV_B64 exec, -1 3621 MachineInstr *FirstMI = &*BB->begin(); 3622 MachineRegisterInfo &MRI = MF->getRegInfo(); 3623 unsigned InputReg = MI.getOperand(0).getReg(); 3624 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3625 bool Found = false; 3626 3627 // Move the COPY of the input reg to the beginning, so that we can use it. 3628 for (auto I = BB->begin(); I != &MI; I++) { 3629 if (I->getOpcode() != TargetOpcode::COPY || 3630 I->getOperand(0).getReg() != InputReg) 3631 continue; 3632 3633 if (I == FirstMI) { 3634 FirstMI = &*++BB->begin(); 3635 } else { 3636 I->removeFromParent(); 3637 BB->insert(FirstMI, &*I); 3638 } 3639 Found = true; 3640 break; 3641 } 3642 assert(Found); 3643 (void)Found; 3644 3645 // This should be before all vector instructions. 3646 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3647 bool isWave32 = getSubtarget()->isWave32(); 3648 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3649 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3650 .addReg(InputReg) 3651 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3652 BuildMI(*BB, FirstMI, DebugLoc(), 3653 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3654 Exec) 3655 .addReg(CountReg) 3656 .addImm(0); 3657 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3658 .addReg(CountReg, RegState::Kill) 3659 .addImm(getSubtarget()->getWavefrontSize()); 3660 BuildMI(*BB, FirstMI, DebugLoc(), 3661 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3662 Exec) 3663 .addImm(-1); 3664 MI.eraseFromParent(); 3665 return BB; 3666 } 3667 3668 case AMDGPU::GET_GROUPSTATICSIZE: { 3669 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3670 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3671 DebugLoc DL = MI.getDebugLoc(); 3672 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3673 .add(MI.getOperand(0)) 3674 .addImm(MFI->getLDSSize()); 3675 MI.eraseFromParent(); 3676 return BB; 3677 } 3678 case AMDGPU::SI_INDIRECT_SRC_V1: 3679 case AMDGPU::SI_INDIRECT_SRC_V2: 3680 case AMDGPU::SI_INDIRECT_SRC_V4: 3681 case AMDGPU::SI_INDIRECT_SRC_V8: 3682 case AMDGPU::SI_INDIRECT_SRC_V16: 3683 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3684 case AMDGPU::SI_INDIRECT_DST_V1: 3685 case AMDGPU::SI_INDIRECT_DST_V2: 3686 case AMDGPU::SI_INDIRECT_DST_V4: 3687 case AMDGPU::SI_INDIRECT_DST_V8: 3688 case AMDGPU::SI_INDIRECT_DST_V16: 3689 return emitIndirectDst(MI, *BB, *getSubtarget()); 3690 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3691 case AMDGPU::SI_KILL_I1_PSEUDO: 3692 return splitKillBlock(MI, BB); 3693 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3694 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3695 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3696 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3697 3698 unsigned Dst = MI.getOperand(0).getReg(); 3699 unsigned Src0 = MI.getOperand(1).getReg(); 3700 unsigned Src1 = MI.getOperand(2).getReg(); 3701 const DebugLoc &DL = MI.getDebugLoc(); 3702 unsigned SrcCond = MI.getOperand(3).getReg(); 3703 3704 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3705 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3706 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3707 unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC); 3708 3709 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3710 .addReg(SrcCond); 3711 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3712 .addImm(0) 3713 .addReg(Src0, 0, AMDGPU::sub0) 3714 .addImm(0) 3715 .addReg(Src1, 0, AMDGPU::sub0) 3716 .addReg(SrcCondCopy); 3717 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3718 .addImm(0) 3719 .addReg(Src0, 0, AMDGPU::sub1) 3720 .addImm(0) 3721 .addReg(Src1, 0, AMDGPU::sub1) 3722 .addReg(SrcCondCopy); 3723 3724 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3725 .addReg(DstLo) 3726 .addImm(AMDGPU::sub0) 3727 .addReg(DstHi) 3728 .addImm(AMDGPU::sub1); 3729 MI.eraseFromParent(); 3730 return BB; 3731 } 3732 case AMDGPU::SI_BR_UNDEF: { 3733 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3734 const DebugLoc &DL = MI.getDebugLoc(); 3735 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3736 .add(MI.getOperand(0)); 3737 Br->getOperand(1).setIsUndef(true); // read undef SCC 3738 MI.eraseFromParent(); 3739 return BB; 3740 } 3741 case AMDGPU::ADJCALLSTACKUP: 3742 case AMDGPU::ADJCALLSTACKDOWN: { 3743 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3744 MachineInstrBuilder MIB(*MF, &MI); 3745 3746 // Add an implicit use of the frame offset reg to prevent the restore copy 3747 // inserted after the call from being reorderd after stack operations in the 3748 // the caller's frame. 3749 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3750 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3751 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3752 return BB; 3753 } 3754 case AMDGPU::SI_CALL_ISEL: { 3755 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3756 const DebugLoc &DL = MI.getDebugLoc(); 3757 3758 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3759 3760 MachineInstrBuilder MIB; 3761 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3762 3763 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3764 MIB.add(MI.getOperand(I)); 3765 3766 MIB.cloneMemRefs(MI); 3767 MI.eraseFromParent(); 3768 return BB; 3769 } 3770 case AMDGPU::V_ADD_I32_e32: 3771 case AMDGPU::V_SUB_I32_e32: 3772 case AMDGPU::V_SUBREV_I32_e32: { 3773 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3774 const DebugLoc &DL = MI.getDebugLoc(); 3775 unsigned Opc = MI.getOpcode(); 3776 3777 bool NeedClampOperand = false; 3778 if (TII->pseudoToMCOpcode(Opc) == -1) { 3779 Opc = AMDGPU::getVOPe64(Opc); 3780 NeedClampOperand = true; 3781 } 3782 3783 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3784 if (TII->isVOP3(*I)) { 3785 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3786 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3787 I.addReg(TRI->getVCC(), RegState::Define); 3788 } 3789 I.add(MI.getOperand(1)) 3790 .add(MI.getOperand(2)); 3791 if (NeedClampOperand) 3792 I.addImm(0); // clamp bit for e64 encoding 3793 3794 TII->legalizeOperands(*I); 3795 3796 MI.eraseFromParent(); 3797 return BB; 3798 } 3799 case AMDGPU::DS_GWS_INIT: 3800 case AMDGPU::DS_GWS_SEMA_V: 3801 case AMDGPU::DS_GWS_SEMA_BR: 3802 case AMDGPU::DS_GWS_SEMA_P: 3803 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3804 case AMDGPU::DS_GWS_BARRIER: 3805 if (getSubtarget()->hasGWSAutoReplay()) 3806 return BB; 3807 return emitGWSMemViolTestLoop(MI, BB); 3808 default: 3809 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3810 } 3811 } 3812 3813 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3814 return isTypeLegal(VT.getScalarType()); 3815 } 3816 3817 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3818 // This currently forces unfolding various combinations of fsub into fma with 3819 // free fneg'd operands. As long as we have fast FMA (controlled by 3820 // isFMAFasterThanFMulAndFAdd), we should perform these. 3821 3822 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3823 // most of these combines appear to be cycle neutral but save on instruction 3824 // count / code size. 3825 return true; 3826 } 3827 3828 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3829 EVT VT) const { 3830 if (!VT.isVector()) { 3831 return MVT::i1; 3832 } 3833 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3834 } 3835 3836 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3837 // TODO: Should i16 be used always if legal? For now it would force VALU 3838 // shifts. 3839 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3840 } 3841 3842 // Answering this is somewhat tricky and depends on the specific device which 3843 // have different rates for fma or all f64 operations. 3844 // 3845 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3846 // regardless of which device (although the number of cycles differs between 3847 // devices), so it is always profitable for f64. 3848 // 3849 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3850 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3851 // which we can always do even without fused FP ops since it returns the same 3852 // result as the separate operations and since it is always full 3853 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3854 // however does not support denormals, so we do report fma as faster if we have 3855 // a fast fma device and require denormals. 3856 // 3857 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3858 VT = VT.getScalarType(); 3859 3860 switch (VT.getSimpleVT().SimpleTy) { 3861 case MVT::f32: { 3862 // This is as fast on some subtargets. However, we always have full rate f32 3863 // mad available which returns the same result as the separate operations 3864 // which we should prefer over fma. We can't use this if we want to support 3865 // denormals, so only report this in these cases. 3866 if (Subtarget->hasFP32Denormals()) 3867 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3868 3869 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3870 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3871 } 3872 case MVT::f64: 3873 return true; 3874 case MVT::f16: 3875 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3876 default: 3877 break; 3878 } 3879 3880 return false; 3881 } 3882 3883 //===----------------------------------------------------------------------===// 3884 // Custom DAG Lowering Operations 3885 //===----------------------------------------------------------------------===// 3886 3887 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3888 // wider vector type is legal. 3889 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3890 SelectionDAG &DAG) const { 3891 unsigned Opc = Op.getOpcode(); 3892 EVT VT = Op.getValueType(); 3893 assert(VT == MVT::v4f16); 3894 3895 SDValue Lo, Hi; 3896 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3897 3898 SDLoc SL(Op); 3899 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3900 Op->getFlags()); 3901 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3902 Op->getFlags()); 3903 3904 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3905 } 3906 3907 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3908 // wider vector type is legal. 3909 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3910 SelectionDAG &DAG) const { 3911 unsigned Opc = Op.getOpcode(); 3912 EVT VT = Op.getValueType(); 3913 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3914 3915 SDValue Lo0, Hi0; 3916 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3917 SDValue Lo1, Hi1; 3918 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3919 3920 SDLoc SL(Op); 3921 3922 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3923 Op->getFlags()); 3924 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3925 Op->getFlags()); 3926 3927 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3928 } 3929 3930 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3931 switch (Op.getOpcode()) { 3932 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3933 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3934 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 3935 case ISD::LOAD: { 3936 SDValue Result = LowerLOAD(Op, DAG); 3937 assert((!Result.getNode() || 3938 Result.getNode()->getNumValues() == 2) && 3939 "Load should return a value and a chain"); 3940 return Result; 3941 } 3942 3943 case ISD::FSIN: 3944 case ISD::FCOS: 3945 return LowerTrig(Op, DAG); 3946 case ISD::SELECT: return LowerSELECT(Op, DAG); 3947 case ISD::FDIV: return LowerFDIV(Op, DAG); 3948 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3949 case ISD::STORE: return LowerSTORE(Op, DAG); 3950 case ISD::GlobalAddress: { 3951 MachineFunction &MF = DAG.getMachineFunction(); 3952 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3953 return LowerGlobalAddress(MFI, Op, DAG); 3954 } 3955 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3956 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3957 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3958 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3959 case ISD::INSERT_VECTOR_ELT: 3960 return lowerINSERT_VECTOR_ELT(Op, DAG); 3961 case ISD::EXTRACT_VECTOR_ELT: 3962 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3963 case ISD::VECTOR_SHUFFLE: 3964 return lowerVECTOR_SHUFFLE(Op, DAG); 3965 case ISD::BUILD_VECTOR: 3966 return lowerBUILD_VECTOR(Op, DAG); 3967 case ISD::FP_ROUND: 3968 return lowerFP_ROUND(Op, DAG); 3969 case ISD::TRAP: 3970 return lowerTRAP(Op, DAG); 3971 case ISD::DEBUGTRAP: 3972 return lowerDEBUGTRAP(Op, DAG); 3973 case ISD::FABS: 3974 case ISD::FNEG: 3975 case ISD::FCANONICALIZE: 3976 return splitUnaryVectorOp(Op, DAG); 3977 case ISD::FMINNUM: 3978 case ISD::FMAXNUM: 3979 return lowerFMINNUM_FMAXNUM(Op, DAG); 3980 case ISD::SHL: 3981 case ISD::SRA: 3982 case ISD::SRL: 3983 case ISD::ADD: 3984 case ISD::SUB: 3985 case ISD::MUL: 3986 case ISD::SMIN: 3987 case ISD::SMAX: 3988 case ISD::UMIN: 3989 case ISD::UMAX: 3990 case ISD::FADD: 3991 case ISD::FMUL: 3992 case ISD::FMINNUM_IEEE: 3993 case ISD::FMAXNUM_IEEE: 3994 return splitBinaryVectorOp(Op, DAG); 3995 } 3996 return SDValue(); 3997 } 3998 3999 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4000 const SDLoc &DL, 4001 SelectionDAG &DAG, bool Unpacked) { 4002 if (!LoadVT.isVector()) 4003 return Result; 4004 4005 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4006 // Truncate to v2i16/v4i16. 4007 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4008 4009 // Workaround legalizer not scalarizing truncate after vector op 4010 // legalization byt not creating intermediate vector trunc. 4011 SmallVector<SDValue, 4> Elts; 4012 DAG.ExtractVectorElements(Result, Elts); 4013 for (SDValue &Elt : Elts) 4014 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4015 4016 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4017 4018 // Bitcast to original type (v2f16/v4f16). 4019 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4020 } 4021 4022 // Cast back to the original packed type. 4023 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4024 } 4025 4026 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4027 MemSDNode *M, 4028 SelectionDAG &DAG, 4029 ArrayRef<SDValue> Ops, 4030 bool IsIntrinsic) const { 4031 SDLoc DL(M); 4032 4033 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4034 EVT LoadVT = M->getValueType(0); 4035 4036 EVT EquivLoadVT = LoadVT; 4037 if (Unpacked && LoadVT.isVector()) { 4038 EquivLoadVT = LoadVT.isVector() ? 4039 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4040 LoadVT.getVectorNumElements()) : LoadVT; 4041 } 4042 4043 // Change from v4f16/v2f16 to EquivLoadVT. 4044 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4045 4046 SDValue Load 4047 = DAG.getMemIntrinsicNode( 4048 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4049 VTList, Ops, M->getMemoryVT(), 4050 M->getMemOperand()); 4051 if (!Unpacked) // Just adjusted the opcode. 4052 return Load; 4053 4054 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4055 4056 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4057 } 4058 4059 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4060 SDNode *N, SelectionDAG &DAG) { 4061 EVT VT = N->getValueType(0); 4062 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4063 int CondCode = CD->getSExtValue(); 4064 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4065 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4066 return DAG.getUNDEF(VT); 4067 4068 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4069 4070 SDValue LHS = N->getOperand(1); 4071 SDValue RHS = N->getOperand(2); 4072 4073 SDLoc DL(N); 4074 4075 EVT CmpVT = LHS.getValueType(); 4076 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4077 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4078 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4079 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4080 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4081 } 4082 4083 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4084 4085 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4086 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4087 4088 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4089 DAG.getCondCode(CCOpcode)); 4090 if (VT.bitsEq(CCVT)) 4091 return SetCC; 4092 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4093 } 4094 4095 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4096 SDNode *N, SelectionDAG &DAG) { 4097 EVT VT = N->getValueType(0); 4098 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4099 4100 int CondCode = CD->getSExtValue(); 4101 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4102 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4103 return DAG.getUNDEF(VT); 4104 } 4105 4106 SDValue Src0 = N->getOperand(1); 4107 SDValue Src1 = N->getOperand(2); 4108 EVT CmpVT = Src0.getValueType(); 4109 SDLoc SL(N); 4110 4111 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4112 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4113 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4114 } 4115 4116 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4117 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4118 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4119 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4120 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4121 Src1, DAG.getCondCode(CCOpcode)); 4122 if (VT.bitsEq(CCVT)) 4123 return SetCC; 4124 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4125 } 4126 4127 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4128 SmallVectorImpl<SDValue> &Results, 4129 SelectionDAG &DAG) const { 4130 switch (N->getOpcode()) { 4131 case ISD::INSERT_VECTOR_ELT: { 4132 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4133 Results.push_back(Res); 4134 return; 4135 } 4136 case ISD::EXTRACT_VECTOR_ELT: { 4137 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4138 Results.push_back(Res); 4139 return; 4140 } 4141 case ISD::INTRINSIC_WO_CHAIN: { 4142 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4143 switch (IID) { 4144 case Intrinsic::amdgcn_cvt_pkrtz: { 4145 SDValue Src0 = N->getOperand(1); 4146 SDValue Src1 = N->getOperand(2); 4147 SDLoc SL(N); 4148 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4149 Src0, Src1); 4150 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4151 return; 4152 } 4153 case Intrinsic::amdgcn_cvt_pknorm_i16: 4154 case Intrinsic::amdgcn_cvt_pknorm_u16: 4155 case Intrinsic::amdgcn_cvt_pk_i16: 4156 case Intrinsic::amdgcn_cvt_pk_u16: { 4157 SDValue Src0 = N->getOperand(1); 4158 SDValue Src1 = N->getOperand(2); 4159 SDLoc SL(N); 4160 unsigned Opcode; 4161 4162 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4163 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4164 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4165 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4166 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4167 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4168 else 4169 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4170 4171 EVT VT = N->getValueType(0); 4172 if (isTypeLegal(VT)) 4173 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4174 else { 4175 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4176 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4177 } 4178 return; 4179 } 4180 } 4181 break; 4182 } 4183 case ISD::INTRINSIC_W_CHAIN: { 4184 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4185 Results.push_back(Res); 4186 Results.push_back(Res.getValue(1)); 4187 return; 4188 } 4189 4190 break; 4191 } 4192 case ISD::SELECT: { 4193 SDLoc SL(N); 4194 EVT VT = N->getValueType(0); 4195 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4196 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4197 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4198 4199 EVT SelectVT = NewVT; 4200 if (NewVT.bitsLT(MVT::i32)) { 4201 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4202 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4203 SelectVT = MVT::i32; 4204 } 4205 4206 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4207 N->getOperand(0), LHS, RHS); 4208 4209 if (NewVT != SelectVT) 4210 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4211 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4212 return; 4213 } 4214 case ISD::FNEG: { 4215 if (N->getValueType(0) != MVT::v2f16) 4216 break; 4217 4218 SDLoc SL(N); 4219 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4220 4221 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4222 BC, 4223 DAG.getConstant(0x80008000, SL, MVT::i32)); 4224 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4225 return; 4226 } 4227 case ISD::FABS: { 4228 if (N->getValueType(0) != MVT::v2f16) 4229 break; 4230 4231 SDLoc SL(N); 4232 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4233 4234 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4235 BC, 4236 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4237 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4238 return; 4239 } 4240 default: 4241 break; 4242 } 4243 } 4244 4245 /// Helper function for LowerBRCOND 4246 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4247 4248 SDNode *Parent = Value.getNode(); 4249 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4250 I != E; ++I) { 4251 4252 if (I.getUse().get() != Value) 4253 continue; 4254 4255 if (I->getOpcode() == Opcode) 4256 return *I; 4257 } 4258 return nullptr; 4259 } 4260 4261 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4262 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4263 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4264 case Intrinsic::amdgcn_if: 4265 return AMDGPUISD::IF; 4266 case Intrinsic::amdgcn_else: 4267 return AMDGPUISD::ELSE; 4268 case Intrinsic::amdgcn_loop: 4269 return AMDGPUISD::LOOP; 4270 case Intrinsic::amdgcn_end_cf: 4271 llvm_unreachable("should not occur"); 4272 default: 4273 return 0; 4274 } 4275 } 4276 4277 // break, if_break, else_break are all only used as inputs to loop, not 4278 // directly as branch conditions. 4279 return 0; 4280 } 4281 4282 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4283 const Triple &TT = getTargetMachine().getTargetTriple(); 4284 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4285 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4286 AMDGPU::shouldEmitConstantsToTextSection(TT); 4287 } 4288 4289 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4290 // FIXME: Either avoid relying on address space here or change the default 4291 // address space for functions to avoid the explicit check. 4292 return (GV->getValueType()->isFunctionTy() || 4293 GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4294 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4295 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4296 !shouldEmitFixup(GV) && 4297 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4298 } 4299 4300 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4301 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4302 } 4303 4304 /// This transforms the control flow intrinsics to get the branch destination as 4305 /// last parameter, also switches branch target with BR if the need arise 4306 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4307 SelectionDAG &DAG) const { 4308 SDLoc DL(BRCOND); 4309 4310 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4311 SDValue Target = BRCOND.getOperand(2); 4312 SDNode *BR = nullptr; 4313 SDNode *SetCC = nullptr; 4314 4315 if (Intr->getOpcode() == ISD::SETCC) { 4316 // As long as we negate the condition everything is fine 4317 SetCC = Intr; 4318 Intr = SetCC->getOperand(0).getNode(); 4319 4320 } else { 4321 // Get the target from BR if we don't negate the condition 4322 BR = findUser(BRCOND, ISD::BR); 4323 Target = BR->getOperand(1); 4324 } 4325 4326 // FIXME: This changes the types of the intrinsics instead of introducing new 4327 // nodes with the correct types. 4328 // e.g. llvm.amdgcn.loop 4329 4330 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4331 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4332 4333 unsigned CFNode = isCFIntrinsic(Intr); 4334 if (CFNode == 0) { 4335 // This is a uniform branch so we don't need to legalize. 4336 return BRCOND; 4337 } 4338 4339 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4340 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4341 4342 assert(!SetCC || 4343 (SetCC->getConstantOperandVal(1) == 1 && 4344 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4345 ISD::SETNE)); 4346 4347 // operands of the new intrinsic call 4348 SmallVector<SDValue, 4> Ops; 4349 if (HaveChain) 4350 Ops.push_back(BRCOND.getOperand(0)); 4351 4352 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4353 Ops.push_back(Target); 4354 4355 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4356 4357 // build the new intrinsic call 4358 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4359 4360 if (!HaveChain) { 4361 SDValue Ops[] = { 4362 SDValue(Result, 0), 4363 BRCOND.getOperand(0) 4364 }; 4365 4366 Result = DAG.getMergeValues(Ops, DL).getNode(); 4367 } 4368 4369 if (BR) { 4370 // Give the branch instruction our target 4371 SDValue Ops[] = { 4372 BR->getOperand(0), 4373 BRCOND.getOperand(2) 4374 }; 4375 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4376 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4377 BR = NewBR.getNode(); 4378 } 4379 4380 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4381 4382 // Copy the intrinsic results to registers 4383 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4384 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4385 if (!CopyToReg) 4386 continue; 4387 4388 Chain = DAG.getCopyToReg( 4389 Chain, DL, 4390 CopyToReg->getOperand(1), 4391 SDValue(Result, i - 1), 4392 SDValue()); 4393 4394 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4395 } 4396 4397 // Remove the old intrinsic from the chain 4398 DAG.ReplaceAllUsesOfValueWith( 4399 SDValue(Intr, Intr->getNumValues() - 1), 4400 Intr->getOperand(0)); 4401 4402 return Chain; 4403 } 4404 4405 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4406 SelectionDAG &DAG) const { 4407 MVT VT = Op.getSimpleValueType(); 4408 SDLoc DL(Op); 4409 // Checking the depth 4410 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4411 return DAG.getConstant(0, DL, VT); 4412 4413 MachineFunction &MF = DAG.getMachineFunction(); 4414 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4415 // Check for kernel and shader functions 4416 if (Info->isEntryFunction()) 4417 return DAG.getConstant(0, DL, VT); 4418 4419 MachineFrameInfo &MFI = MF.getFrameInfo(); 4420 // There is a call to @llvm.returnaddress in this function 4421 MFI.setReturnAddressIsTaken(true); 4422 4423 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4424 // Get the return address reg and mark it as an implicit live-in 4425 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4426 4427 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4428 } 4429 4430 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4431 SDValue Op, 4432 const SDLoc &DL, 4433 EVT VT) const { 4434 return Op.getValueType().bitsLE(VT) ? 4435 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4436 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4437 } 4438 4439 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4440 assert(Op.getValueType() == MVT::f16 && 4441 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4442 4443 SDValue Src = Op.getOperand(0); 4444 EVT SrcVT = Src.getValueType(); 4445 if (SrcVT != MVT::f64) 4446 return Op; 4447 4448 SDLoc DL(Op); 4449 4450 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4451 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4452 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4453 } 4454 4455 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4456 SelectionDAG &DAG) const { 4457 EVT VT = Op.getValueType(); 4458 const MachineFunction &MF = DAG.getMachineFunction(); 4459 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4460 bool IsIEEEMode = Info->getMode().IEEE; 4461 4462 // FIXME: Assert during eslection that this is only selected for 4463 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4464 // mode functions, but this happens to be OK since it's only done in cases 4465 // where there is known no sNaN. 4466 if (IsIEEEMode) 4467 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4468 4469 if (VT == MVT::v4f16) 4470 return splitBinaryVectorOp(Op, DAG); 4471 return Op; 4472 } 4473 4474 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4475 SDLoc SL(Op); 4476 SDValue Chain = Op.getOperand(0); 4477 4478 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4479 !Subtarget->isTrapHandlerEnabled()) 4480 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4481 4482 MachineFunction &MF = DAG.getMachineFunction(); 4483 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4484 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4485 assert(UserSGPR != AMDGPU::NoRegister); 4486 SDValue QueuePtr = CreateLiveInRegister( 4487 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4488 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4489 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4490 QueuePtr, SDValue()); 4491 SDValue Ops[] = { 4492 ToReg, 4493 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4494 SGPR01, 4495 ToReg.getValue(1) 4496 }; 4497 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4498 } 4499 4500 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4501 SDLoc SL(Op); 4502 SDValue Chain = Op.getOperand(0); 4503 MachineFunction &MF = DAG.getMachineFunction(); 4504 4505 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4506 !Subtarget->isTrapHandlerEnabled()) { 4507 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4508 "debugtrap handler not supported", 4509 Op.getDebugLoc(), 4510 DS_Warning); 4511 LLVMContext &Ctx = MF.getFunction().getContext(); 4512 Ctx.diagnose(NoTrap); 4513 return Chain; 4514 } 4515 4516 SDValue Ops[] = { 4517 Chain, 4518 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4519 }; 4520 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4521 } 4522 4523 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4524 SelectionDAG &DAG) const { 4525 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4526 if (Subtarget->hasApertureRegs()) { 4527 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4528 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4529 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4530 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4531 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4532 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4533 unsigned Encoding = 4534 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4535 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4536 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4537 4538 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4539 SDValue ApertureReg = SDValue( 4540 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4541 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4542 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4543 } 4544 4545 MachineFunction &MF = DAG.getMachineFunction(); 4546 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4547 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4548 assert(UserSGPR != AMDGPU::NoRegister); 4549 4550 SDValue QueuePtr = CreateLiveInRegister( 4551 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4552 4553 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4554 // private_segment_aperture_base_hi. 4555 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4556 4557 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4558 4559 // TODO: Use custom target PseudoSourceValue. 4560 // TODO: We should use the value from the IR intrinsic call, but it might not 4561 // be available and how do we get it? 4562 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4563 AMDGPUAS::CONSTANT_ADDRESS)); 4564 4565 MachinePointerInfo PtrInfo(V, StructOffset); 4566 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4567 MinAlign(64, StructOffset), 4568 MachineMemOperand::MODereferenceable | 4569 MachineMemOperand::MOInvariant); 4570 } 4571 4572 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4573 SelectionDAG &DAG) const { 4574 SDLoc SL(Op); 4575 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4576 4577 SDValue Src = ASC->getOperand(0); 4578 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4579 4580 const AMDGPUTargetMachine &TM = 4581 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4582 4583 // flat -> local/private 4584 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4585 unsigned DestAS = ASC->getDestAddressSpace(); 4586 4587 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4588 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4589 unsigned NullVal = TM.getNullPointerValue(DestAS); 4590 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4591 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4592 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4593 4594 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4595 NonNull, Ptr, SegmentNullPtr); 4596 } 4597 } 4598 4599 // local/private -> flat 4600 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4601 unsigned SrcAS = ASC->getSrcAddressSpace(); 4602 4603 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4604 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4605 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4606 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4607 4608 SDValue NonNull 4609 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4610 4611 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4612 SDValue CvtPtr 4613 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4614 4615 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4616 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4617 FlatNullPtr); 4618 } 4619 } 4620 4621 // global <-> flat are no-ops and never emitted. 4622 4623 const MachineFunction &MF = DAG.getMachineFunction(); 4624 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4625 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4626 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4627 4628 return DAG.getUNDEF(ASC->getValueType(0)); 4629 } 4630 4631 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4632 SelectionDAG &DAG) const { 4633 SDValue Vec = Op.getOperand(0); 4634 SDValue InsVal = Op.getOperand(1); 4635 SDValue Idx = Op.getOperand(2); 4636 EVT VecVT = Vec.getValueType(); 4637 EVT EltVT = VecVT.getVectorElementType(); 4638 unsigned VecSize = VecVT.getSizeInBits(); 4639 unsigned EltSize = EltVT.getSizeInBits(); 4640 4641 4642 assert(VecSize <= 64); 4643 4644 unsigned NumElts = VecVT.getVectorNumElements(); 4645 SDLoc SL(Op); 4646 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4647 4648 if (NumElts == 4 && EltSize == 16 && KIdx) { 4649 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4650 4651 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4652 DAG.getConstant(0, SL, MVT::i32)); 4653 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4654 DAG.getConstant(1, SL, MVT::i32)); 4655 4656 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4657 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4658 4659 unsigned Idx = KIdx->getZExtValue(); 4660 bool InsertLo = Idx < 2; 4661 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4662 InsertLo ? LoVec : HiVec, 4663 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4664 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4665 4666 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4667 4668 SDValue Concat = InsertLo ? 4669 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4670 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4671 4672 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4673 } 4674 4675 if (isa<ConstantSDNode>(Idx)) 4676 return SDValue(); 4677 4678 MVT IntVT = MVT::getIntegerVT(VecSize); 4679 4680 // Avoid stack access for dynamic indexing. 4681 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4682 4683 // Create a congruent vector with the target value in each element so that 4684 // the required element can be masked and ORed into the target vector. 4685 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4686 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4687 4688 assert(isPowerOf2_32(EltSize)); 4689 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4690 4691 // Convert vector index to bit-index. 4692 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4693 4694 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4695 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4696 DAG.getConstant(0xffff, SL, IntVT), 4697 ScaledIdx); 4698 4699 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4700 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4701 DAG.getNOT(SL, BFM, IntVT), BCVec); 4702 4703 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4704 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4705 } 4706 4707 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4708 SelectionDAG &DAG) const { 4709 SDLoc SL(Op); 4710 4711 EVT ResultVT = Op.getValueType(); 4712 SDValue Vec = Op.getOperand(0); 4713 SDValue Idx = Op.getOperand(1); 4714 EVT VecVT = Vec.getValueType(); 4715 unsigned VecSize = VecVT.getSizeInBits(); 4716 EVT EltVT = VecVT.getVectorElementType(); 4717 assert(VecSize <= 64); 4718 4719 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4720 4721 // Make sure we do any optimizations that will make it easier to fold 4722 // source modifiers before obscuring it with bit operations. 4723 4724 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4725 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4726 return Combined; 4727 4728 unsigned EltSize = EltVT.getSizeInBits(); 4729 assert(isPowerOf2_32(EltSize)); 4730 4731 MVT IntVT = MVT::getIntegerVT(VecSize); 4732 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4733 4734 // Convert vector index to bit-index (* EltSize) 4735 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4736 4737 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4738 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4739 4740 if (ResultVT == MVT::f16) { 4741 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4742 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4743 } 4744 4745 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4746 } 4747 4748 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4749 assert(Elt % 2 == 0); 4750 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4751 } 4752 4753 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4754 SelectionDAG &DAG) const { 4755 SDLoc SL(Op); 4756 EVT ResultVT = Op.getValueType(); 4757 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4758 4759 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4760 EVT EltVT = PackVT.getVectorElementType(); 4761 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4762 4763 // vector_shuffle <0,1,6,7> lhs, rhs 4764 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4765 // 4766 // vector_shuffle <6,7,2,3> lhs, rhs 4767 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4768 // 4769 // vector_shuffle <6,7,0,1> lhs, rhs 4770 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4771 4772 // Avoid scalarizing when both halves are reading from consecutive elements. 4773 SmallVector<SDValue, 4> Pieces; 4774 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4775 if (elementPairIsContiguous(SVN->getMask(), I)) { 4776 const int Idx = SVN->getMaskElt(I); 4777 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4778 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4779 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4780 PackVT, SVN->getOperand(VecIdx), 4781 DAG.getConstant(EltIdx, SL, MVT::i32)); 4782 Pieces.push_back(SubVec); 4783 } else { 4784 const int Idx0 = SVN->getMaskElt(I); 4785 const int Idx1 = SVN->getMaskElt(I + 1); 4786 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4787 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4788 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4789 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4790 4791 SDValue Vec0 = SVN->getOperand(VecIdx0); 4792 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4793 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4794 4795 SDValue Vec1 = SVN->getOperand(VecIdx1); 4796 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4797 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4798 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4799 } 4800 } 4801 4802 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4803 } 4804 4805 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4806 SelectionDAG &DAG) const { 4807 SDLoc SL(Op); 4808 EVT VT = Op.getValueType(); 4809 4810 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4811 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4812 4813 // Turn into pair of packed build_vectors. 4814 // TODO: Special case for constants that can be materialized with s_mov_b64. 4815 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4816 { Op.getOperand(0), Op.getOperand(1) }); 4817 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4818 { Op.getOperand(2), Op.getOperand(3) }); 4819 4820 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4821 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4822 4823 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4824 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4825 } 4826 4827 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4828 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4829 4830 SDValue Lo = Op.getOperand(0); 4831 SDValue Hi = Op.getOperand(1); 4832 4833 // Avoid adding defined bits with the zero_extend. 4834 if (Hi.isUndef()) { 4835 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4836 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4837 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4838 } 4839 4840 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4841 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4842 4843 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4844 DAG.getConstant(16, SL, MVT::i32)); 4845 if (Lo.isUndef()) 4846 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4847 4848 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4849 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4850 4851 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4852 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4853 } 4854 4855 bool 4856 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4857 // We can fold offsets for anything that doesn't require a GOT relocation. 4858 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4859 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4860 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4861 !shouldEmitGOTReloc(GA->getGlobal()); 4862 } 4863 4864 static SDValue 4865 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4866 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4867 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4868 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4869 // lowered to the following code sequence: 4870 // 4871 // For constant address space: 4872 // s_getpc_b64 s[0:1] 4873 // s_add_u32 s0, s0, $symbol 4874 // s_addc_u32 s1, s1, 0 4875 // 4876 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4877 // a fixup or relocation is emitted to replace $symbol with a literal 4878 // constant, which is a pc-relative offset from the encoding of the $symbol 4879 // operand to the global variable. 4880 // 4881 // For global address space: 4882 // s_getpc_b64 s[0:1] 4883 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4884 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4885 // 4886 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4887 // fixups or relocations are emitted to replace $symbol@*@lo and 4888 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4889 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4890 // operand to the global variable. 4891 // 4892 // What we want here is an offset from the value returned by s_getpc 4893 // (which is the address of the s_add_u32 instruction) to the global 4894 // variable, but since the encoding of $symbol starts 4 bytes after the start 4895 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4896 // small. This requires us to add 4 to the global variable offset in order to 4897 // compute the correct address. 4898 unsigned LoFlags = GAFlags; 4899 if (LoFlags == SIInstrInfo::MO_NONE) 4900 LoFlags = SIInstrInfo::MO_REL32; 4901 SDValue PtrLo = 4902 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags); 4903 SDValue PtrHi; 4904 if (GAFlags == SIInstrInfo::MO_NONE) { 4905 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 4906 } else { 4907 PtrHi = 4908 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 4909 } 4910 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4911 } 4912 4913 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4914 SDValue Op, 4915 SelectionDAG &DAG) const { 4916 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4917 const GlobalValue *GV = GSD->getGlobal(); 4918 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 4919 (!GV->hasExternalLinkage() || 4920 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4921 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 4922 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 4923 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 4924 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4925 4926 SDLoc DL(GSD); 4927 EVT PtrVT = Op.getValueType(); 4928 4929 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 4930 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 4931 SIInstrInfo::MO_ABS32_LO); 4932 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 4933 } 4934 4935 if (shouldEmitFixup(GV)) 4936 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 4937 else if (shouldEmitPCReloc(GV)) 4938 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 4939 SIInstrInfo::MO_REL32); 4940 4941 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 4942 SIInstrInfo::MO_GOTPCREL32); 4943 4944 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 4945 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 4946 const DataLayout &DataLayout = DAG.getDataLayout(); 4947 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 4948 MachinePointerInfo PtrInfo 4949 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 4950 4951 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 4952 MachineMemOperand::MODereferenceable | 4953 MachineMemOperand::MOInvariant); 4954 } 4955 4956 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 4957 const SDLoc &DL, SDValue V) const { 4958 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 4959 // the destination register. 4960 // 4961 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 4962 // so we will end up with redundant moves to m0. 4963 // 4964 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 4965 4966 // A Null SDValue creates a glue result. 4967 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 4968 V, Chain); 4969 return SDValue(M0, 0); 4970 } 4971 4972 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 4973 SDValue Op, 4974 MVT VT, 4975 unsigned Offset) const { 4976 SDLoc SL(Op); 4977 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 4978 DAG.getEntryNode(), Offset, 4, false); 4979 // The local size values will have the hi 16-bits as zero. 4980 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 4981 DAG.getValueType(VT)); 4982 } 4983 4984 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4985 EVT VT) { 4986 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4987 "non-hsa intrinsic with hsa target", 4988 DL.getDebugLoc()); 4989 DAG.getContext()->diagnose(BadIntrin); 4990 return DAG.getUNDEF(VT); 4991 } 4992 4993 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 4994 EVT VT) { 4995 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 4996 "intrinsic not supported on subtarget", 4997 DL.getDebugLoc()); 4998 DAG.getContext()->diagnose(BadIntrin); 4999 return DAG.getUNDEF(VT); 5000 } 5001 5002 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5003 ArrayRef<SDValue> Elts) { 5004 assert(!Elts.empty()); 5005 MVT Type; 5006 unsigned NumElts; 5007 5008 if (Elts.size() == 1) { 5009 Type = MVT::f32; 5010 NumElts = 1; 5011 } else if (Elts.size() == 2) { 5012 Type = MVT::v2f32; 5013 NumElts = 2; 5014 } else if (Elts.size() <= 4) { 5015 Type = MVT::v4f32; 5016 NumElts = 4; 5017 } else if (Elts.size() <= 8) { 5018 Type = MVT::v8f32; 5019 NumElts = 8; 5020 } else { 5021 assert(Elts.size() <= 16); 5022 Type = MVT::v16f32; 5023 NumElts = 16; 5024 } 5025 5026 SmallVector<SDValue, 16> VecElts(NumElts); 5027 for (unsigned i = 0; i < Elts.size(); ++i) { 5028 SDValue Elt = Elts[i]; 5029 if (Elt.getValueType() != MVT::f32) 5030 Elt = DAG.getBitcast(MVT::f32, Elt); 5031 VecElts[i] = Elt; 5032 } 5033 for (unsigned i = Elts.size(); i < NumElts; ++i) 5034 VecElts[i] = DAG.getUNDEF(MVT::f32); 5035 5036 if (NumElts == 1) 5037 return VecElts[0]; 5038 return DAG.getBuildVector(Type, DL, VecElts); 5039 } 5040 5041 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5042 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5043 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5044 5045 uint64_t Value = CachePolicyConst->getZExtValue(); 5046 SDLoc DL(CachePolicy); 5047 if (GLC) { 5048 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5049 Value &= ~(uint64_t)0x1; 5050 } 5051 if (SLC) { 5052 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5053 Value &= ~(uint64_t)0x2; 5054 } 5055 if (DLC) { 5056 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5057 Value &= ~(uint64_t)0x4; 5058 } 5059 5060 return Value == 0; 5061 } 5062 5063 // Re-construct the required return value for a image load intrinsic. 5064 // This is more complicated due to the optional use TexFailCtrl which means the required 5065 // return type is an aggregate 5066 static SDValue constructRetValue(SelectionDAG &DAG, 5067 MachineSDNode *Result, 5068 ArrayRef<EVT> ResultTypes, 5069 bool IsTexFail, bool Unpacked, bool IsD16, 5070 int DMaskPop, int NumVDataDwords, 5071 const SDLoc &DL, LLVMContext &Context) { 5072 // Determine the required return type. This is the same regardless of IsTexFail flag 5073 EVT ReqRetVT = ResultTypes[0]; 5074 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5075 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5076 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5077 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5078 : AdjEltVT 5079 : ReqRetVT; 5080 5081 // Extract data part of the result 5082 // Bitcast the result to the same type as the required return type 5083 int NumElts; 5084 if (IsD16 && !Unpacked) 5085 NumElts = NumVDataDwords << 1; 5086 else 5087 NumElts = NumVDataDwords; 5088 5089 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5090 : AdjEltVT; 5091 5092 // Special case for v6f16. Rather than add support for this, use v3i32 to 5093 // extract the data elements 5094 bool V6F16Special = false; 5095 if (NumElts == 6) { 5096 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5097 DMaskPop >>= 1; 5098 ReqRetNumElts >>= 1; 5099 V6F16Special = true; 5100 AdjVT = MVT::v2i32; 5101 } 5102 5103 SDValue N = SDValue(Result, 0); 5104 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5105 5106 // Iterate over the result 5107 SmallVector<SDValue, 4> BVElts; 5108 5109 if (CastVT.isVector()) { 5110 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5111 } else { 5112 BVElts.push_back(CastRes); 5113 } 5114 int ExtraElts = ReqRetNumElts - DMaskPop; 5115 while(ExtraElts--) 5116 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5117 5118 SDValue PreTFCRes; 5119 if (ReqRetNumElts > 1) { 5120 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5121 if (IsD16 && Unpacked) 5122 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5123 else 5124 PreTFCRes = NewVec; 5125 } else { 5126 PreTFCRes = BVElts[0]; 5127 } 5128 5129 if (V6F16Special) 5130 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5131 5132 if (!IsTexFail) { 5133 if (Result->getNumValues() > 1) 5134 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5135 else 5136 return PreTFCRes; 5137 } 5138 5139 // Extract the TexFail result and insert into aggregate return 5140 SmallVector<SDValue, 1> TFCElt; 5141 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5142 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5143 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5144 } 5145 5146 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5147 SDValue *LWE, bool &IsTexFail) { 5148 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5149 5150 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5151 if (Value) { 5152 IsTexFail = true; 5153 } 5154 5155 SDLoc DL(TexFailCtrlConst); 5156 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5157 Value &= ~(uint64_t)0x1; 5158 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5159 Value &= ~(uint64_t)0x2; 5160 5161 return Value == 0; 5162 } 5163 5164 SDValue SITargetLowering::lowerImage(SDValue Op, 5165 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5166 SelectionDAG &DAG) const { 5167 SDLoc DL(Op); 5168 MachineFunction &MF = DAG.getMachineFunction(); 5169 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5170 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5171 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5172 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5173 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5174 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5175 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5176 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5177 unsigned IntrOpcode = Intr->BaseOpcode; 5178 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5179 5180 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5181 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5182 bool IsD16 = false; 5183 bool IsA16 = false; 5184 SDValue VData; 5185 int NumVDataDwords; 5186 bool AdjustRetType = false; 5187 5188 unsigned AddrIdx; // Index of first address argument 5189 unsigned DMask; 5190 unsigned DMaskLanes = 0; 5191 5192 if (BaseOpcode->Atomic) { 5193 VData = Op.getOperand(2); 5194 5195 bool Is64Bit = VData.getValueType() == MVT::i64; 5196 if (BaseOpcode->AtomicX2) { 5197 SDValue VData2 = Op.getOperand(3); 5198 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5199 {VData, VData2}); 5200 if (Is64Bit) 5201 VData = DAG.getBitcast(MVT::v4i32, VData); 5202 5203 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5204 DMask = Is64Bit ? 0xf : 0x3; 5205 NumVDataDwords = Is64Bit ? 4 : 2; 5206 AddrIdx = 4; 5207 } else { 5208 DMask = Is64Bit ? 0x3 : 0x1; 5209 NumVDataDwords = Is64Bit ? 2 : 1; 5210 AddrIdx = 3; 5211 } 5212 } else { 5213 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5214 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5215 DMask = DMaskConst->getZExtValue(); 5216 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5217 5218 if (BaseOpcode->Store) { 5219 VData = Op.getOperand(2); 5220 5221 MVT StoreVT = VData.getSimpleValueType(); 5222 if (StoreVT.getScalarType() == MVT::f16) { 5223 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5224 return Op; // D16 is unsupported for this instruction 5225 5226 IsD16 = true; 5227 VData = handleD16VData(VData, DAG); 5228 } 5229 5230 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5231 } else { 5232 // Work out the num dwords based on the dmask popcount and underlying type 5233 // and whether packing is supported. 5234 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5235 if (LoadVT.getScalarType() == MVT::f16) { 5236 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5237 return Op; // D16 is unsupported for this instruction 5238 5239 IsD16 = true; 5240 } 5241 5242 // Confirm that the return type is large enough for the dmask specified 5243 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5244 (!LoadVT.isVector() && DMaskLanes > 1)) 5245 return Op; 5246 5247 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5248 NumVDataDwords = (DMaskLanes + 1) / 2; 5249 else 5250 NumVDataDwords = DMaskLanes; 5251 5252 AdjustRetType = true; 5253 } 5254 5255 AddrIdx = DMaskIdx + 1; 5256 } 5257 5258 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5259 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5260 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5261 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5262 NumCoords + NumLCM; 5263 unsigned NumMIVAddrs = NumVAddrs; 5264 5265 SmallVector<SDValue, 4> VAddrs; 5266 5267 // Optimize _L to _LZ when _L is zero 5268 if (LZMappingInfo) { 5269 if (auto ConstantLod = 5270 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5271 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5272 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5273 NumMIVAddrs--; // remove 'lod' 5274 } 5275 } 5276 } 5277 5278 // Optimize _mip away, when 'lod' is zero 5279 if (MIPMappingInfo) { 5280 if (auto ConstantLod = 5281 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5282 if (ConstantLod->isNullValue()) { 5283 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5284 NumMIVAddrs--; // remove 'lod' 5285 } 5286 } 5287 } 5288 5289 // Check for 16 bit addresses and pack if true. 5290 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5291 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5292 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5293 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5294 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5295 IsA16 = true; 5296 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5297 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5298 SDValue AddrLo, AddrHi; 5299 // Push back extra arguments. 5300 if (i < DimIdx) { 5301 AddrLo = Op.getOperand(i); 5302 } else { 5303 AddrLo = Op.getOperand(i); 5304 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5305 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5306 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5307 ((NumGradients / 2) % 2 == 1 && 5308 (i == DimIdx + (NumGradients / 2) - 1 || 5309 i == DimIdx + NumGradients - 1))) { 5310 AddrHi = DAG.getUNDEF(MVT::f16); 5311 } else { 5312 AddrHi = Op.getOperand(i + 1); 5313 i++; 5314 } 5315 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5316 {AddrLo, AddrHi}); 5317 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5318 } 5319 VAddrs.push_back(AddrLo); 5320 } 5321 } else { 5322 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5323 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5324 } 5325 5326 // If the register allocator cannot place the address registers contiguously 5327 // without introducing moves, then using the non-sequential address encoding 5328 // is always preferable, since it saves VALU instructions and is usually a 5329 // wash in terms of code size or even better. 5330 // 5331 // However, we currently have no way of hinting to the register allocator that 5332 // MIMG addresses should be placed contiguously when it is possible to do so, 5333 // so force non-NSA for the common 2-address case as a heuristic. 5334 // 5335 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5336 // allocation when possible. 5337 bool UseNSA = 5338 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5339 SDValue VAddr; 5340 if (!UseNSA) 5341 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5342 5343 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5344 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5345 unsigned CtrlIdx; // Index of texfailctrl argument 5346 SDValue Unorm; 5347 if (!BaseOpcode->Sampler) { 5348 Unorm = True; 5349 CtrlIdx = AddrIdx + NumVAddrs + 1; 5350 } else { 5351 auto UnormConst = 5352 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5353 5354 Unorm = UnormConst->getZExtValue() ? True : False; 5355 CtrlIdx = AddrIdx + NumVAddrs + 3; 5356 } 5357 5358 SDValue TFE; 5359 SDValue LWE; 5360 SDValue TexFail = Op.getOperand(CtrlIdx); 5361 bool IsTexFail = false; 5362 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5363 return Op; 5364 5365 if (IsTexFail) { 5366 if (!DMaskLanes) { 5367 // Expecting to get an error flag since TFC is on - and dmask is 0 5368 // Force dmask to be at least 1 otherwise the instruction will fail 5369 DMask = 0x1; 5370 DMaskLanes = 1; 5371 NumVDataDwords = 1; 5372 } 5373 NumVDataDwords += 1; 5374 AdjustRetType = true; 5375 } 5376 5377 // Has something earlier tagged that the return type needs adjusting 5378 // This happens if the instruction is a load or has set TexFailCtrl flags 5379 if (AdjustRetType) { 5380 // NumVDataDwords reflects the true number of dwords required in the return type 5381 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5382 // This is a no-op load. This can be eliminated 5383 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5384 if (isa<MemSDNode>(Op)) 5385 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5386 return Undef; 5387 } 5388 5389 EVT NewVT = NumVDataDwords > 1 ? 5390 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5391 : MVT::f32; 5392 5393 ResultTypes[0] = NewVT; 5394 if (ResultTypes.size() == 3) { 5395 // Original result was aggregate type used for TexFailCtrl results 5396 // The actual instruction returns as a vector type which has now been 5397 // created. Remove the aggregate result. 5398 ResultTypes.erase(&ResultTypes[1]); 5399 } 5400 } 5401 5402 SDValue GLC; 5403 SDValue SLC; 5404 SDValue DLC; 5405 if (BaseOpcode->Atomic) { 5406 GLC = True; // TODO no-return optimization 5407 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5408 IsGFX10 ? &DLC : nullptr)) 5409 return Op; 5410 } else { 5411 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5412 IsGFX10 ? &DLC : nullptr)) 5413 return Op; 5414 } 5415 5416 SmallVector<SDValue, 26> Ops; 5417 if (BaseOpcode->Store || BaseOpcode->Atomic) 5418 Ops.push_back(VData); // vdata 5419 if (UseNSA) { 5420 for (const SDValue &Addr : VAddrs) 5421 Ops.push_back(Addr); 5422 } else { 5423 Ops.push_back(VAddr); 5424 } 5425 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5426 if (BaseOpcode->Sampler) 5427 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5428 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5429 if (IsGFX10) 5430 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5431 Ops.push_back(Unorm); 5432 if (IsGFX10) 5433 Ops.push_back(DLC); 5434 Ops.push_back(GLC); 5435 Ops.push_back(SLC); 5436 Ops.push_back(IsA16 && // a16 or r128 5437 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5438 Ops.push_back(TFE); // tfe 5439 Ops.push_back(LWE); // lwe 5440 if (!IsGFX10) 5441 Ops.push_back(DimInfo->DA ? True : False); 5442 if (BaseOpcode->HasD16) 5443 Ops.push_back(IsD16 ? True : False); 5444 if (isa<MemSDNode>(Op)) 5445 Ops.push_back(Op.getOperand(0)); // chain 5446 5447 int NumVAddrDwords = 5448 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5449 int Opcode = -1; 5450 5451 if (IsGFX10) { 5452 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5453 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5454 : AMDGPU::MIMGEncGfx10Default, 5455 NumVDataDwords, NumVAddrDwords); 5456 } else { 5457 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5458 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5459 NumVDataDwords, NumVAddrDwords); 5460 if (Opcode == -1) 5461 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5462 NumVDataDwords, NumVAddrDwords); 5463 } 5464 assert(Opcode != -1); 5465 5466 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5467 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5468 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5469 DAG.setNodeMemRefs(NewNode, {MemRef}); 5470 } 5471 5472 if (BaseOpcode->AtomicX2) { 5473 SmallVector<SDValue, 1> Elt; 5474 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5475 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5476 } else if (!BaseOpcode->Store) { 5477 return constructRetValue(DAG, NewNode, 5478 OrigResultTypes, IsTexFail, 5479 Subtarget->hasUnpackedD16VMem(), IsD16, 5480 DMaskLanes, NumVDataDwords, DL, 5481 *DAG.getContext()); 5482 } 5483 5484 return SDValue(NewNode, 0); 5485 } 5486 5487 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5488 SDValue Offset, SDValue GLC, SDValue DLC, 5489 SelectionDAG &DAG) const { 5490 MachineFunction &MF = DAG.getMachineFunction(); 5491 MachineMemOperand *MMO = MF.getMachineMemOperand( 5492 MachinePointerInfo(), 5493 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5494 MachineMemOperand::MOInvariant, 5495 VT.getStoreSize(), VT.getStoreSize()); 5496 5497 if (!Offset->isDivergent()) { 5498 SDValue Ops[] = { 5499 Rsrc, 5500 Offset, // Offset 5501 GLC, 5502 DLC, 5503 }; 5504 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5505 DAG.getVTList(VT), Ops, VT, MMO); 5506 } 5507 5508 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5509 // assume that the buffer is unswizzled. 5510 SmallVector<SDValue, 4> Loads; 5511 unsigned NumLoads = 1; 5512 MVT LoadVT = VT.getSimpleVT(); 5513 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5514 assert((LoadVT.getScalarType() == MVT::i32 || 5515 LoadVT.getScalarType() == MVT::f32) && 5516 isPowerOf2_32(NumElts)); 5517 5518 if (NumElts == 8 || NumElts == 16) { 5519 NumLoads = NumElts == 16 ? 4 : 2; 5520 LoadVT = MVT::v4i32; 5521 } 5522 5523 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5524 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5525 SDValue Ops[] = { 5526 DAG.getEntryNode(), // Chain 5527 Rsrc, // rsrc 5528 DAG.getConstant(0, DL, MVT::i32), // vindex 5529 {}, // voffset 5530 {}, // soffset 5531 {}, // offset 5532 DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5533 DAG.getConstant(0, DL, MVT::i1), // idxen 5534 }; 5535 5536 // Use the alignment to ensure that the required offsets will fit into the 5537 // immediate offsets. 5538 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5539 5540 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5541 for (unsigned i = 0; i < NumLoads; ++i) { 5542 Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32); 5543 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, 5544 Ops, LoadVT, MMO)); 5545 } 5546 5547 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5548 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5549 5550 return Loads[0]; 5551 } 5552 5553 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5554 SelectionDAG &DAG) const { 5555 MachineFunction &MF = DAG.getMachineFunction(); 5556 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5557 5558 EVT VT = Op.getValueType(); 5559 SDLoc DL(Op); 5560 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5561 5562 // TODO: Should this propagate fast-math-flags? 5563 5564 switch (IntrinsicID) { 5565 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5566 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5567 return emitNonHSAIntrinsicError(DAG, DL, VT); 5568 return getPreloadedValue(DAG, *MFI, VT, 5569 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5570 } 5571 case Intrinsic::amdgcn_dispatch_ptr: 5572 case Intrinsic::amdgcn_queue_ptr: { 5573 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5574 DiagnosticInfoUnsupported BadIntrin( 5575 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5576 DL.getDebugLoc()); 5577 DAG.getContext()->diagnose(BadIntrin); 5578 return DAG.getUNDEF(VT); 5579 } 5580 5581 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5582 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5583 return getPreloadedValue(DAG, *MFI, VT, RegID); 5584 } 5585 case Intrinsic::amdgcn_implicitarg_ptr: { 5586 if (MFI->isEntryFunction()) 5587 return getImplicitArgPtr(DAG, DL); 5588 return getPreloadedValue(DAG, *MFI, VT, 5589 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5590 } 5591 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5592 return getPreloadedValue(DAG, *MFI, VT, 5593 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5594 } 5595 case Intrinsic::amdgcn_dispatch_id: { 5596 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5597 } 5598 case Intrinsic::amdgcn_rcp: 5599 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5600 case Intrinsic::amdgcn_rsq: 5601 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5602 case Intrinsic::amdgcn_rsq_legacy: 5603 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5604 return emitRemovedIntrinsicError(DAG, DL, VT); 5605 5606 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5607 case Intrinsic::amdgcn_rcp_legacy: 5608 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5609 return emitRemovedIntrinsicError(DAG, DL, VT); 5610 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5611 case Intrinsic::amdgcn_rsq_clamp: { 5612 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5613 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5614 5615 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5616 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5617 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5618 5619 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5620 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5621 DAG.getConstantFP(Max, DL, VT)); 5622 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5623 DAG.getConstantFP(Min, DL, VT)); 5624 } 5625 case Intrinsic::r600_read_ngroups_x: 5626 if (Subtarget->isAmdHsaOS()) 5627 return emitNonHSAIntrinsicError(DAG, DL, VT); 5628 5629 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5630 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5631 case Intrinsic::r600_read_ngroups_y: 5632 if (Subtarget->isAmdHsaOS()) 5633 return emitNonHSAIntrinsicError(DAG, DL, VT); 5634 5635 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5636 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5637 case Intrinsic::r600_read_ngroups_z: 5638 if (Subtarget->isAmdHsaOS()) 5639 return emitNonHSAIntrinsicError(DAG, DL, VT); 5640 5641 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5642 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5643 case Intrinsic::r600_read_global_size_x: 5644 if (Subtarget->isAmdHsaOS()) 5645 return emitNonHSAIntrinsicError(DAG, DL, VT); 5646 5647 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5648 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5649 case Intrinsic::r600_read_global_size_y: 5650 if (Subtarget->isAmdHsaOS()) 5651 return emitNonHSAIntrinsicError(DAG, DL, VT); 5652 5653 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5654 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5655 case Intrinsic::r600_read_global_size_z: 5656 if (Subtarget->isAmdHsaOS()) 5657 return emitNonHSAIntrinsicError(DAG, DL, VT); 5658 5659 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5660 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5661 case Intrinsic::r600_read_local_size_x: 5662 if (Subtarget->isAmdHsaOS()) 5663 return emitNonHSAIntrinsicError(DAG, DL, VT); 5664 5665 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5666 SI::KernelInputOffsets::LOCAL_SIZE_X); 5667 case Intrinsic::r600_read_local_size_y: 5668 if (Subtarget->isAmdHsaOS()) 5669 return emitNonHSAIntrinsicError(DAG, DL, VT); 5670 5671 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5672 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5673 case Intrinsic::r600_read_local_size_z: 5674 if (Subtarget->isAmdHsaOS()) 5675 return emitNonHSAIntrinsicError(DAG, DL, VT); 5676 5677 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5678 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5679 case Intrinsic::amdgcn_workgroup_id_x: 5680 case Intrinsic::r600_read_tgid_x: 5681 return getPreloadedValue(DAG, *MFI, VT, 5682 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5683 case Intrinsic::amdgcn_workgroup_id_y: 5684 case Intrinsic::r600_read_tgid_y: 5685 return getPreloadedValue(DAG, *MFI, VT, 5686 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5687 case Intrinsic::amdgcn_workgroup_id_z: 5688 case Intrinsic::r600_read_tgid_z: 5689 return getPreloadedValue(DAG, *MFI, VT, 5690 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5691 case Intrinsic::amdgcn_workitem_id_x: 5692 case Intrinsic::r600_read_tidig_x: 5693 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5694 SDLoc(DAG.getEntryNode()), 5695 MFI->getArgInfo().WorkItemIDX); 5696 case Intrinsic::amdgcn_workitem_id_y: 5697 case Intrinsic::r600_read_tidig_y: 5698 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5699 SDLoc(DAG.getEntryNode()), 5700 MFI->getArgInfo().WorkItemIDY); 5701 case Intrinsic::amdgcn_workitem_id_z: 5702 case Intrinsic::r600_read_tidig_z: 5703 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5704 SDLoc(DAG.getEntryNode()), 5705 MFI->getArgInfo().WorkItemIDZ); 5706 case Intrinsic::amdgcn_wavefrontsize: 5707 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5708 SDLoc(Op), MVT::i32); 5709 case Intrinsic::amdgcn_s_buffer_load: { 5710 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5711 SDValue GLC; 5712 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5713 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5714 IsGFX10 ? &DLC : nullptr)) 5715 return Op; 5716 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5717 DAG); 5718 } 5719 case Intrinsic::amdgcn_fdiv_fast: 5720 return lowerFDIV_FAST(Op, DAG); 5721 case Intrinsic::amdgcn_interp_mov: { 5722 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5723 SDValue Glue = M0.getValue(1); 5724 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 5725 Op.getOperand(2), Op.getOperand(3), Glue); 5726 } 5727 case Intrinsic::amdgcn_interp_p1: { 5728 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5729 SDValue Glue = M0.getValue(1); 5730 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 5731 Op.getOperand(2), Op.getOperand(3), Glue); 5732 } 5733 case Intrinsic::amdgcn_interp_p2: { 5734 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5735 SDValue Glue = SDValue(M0.getNode(), 1); 5736 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 5737 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 5738 Glue); 5739 } 5740 case Intrinsic::amdgcn_interp_p1_f16: { 5741 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5742 SDValue Glue = M0.getValue(1); 5743 if (getSubtarget()->getLDSBankCount() == 16) { 5744 // 16 bank LDS 5745 SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 5746 DAG.getConstant(2, DL, MVT::i32), // P0 5747 Op.getOperand(2), // Attrchan 5748 Op.getOperand(3), // Attr 5749 Glue); 5750 SDValue Ops[] = { 5751 Op.getOperand(1), // Src0 5752 Op.getOperand(2), // Attrchan 5753 Op.getOperand(3), // Attr 5754 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5755 S, // Src2 - holds two f16 values selected by high 5756 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5757 Op.getOperand(4), // high 5758 DAG.getConstant(0, DL, MVT::i1), // $clamp 5759 DAG.getConstant(0, DL, MVT::i32) // $omod 5760 }; 5761 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5762 } else { 5763 // 32 bank LDS 5764 SDValue Ops[] = { 5765 Op.getOperand(1), // Src0 5766 Op.getOperand(2), // Attrchan 5767 Op.getOperand(3), // Attr 5768 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5769 Op.getOperand(4), // high 5770 DAG.getConstant(0, DL, MVT::i1), // $clamp 5771 DAG.getConstant(0, DL, MVT::i32), // $omod 5772 Glue 5773 }; 5774 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5775 } 5776 } 5777 case Intrinsic::amdgcn_interp_p2_f16: { 5778 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6)); 5779 SDValue Glue = SDValue(M0.getNode(), 1); 5780 SDValue Ops[] = { 5781 Op.getOperand(2), // Src0 5782 Op.getOperand(3), // Attrchan 5783 Op.getOperand(4), // Attr 5784 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5785 Op.getOperand(1), // Src2 5786 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5787 Op.getOperand(5), // high 5788 DAG.getConstant(0, DL, MVT::i1), // $clamp 5789 Glue 5790 }; 5791 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5792 } 5793 case Intrinsic::amdgcn_sin: 5794 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5795 5796 case Intrinsic::amdgcn_cos: 5797 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5798 5799 case Intrinsic::amdgcn_log_clamp: { 5800 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5801 return SDValue(); 5802 5803 DiagnosticInfoUnsupported BadIntrin( 5804 MF.getFunction(), "intrinsic not supported on subtarget", 5805 DL.getDebugLoc()); 5806 DAG.getContext()->diagnose(BadIntrin); 5807 return DAG.getUNDEF(VT); 5808 } 5809 case Intrinsic::amdgcn_ldexp: 5810 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5811 Op.getOperand(1), Op.getOperand(2)); 5812 5813 case Intrinsic::amdgcn_fract: 5814 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5815 5816 case Intrinsic::amdgcn_class: 5817 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5818 Op.getOperand(1), Op.getOperand(2)); 5819 case Intrinsic::amdgcn_div_fmas: 5820 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5821 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5822 Op.getOperand(4)); 5823 5824 case Intrinsic::amdgcn_div_fixup: 5825 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5826 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5827 5828 case Intrinsic::amdgcn_trig_preop: 5829 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5830 Op.getOperand(1), Op.getOperand(2)); 5831 case Intrinsic::amdgcn_div_scale: { 5832 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5833 5834 // Translate to the operands expected by the machine instruction. The 5835 // first parameter must be the same as the first instruction. 5836 SDValue Numerator = Op.getOperand(1); 5837 SDValue Denominator = Op.getOperand(2); 5838 5839 // Note this order is opposite of the machine instruction's operations, 5840 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5841 // intrinsic has the numerator as the first operand to match a normal 5842 // division operation. 5843 5844 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5845 5846 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5847 Denominator, Numerator); 5848 } 5849 case Intrinsic::amdgcn_icmp: { 5850 // There is a Pat that handles this variant, so return it as-is. 5851 if (Op.getOperand(1).getValueType() == MVT::i1 && 5852 Op.getConstantOperandVal(2) == 0 && 5853 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5854 return Op; 5855 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5856 } 5857 case Intrinsic::amdgcn_fcmp: { 5858 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5859 } 5860 case Intrinsic::amdgcn_fmed3: 5861 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5862 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5863 case Intrinsic::amdgcn_fdot2: 5864 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5865 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5866 Op.getOperand(4)); 5867 case Intrinsic::amdgcn_fmul_legacy: 5868 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5869 Op.getOperand(1), Op.getOperand(2)); 5870 case Intrinsic::amdgcn_sffbh: 5871 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5872 case Intrinsic::amdgcn_sbfe: 5873 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5874 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5875 case Intrinsic::amdgcn_ubfe: 5876 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5877 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5878 case Intrinsic::amdgcn_cvt_pkrtz: 5879 case Intrinsic::amdgcn_cvt_pknorm_i16: 5880 case Intrinsic::amdgcn_cvt_pknorm_u16: 5881 case Intrinsic::amdgcn_cvt_pk_i16: 5882 case Intrinsic::amdgcn_cvt_pk_u16: { 5883 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5884 EVT VT = Op.getValueType(); 5885 unsigned Opcode; 5886 5887 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5888 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5889 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5890 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5891 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5892 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5893 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5894 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5895 else 5896 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5897 5898 if (isTypeLegal(VT)) 5899 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5900 5901 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5902 Op.getOperand(1), Op.getOperand(2)); 5903 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5904 } 5905 case Intrinsic::amdgcn_wqm: { 5906 SDValue Src = Op.getOperand(1); 5907 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 5908 0); 5909 } 5910 case Intrinsic::amdgcn_wwm: { 5911 SDValue Src = Op.getOperand(1); 5912 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 5913 0); 5914 } 5915 case Intrinsic::amdgcn_fmad_ftz: 5916 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5917 Op.getOperand(2), Op.getOperand(3)); 5918 5919 case Intrinsic::amdgcn_if_break: 5920 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5921 Op->getOperand(1), Op->getOperand(2)), 0); 5922 5923 case Intrinsic::amdgcn_groupstaticsize: { 5924 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 5925 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 5926 return Op; 5927 5928 const Module *M = MF.getFunction().getParent(); 5929 const GlobalValue *GV = 5930 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 5931 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 5932 SIInstrInfo::MO_ABS32_LO); 5933 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 5934 } 5935 default: 5936 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 5937 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 5938 return lowerImage(Op, ImageDimIntr, DAG); 5939 5940 return Op; 5941 } 5942 } 5943 5944 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 5945 SelectionDAG &DAG) const { 5946 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5947 SDLoc DL(Op); 5948 5949 switch (IntrID) { 5950 case Intrinsic::amdgcn_ds_ordered_add: 5951 case Intrinsic::amdgcn_ds_ordered_swap: { 5952 MemSDNode *M = cast<MemSDNode>(Op); 5953 SDValue Chain = M->getOperand(0); 5954 SDValue M0 = M->getOperand(2); 5955 SDValue Value = M->getOperand(3); 5956 unsigned IndexOperand = M->getConstantOperandVal(7); 5957 unsigned WaveRelease = M->getConstantOperandVal(8); 5958 unsigned WaveDone = M->getConstantOperandVal(9); 5959 unsigned ShaderType; 5960 unsigned Instruction; 5961 5962 unsigned OrderedCountIndex = IndexOperand & 0x3f; 5963 IndexOperand &= ~0x3f; 5964 unsigned CountDw = 0; 5965 5966 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 5967 CountDw = (IndexOperand >> 24) & 0xf; 5968 IndexOperand &= ~(0xf << 24); 5969 5970 if (CountDw < 1 || CountDw > 4) { 5971 report_fatal_error( 5972 "ds_ordered_count: dword count must be between 1 and 4"); 5973 } 5974 } 5975 5976 if (IndexOperand) 5977 report_fatal_error("ds_ordered_count: bad index operand"); 5978 5979 switch (IntrID) { 5980 case Intrinsic::amdgcn_ds_ordered_add: 5981 Instruction = 0; 5982 break; 5983 case Intrinsic::amdgcn_ds_ordered_swap: 5984 Instruction = 1; 5985 break; 5986 } 5987 5988 if (WaveDone && !WaveRelease) 5989 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 5990 5991 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 5992 case CallingConv::AMDGPU_CS: 5993 case CallingConv::AMDGPU_KERNEL: 5994 ShaderType = 0; 5995 break; 5996 case CallingConv::AMDGPU_PS: 5997 ShaderType = 1; 5998 break; 5999 case CallingConv::AMDGPU_VS: 6000 ShaderType = 2; 6001 break; 6002 case CallingConv::AMDGPU_GS: 6003 ShaderType = 3; 6004 break; 6005 default: 6006 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6007 } 6008 6009 unsigned Offset0 = OrderedCountIndex << 2; 6010 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6011 (Instruction << 4); 6012 6013 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6014 Offset1 |= (CountDw - 1) << 6; 6015 6016 unsigned Offset = Offset0 | (Offset1 << 8); 6017 6018 SDValue Ops[] = { 6019 Chain, 6020 Value, 6021 DAG.getTargetConstant(Offset, DL, MVT::i16), 6022 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6023 }; 6024 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6025 M->getVTList(), Ops, M->getMemoryVT(), 6026 M->getMemOperand()); 6027 } 6028 case Intrinsic::amdgcn_ds_fadd: { 6029 MemSDNode *M = cast<MemSDNode>(Op); 6030 unsigned Opc; 6031 switch (IntrID) { 6032 case Intrinsic::amdgcn_ds_fadd: 6033 Opc = ISD::ATOMIC_LOAD_FADD; 6034 break; 6035 } 6036 6037 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6038 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6039 M->getMemOperand()); 6040 } 6041 case Intrinsic::amdgcn_atomic_inc: 6042 case Intrinsic::amdgcn_atomic_dec: 6043 case Intrinsic::amdgcn_ds_fmin: 6044 case Intrinsic::amdgcn_ds_fmax: { 6045 MemSDNode *M = cast<MemSDNode>(Op); 6046 unsigned Opc; 6047 switch (IntrID) { 6048 case Intrinsic::amdgcn_atomic_inc: 6049 Opc = AMDGPUISD::ATOMIC_INC; 6050 break; 6051 case Intrinsic::amdgcn_atomic_dec: 6052 Opc = AMDGPUISD::ATOMIC_DEC; 6053 break; 6054 case Intrinsic::amdgcn_ds_fmin: 6055 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6056 break; 6057 case Intrinsic::amdgcn_ds_fmax: 6058 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6059 break; 6060 default: 6061 llvm_unreachable("Unknown intrinsic!"); 6062 } 6063 SDValue Ops[] = { 6064 M->getOperand(0), // Chain 6065 M->getOperand(2), // Ptr 6066 M->getOperand(3) // Value 6067 }; 6068 6069 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6070 M->getMemoryVT(), M->getMemOperand()); 6071 } 6072 case Intrinsic::amdgcn_buffer_load: 6073 case Intrinsic::amdgcn_buffer_load_format: { 6074 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6075 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6076 unsigned IdxEn = 1; 6077 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6078 IdxEn = Idx->getZExtValue() != 0; 6079 SDValue Ops[] = { 6080 Op.getOperand(0), // Chain 6081 Op.getOperand(2), // rsrc 6082 Op.getOperand(3), // vindex 6083 SDValue(), // voffset -- will be set by setBufferOffsets 6084 SDValue(), // soffset -- will be set by setBufferOffsets 6085 SDValue(), // offset -- will be set by setBufferOffsets 6086 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6087 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6088 }; 6089 6090 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6091 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6092 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6093 6094 EVT VT = Op.getValueType(); 6095 EVT IntVT = VT.changeTypeToInteger(); 6096 auto *M = cast<MemSDNode>(Op); 6097 EVT LoadVT = Op.getValueType(); 6098 6099 if (LoadVT.getScalarType() == MVT::f16) 6100 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6101 M, DAG, Ops); 6102 6103 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6104 if (LoadVT.getScalarType() == MVT::i8 || 6105 LoadVT.getScalarType() == MVT::i16) 6106 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6107 6108 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6109 M->getMemOperand(), DAG); 6110 } 6111 case Intrinsic::amdgcn_raw_buffer_load: 6112 case Intrinsic::amdgcn_raw_buffer_load_format: { 6113 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6114 SDValue Ops[] = { 6115 Op.getOperand(0), // Chain 6116 Op.getOperand(2), // rsrc 6117 DAG.getConstant(0, DL, MVT::i32), // vindex 6118 Offsets.first, // voffset 6119 Op.getOperand(4), // soffset 6120 Offsets.second, // offset 6121 Op.getOperand(5), // cachepolicy 6122 DAG.getConstant(0, DL, MVT::i1), // idxen 6123 }; 6124 6125 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ? 6126 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6127 6128 EVT VT = Op.getValueType(); 6129 EVT IntVT = VT.changeTypeToInteger(); 6130 auto *M = cast<MemSDNode>(Op); 6131 EVT LoadVT = Op.getValueType(); 6132 6133 if (LoadVT.getScalarType() == MVT::f16) 6134 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6135 M, DAG, Ops); 6136 6137 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6138 if (LoadVT.getScalarType() == MVT::i8 || 6139 LoadVT.getScalarType() == MVT::i16) 6140 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6141 6142 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6143 M->getMemOperand(), DAG); 6144 } 6145 case Intrinsic::amdgcn_struct_buffer_load: 6146 case Intrinsic::amdgcn_struct_buffer_load_format: { 6147 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6148 SDValue Ops[] = { 6149 Op.getOperand(0), // Chain 6150 Op.getOperand(2), // rsrc 6151 Op.getOperand(3), // vindex 6152 Offsets.first, // voffset 6153 Op.getOperand(5), // soffset 6154 Offsets.second, // offset 6155 Op.getOperand(6), // cachepolicy 6156 DAG.getConstant(1, DL, MVT::i1), // idxen 6157 }; 6158 6159 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ? 6160 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6161 6162 EVT VT = Op.getValueType(); 6163 EVT IntVT = VT.changeTypeToInteger(); 6164 auto *M = cast<MemSDNode>(Op); 6165 EVT LoadVT = Op.getValueType(); 6166 6167 if (LoadVT.getScalarType() == MVT::f16) 6168 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6169 M, DAG, Ops); 6170 6171 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6172 if (LoadVT.getScalarType() == MVT::i8 || 6173 LoadVT.getScalarType() == MVT::i16) 6174 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6175 6176 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6177 M->getMemOperand(), DAG); 6178 } 6179 case Intrinsic::amdgcn_tbuffer_load: { 6180 MemSDNode *M = cast<MemSDNode>(Op); 6181 EVT LoadVT = Op.getValueType(); 6182 6183 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6184 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6185 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6186 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6187 unsigned IdxEn = 1; 6188 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6189 IdxEn = Idx->getZExtValue() != 0; 6190 SDValue Ops[] = { 6191 Op.getOperand(0), // Chain 6192 Op.getOperand(2), // rsrc 6193 Op.getOperand(3), // vindex 6194 Op.getOperand(4), // voffset 6195 Op.getOperand(5), // soffset 6196 Op.getOperand(6), // offset 6197 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6198 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6199 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6200 }; 6201 6202 if (LoadVT.getScalarType() == MVT::f16) 6203 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6204 M, DAG, Ops); 6205 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6206 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6207 DAG); 6208 } 6209 case Intrinsic::amdgcn_raw_tbuffer_load: { 6210 MemSDNode *M = cast<MemSDNode>(Op); 6211 EVT LoadVT = Op.getValueType(); 6212 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6213 6214 SDValue Ops[] = { 6215 Op.getOperand(0), // Chain 6216 Op.getOperand(2), // rsrc 6217 DAG.getConstant(0, DL, MVT::i32), // vindex 6218 Offsets.first, // voffset 6219 Op.getOperand(4), // soffset 6220 Offsets.second, // offset 6221 Op.getOperand(5), // format 6222 Op.getOperand(6), // cachepolicy 6223 DAG.getConstant(0, DL, MVT::i1), // idxen 6224 }; 6225 6226 if (LoadVT.getScalarType() == MVT::f16) 6227 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6228 M, DAG, Ops); 6229 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6230 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6231 DAG); 6232 } 6233 case Intrinsic::amdgcn_struct_tbuffer_load: { 6234 MemSDNode *M = cast<MemSDNode>(Op); 6235 EVT LoadVT = Op.getValueType(); 6236 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6237 6238 SDValue Ops[] = { 6239 Op.getOperand(0), // Chain 6240 Op.getOperand(2), // rsrc 6241 Op.getOperand(3), // vindex 6242 Offsets.first, // voffset 6243 Op.getOperand(5), // soffset 6244 Offsets.second, // offset 6245 Op.getOperand(6), // format 6246 Op.getOperand(7), // cachepolicy 6247 DAG.getConstant(1, DL, MVT::i1), // idxen 6248 }; 6249 6250 if (LoadVT.getScalarType() == MVT::f16) 6251 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6252 M, DAG, Ops); 6253 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6254 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6255 DAG); 6256 } 6257 case Intrinsic::amdgcn_buffer_atomic_swap: 6258 case Intrinsic::amdgcn_buffer_atomic_add: 6259 case Intrinsic::amdgcn_buffer_atomic_sub: 6260 case Intrinsic::amdgcn_buffer_atomic_smin: 6261 case Intrinsic::amdgcn_buffer_atomic_umin: 6262 case Intrinsic::amdgcn_buffer_atomic_smax: 6263 case Intrinsic::amdgcn_buffer_atomic_umax: 6264 case Intrinsic::amdgcn_buffer_atomic_and: 6265 case Intrinsic::amdgcn_buffer_atomic_or: 6266 case Intrinsic::amdgcn_buffer_atomic_xor: { 6267 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6268 unsigned IdxEn = 1; 6269 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6270 IdxEn = Idx->getZExtValue() != 0; 6271 SDValue Ops[] = { 6272 Op.getOperand(0), // Chain 6273 Op.getOperand(2), // vdata 6274 Op.getOperand(3), // rsrc 6275 Op.getOperand(4), // vindex 6276 SDValue(), // voffset -- will be set by setBufferOffsets 6277 SDValue(), // soffset -- will be set by setBufferOffsets 6278 SDValue(), // offset -- will be set by setBufferOffsets 6279 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6280 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6281 }; 6282 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6283 EVT VT = Op.getValueType(); 6284 6285 auto *M = cast<MemSDNode>(Op); 6286 unsigned Opcode = 0; 6287 6288 switch (IntrID) { 6289 case Intrinsic::amdgcn_buffer_atomic_swap: 6290 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6291 break; 6292 case Intrinsic::amdgcn_buffer_atomic_add: 6293 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6294 break; 6295 case Intrinsic::amdgcn_buffer_atomic_sub: 6296 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6297 break; 6298 case Intrinsic::amdgcn_buffer_atomic_smin: 6299 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6300 break; 6301 case Intrinsic::amdgcn_buffer_atomic_umin: 6302 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6303 break; 6304 case Intrinsic::amdgcn_buffer_atomic_smax: 6305 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6306 break; 6307 case Intrinsic::amdgcn_buffer_atomic_umax: 6308 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6309 break; 6310 case Intrinsic::amdgcn_buffer_atomic_and: 6311 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6312 break; 6313 case Intrinsic::amdgcn_buffer_atomic_or: 6314 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6315 break; 6316 case Intrinsic::amdgcn_buffer_atomic_xor: 6317 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6318 break; 6319 default: 6320 llvm_unreachable("unhandled atomic opcode"); 6321 } 6322 6323 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6324 M->getMemOperand()); 6325 } 6326 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6327 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6328 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6329 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6330 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6331 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6332 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6333 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6334 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6335 case Intrinsic::amdgcn_raw_buffer_atomic_xor: { 6336 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6337 SDValue Ops[] = { 6338 Op.getOperand(0), // Chain 6339 Op.getOperand(2), // vdata 6340 Op.getOperand(3), // rsrc 6341 DAG.getConstant(0, DL, MVT::i32), // vindex 6342 Offsets.first, // voffset 6343 Op.getOperand(5), // soffset 6344 Offsets.second, // offset 6345 Op.getOperand(6), // cachepolicy 6346 DAG.getConstant(0, DL, MVT::i1), // idxen 6347 }; 6348 EVT VT = Op.getValueType(); 6349 6350 auto *M = cast<MemSDNode>(Op); 6351 unsigned Opcode = 0; 6352 6353 switch (IntrID) { 6354 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6355 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6356 break; 6357 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6358 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6359 break; 6360 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6361 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6362 break; 6363 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6364 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6365 break; 6366 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6367 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6368 break; 6369 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6370 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6371 break; 6372 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6373 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6374 break; 6375 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6376 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6377 break; 6378 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6379 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6380 break; 6381 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6382 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6383 break; 6384 default: 6385 llvm_unreachable("unhandled atomic opcode"); 6386 } 6387 6388 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6389 M->getMemOperand()); 6390 } 6391 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6392 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6393 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6394 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6395 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6396 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6397 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6398 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6399 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6400 case Intrinsic::amdgcn_struct_buffer_atomic_xor: { 6401 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6402 SDValue Ops[] = { 6403 Op.getOperand(0), // Chain 6404 Op.getOperand(2), // vdata 6405 Op.getOperand(3), // rsrc 6406 Op.getOperand(4), // vindex 6407 Offsets.first, // voffset 6408 Op.getOperand(6), // soffset 6409 Offsets.second, // offset 6410 Op.getOperand(7), // cachepolicy 6411 DAG.getConstant(1, DL, MVT::i1), // idxen 6412 }; 6413 EVT VT = Op.getValueType(); 6414 6415 auto *M = cast<MemSDNode>(Op); 6416 unsigned Opcode = 0; 6417 6418 switch (IntrID) { 6419 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6420 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6421 break; 6422 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6423 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6424 break; 6425 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6426 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6427 break; 6428 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6429 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6430 break; 6431 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6432 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6433 break; 6434 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6435 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6436 break; 6437 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6438 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6439 break; 6440 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6441 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6442 break; 6443 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6444 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6445 break; 6446 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6447 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6448 break; 6449 default: 6450 llvm_unreachable("unhandled atomic opcode"); 6451 } 6452 6453 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6454 M->getMemOperand()); 6455 } 6456 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6457 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6458 unsigned IdxEn = 1; 6459 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6460 IdxEn = Idx->getZExtValue() != 0; 6461 SDValue Ops[] = { 6462 Op.getOperand(0), // Chain 6463 Op.getOperand(2), // src 6464 Op.getOperand(3), // cmp 6465 Op.getOperand(4), // rsrc 6466 Op.getOperand(5), // vindex 6467 SDValue(), // voffset -- will be set by setBufferOffsets 6468 SDValue(), // soffset -- will be set by setBufferOffsets 6469 SDValue(), // offset -- will be set by setBufferOffsets 6470 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6471 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6472 }; 6473 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6474 EVT VT = Op.getValueType(); 6475 auto *M = cast<MemSDNode>(Op); 6476 6477 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6478 Op->getVTList(), Ops, VT, M->getMemOperand()); 6479 } 6480 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6481 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6482 SDValue Ops[] = { 6483 Op.getOperand(0), // Chain 6484 Op.getOperand(2), // src 6485 Op.getOperand(3), // cmp 6486 Op.getOperand(4), // rsrc 6487 DAG.getConstant(0, DL, MVT::i32), // vindex 6488 Offsets.first, // voffset 6489 Op.getOperand(6), // soffset 6490 Offsets.second, // offset 6491 Op.getOperand(7), // cachepolicy 6492 DAG.getConstant(0, DL, MVT::i1), // idxen 6493 }; 6494 EVT VT = Op.getValueType(); 6495 auto *M = cast<MemSDNode>(Op); 6496 6497 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6498 Op->getVTList(), Ops, VT, M->getMemOperand()); 6499 } 6500 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6501 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6502 SDValue Ops[] = { 6503 Op.getOperand(0), // Chain 6504 Op.getOperand(2), // src 6505 Op.getOperand(3), // cmp 6506 Op.getOperand(4), // rsrc 6507 Op.getOperand(5), // vindex 6508 Offsets.first, // voffset 6509 Op.getOperand(7), // soffset 6510 Offsets.second, // offset 6511 Op.getOperand(8), // cachepolicy 6512 DAG.getConstant(1, DL, MVT::i1), // idxen 6513 }; 6514 EVT VT = Op.getValueType(); 6515 auto *M = cast<MemSDNode>(Op); 6516 6517 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6518 Op->getVTList(), Ops, VT, M->getMemOperand()); 6519 } 6520 6521 default: 6522 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6523 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6524 return lowerImage(Op, ImageDimIntr, DAG); 6525 6526 return SDValue(); 6527 } 6528 } 6529 6530 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6531 // dwordx4 if on SI. 6532 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6533 SDVTList VTList, 6534 ArrayRef<SDValue> Ops, EVT MemVT, 6535 MachineMemOperand *MMO, 6536 SelectionDAG &DAG) const { 6537 EVT VT = VTList.VTs[0]; 6538 EVT WidenedVT = VT; 6539 EVT WidenedMemVT = MemVT; 6540 if (!Subtarget->hasDwordx3LoadStores() && 6541 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6542 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6543 WidenedVT.getVectorElementType(), 4); 6544 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6545 WidenedMemVT.getVectorElementType(), 4); 6546 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6547 } 6548 6549 assert(VTList.NumVTs == 2); 6550 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6551 6552 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6553 WidenedMemVT, MMO); 6554 if (WidenedVT != VT) { 6555 auto Extract = DAG.getNode( 6556 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6557 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6558 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6559 } 6560 return NewOp; 6561 } 6562 6563 SDValue SITargetLowering::handleD16VData(SDValue VData, 6564 SelectionDAG &DAG) const { 6565 EVT StoreVT = VData.getValueType(); 6566 6567 // No change for f16 and legal vector D16 types. 6568 if (!StoreVT.isVector()) 6569 return VData; 6570 6571 SDLoc DL(VData); 6572 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6573 6574 if (Subtarget->hasUnpackedD16VMem()) { 6575 // We need to unpack the packed data to store. 6576 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6577 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6578 6579 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6580 StoreVT.getVectorNumElements()); 6581 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6582 return DAG.UnrollVectorOp(ZExt.getNode()); 6583 } 6584 6585 assert(isTypeLegal(StoreVT)); 6586 return VData; 6587 } 6588 6589 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6590 SelectionDAG &DAG) const { 6591 SDLoc DL(Op); 6592 SDValue Chain = Op.getOperand(0); 6593 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6594 MachineFunction &MF = DAG.getMachineFunction(); 6595 6596 switch (IntrinsicID) { 6597 case Intrinsic::amdgcn_exp: { 6598 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6599 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6600 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6601 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6602 6603 const SDValue Ops[] = { 6604 Chain, 6605 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6606 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6607 Op.getOperand(4), // src0 6608 Op.getOperand(5), // src1 6609 Op.getOperand(6), // src2 6610 Op.getOperand(7), // src3 6611 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6612 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6613 }; 6614 6615 unsigned Opc = Done->isNullValue() ? 6616 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6617 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6618 } 6619 case Intrinsic::amdgcn_exp_compr: { 6620 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6621 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6622 SDValue Src0 = Op.getOperand(4); 6623 SDValue Src1 = Op.getOperand(5); 6624 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6625 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6626 6627 SDValue Undef = DAG.getUNDEF(MVT::f32); 6628 const SDValue Ops[] = { 6629 Chain, 6630 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6631 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6632 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6633 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6634 Undef, // src2 6635 Undef, // src3 6636 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6637 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6638 }; 6639 6640 unsigned Opc = Done->isNullValue() ? 6641 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6642 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6643 } 6644 case Intrinsic::amdgcn_s_sendmsg: 6645 case Intrinsic::amdgcn_s_sendmsghalt: { 6646 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 6647 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 6648 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 6649 SDValue Glue = Chain.getValue(1); 6650 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 6651 Op.getOperand(2), Glue); 6652 } 6653 case Intrinsic::amdgcn_init_exec: { 6654 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 6655 Op.getOperand(2)); 6656 } 6657 case Intrinsic::amdgcn_init_exec_from_input: { 6658 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 6659 Op.getOperand(2), Op.getOperand(3)); 6660 } 6661 case Intrinsic::amdgcn_s_barrier: { 6662 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6663 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6664 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6665 if (WGSize <= ST.getWavefrontSize()) 6666 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6667 Op.getOperand(0)), 0); 6668 } 6669 return SDValue(); 6670 }; 6671 case Intrinsic::amdgcn_tbuffer_store: { 6672 SDValue VData = Op.getOperand(2); 6673 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6674 if (IsD16) 6675 VData = handleD16VData(VData, DAG); 6676 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6677 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6678 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6679 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6680 unsigned IdxEn = 1; 6681 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6682 IdxEn = Idx->getZExtValue() != 0; 6683 SDValue Ops[] = { 6684 Chain, 6685 VData, // vdata 6686 Op.getOperand(3), // rsrc 6687 Op.getOperand(4), // vindex 6688 Op.getOperand(5), // voffset 6689 Op.getOperand(6), // soffset 6690 Op.getOperand(7), // offset 6691 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6692 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6693 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen 6694 }; 6695 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6696 AMDGPUISD::TBUFFER_STORE_FORMAT; 6697 MemSDNode *M = cast<MemSDNode>(Op); 6698 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6699 M->getMemoryVT(), M->getMemOperand()); 6700 } 6701 6702 case Intrinsic::amdgcn_struct_tbuffer_store: { 6703 SDValue VData = Op.getOperand(2); 6704 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6705 if (IsD16) 6706 VData = handleD16VData(VData, DAG); 6707 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6708 SDValue Ops[] = { 6709 Chain, 6710 VData, // vdata 6711 Op.getOperand(3), // rsrc 6712 Op.getOperand(4), // vindex 6713 Offsets.first, // voffset 6714 Op.getOperand(6), // soffset 6715 Offsets.second, // offset 6716 Op.getOperand(7), // format 6717 Op.getOperand(8), // cachepolicy 6718 DAG.getConstant(1, DL, MVT::i1), // idexen 6719 }; 6720 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6721 AMDGPUISD::TBUFFER_STORE_FORMAT; 6722 MemSDNode *M = cast<MemSDNode>(Op); 6723 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6724 M->getMemoryVT(), M->getMemOperand()); 6725 } 6726 6727 case Intrinsic::amdgcn_raw_tbuffer_store: { 6728 SDValue VData = Op.getOperand(2); 6729 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6730 if (IsD16) 6731 VData = handleD16VData(VData, DAG); 6732 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6733 SDValue Ops[] = { 6734 Chain, 6735 VData, // vdata 6736 Op.getOperand(3), // rsrc 6737 DAG.getConstant(0, DL, MVT::i32), // vindex 6738 Offsets.first, // voffset 6739 Op.getOperand(5), // soffset 6740 Offsets.second, // offset 6741 Op.getOperand(6), // format 6742 Op.getOperand(7), // cachepolicy 6743 DAG.getConstant(0, DL, MVT::i1), // idexen 6744 }; 6745 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6746 AMDGPUISD::TBUFFER_STORE_FORMAT; 6747 MemSDNode *M = cast<MemSDNode>(Op); 6748 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6749 M->getMemoryVT(), M->getMemOperand()); 6750 } 6751 6752 case Intrinsic::amdgcn_buffer_store: 6753 case Intrinsic::amdgcn_buffer_store_format: { 6754 SDValue VData = Op.getOperand(2); 6755 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6756 if (IsD16) 6757 VData = handleD16VData(VData, DAG); 6758 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6759 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6760 unsigned IdxEn = 1; 6761 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6762 IdxEn = Idx->getZExtValue() != 0; 6763 SDValue Ops[] = { 6764 Chain, 6765 VData, 6766 Op.getOperand(3), // rsrc 6767 Op.getOperand(4), // vindex 6768 SDValue(), // voffset -- will be set by setBufferOffsets 6769 SDValue(), // soffset -- will be set by setBufferOffsets 6770 SDValue(), // offset -- will be set by setBufferOffsets 6771 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6772 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6773 }; 6774 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6775 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6776 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6777 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6778 MemSDNode *M = cast<MemSDNode>(Op); 6779 6780 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6781 EVT VDataType = VData.getValueType().getScalarType(); 6782 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6783 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6784 6785 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6786 M->getMemoryVT(), M->getMemOperand()); 6787 } 6788 6789 case Intrinsic::amdgcn_raw_buffer_store: 6790 case Intrinsic::amdgcn_raw_buffer_store_format: { 6791 SDValue VData = Op.getOperand(2); 6792 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6793 if (IsD16) 6794 VData = handleD16VData(VData, DAG); 6795 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6796 SDValue Ops[] = { 6797 Chain, 6798 VData, 6799 Op.getOperand(3), // rsrc 6800 DAG.getConstant(0, DL, MVT::i32), // vindex 6801 Offsets.first, // voffset 6802 Op.getOperand(5), // soffset 6803 Offsets.second, // offset 6804 Op.getOperand(6), // cachepolicy 6805 DAG.getConstant(0, DL, MVT::i1), // idxen 6806 }; 6807 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ? 6808 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6809 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6810 MemSDNode *M = cast<MemSDNode>(Op); 6811 6812 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6813 EVT VDataType = VData.getValueType().getScalarType(); 6814 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6815 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6816 6817 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6818 M->getMemoryVT(), M->getMemOperand()); 6819 } 6820 6821 case Intrinsic::amdgcn_struct_buffer_store: 6822 case Intrinsic::amdgcn_struct_buffer_store_format: { 6823 SDValue VData = Op.getOperand(2); 6824 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6825 if (IsD16) 6826 VData = handleD16VData(VData, DAG); 6827 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6828 SDValue Ops[] = { 6829 Chain, 6830 VData, 6831 Op.getOperand(3), // rsrc 6832 Op.getOperand(4), // vindex 6833 Offsets.first, // voffset 6834 Op.getOperand(6), // soffset 6835 Offsets.second, // offset 6836 Op.getOperand(7), // cachepolicy 6837 DAG.getConstant(1, DL, MVT::i1), // idxen 6838 }; 6839 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6840 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6841 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6842 MemSDNode *M = cast<MemSDNode>(Op); 6843 6844 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6845 EVT VDataType = VData.getValueType().getScalarType(); 6846 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6847 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6848 6849 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6850 M->getMemoryVT(), M->getMemOperand()); 6851 } 6852 6853 case Intrinsic::amdgcn_end_cf: 6854 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 6855 Op->getOperand(2), Chain), 0); 6856 6857 default: { 6858 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6859 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6860 return lowerImage(Op, ImageDimIntr, DAG); 6861 6862 return Op; 6863 } 6864 } 6865 } 6866 6867 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 6868 // offset (the offset that is included in bounds checking and swizzling, to be 6869 // split between the instruction's voffset and immoffset fields) and soffset 6870 // (the offset that is excluded from bounds checking and swizzling, to go in 6871 // the instruction's soffset field). This function takes the first kind of 6872 // offset and figures out how to split it between voffset and immoffset. 6873 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 6874 SDValue Offset, SelectionDAG &DAG) const { 6875 SDLoc DL(Offset); 6876 const unsigned MaxImm = 4095; 6877 SDValue N0 = Offset; 6878 ConstantSDNode *C1 = nullptr; 6879 6880 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 6881 N0 = SDValue(); 6882 else if (DAG.isBaseWithConstantOffset(N0)) { 6883 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 6884 N0 = N0.getOperand(0); 6885 } 6886 6887 if (C1) { 6888 unsigned ImmOffset = C1->getZExtValue(); 6889 // If the immediate value is too big for the immoffset field, put the value 6890 // and -4096 into the immoffset field so that the value that is copied/added 6891 // for the voffset field is a multiple of 4096, and it stands more chance 6892 // of being CSEd with the copy/add for another similar load/store. 6893 // However, do not do that rounding down to a multiple of 4096 if that is a 6894 // negative number, as it appears to be illegal to have a negative offset 6895 // in the vgpr, even if adding the immediate offset makes it positive. 6896 unsigned Overflow = ImmOffset & ~MaxImm; 6897 ImmOffset -= Overflow; 6898 if ((int32_t)Overflow < 0) { 6899 Overflow += ImmOffset; 6900 ImmOffset = 0; 6901 } 6902 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32)); 6903 if (Overflow) { 6904 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 6905 if (!N0) 6906 N0 = OverflowVal; 6907 else { 6908 SDValue Ops[] = { N0, OverflowVal }; 6909 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 6910 } 6911 } 6912 } 6913 if (!N0) 6914 N0 = DAG.getConstant(0, DL, MVT::i32); 6915 if (!C1) 6916 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32)); 6917 return {N0, SDValue(C1, 0)}; 6918 } 6919 6920 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 6921 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 6922 // pointed to by Offsets. 6923 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 6924 SelectionDAG &DAG, SDValue *Offsets, 6925 unsigned Align) const { 6926 SDLoc DL(CombinedOffset); 6927 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 6928 uint32_t Imm = C->getZExtValue(); 6929 uint32_t SOffset, ImmOffset; 6930 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 6931 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 6932 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 6933 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 6934 return; 6935 } 6936 } 6937 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 6938 SDValue N0 = CombinedOffset.getOperand(0); 6939 SDValue N1 = CombinedOffset.getOperand(1); 6940 uint32_t SOffset, ImmOffset; 6941 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 6942 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 6943 Subtarget, Align)) { 6944 Offsets[0] = N0; 6945 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 6946 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 6947 return; 6948 } 6949 } 6950 Offsets[0] = CombinedOffset; 6951 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 6952 Offsets[2] = DAG.getConstant(0, DL, MVT::i32); 6953 } 6954 6955 // Handle 8 bit and 16 bit buffer loads 6956 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 6957 EVT LoadVT, SDLoc DL, 6958 ArrayRef<SDValue> Ops, 6959 MemSDNode *M) const { 6960 EVT IntVT = LoadVT.changeTypeToInteger(); 6961 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 6962 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 6963 6964 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 6965 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 6966 Ops, IntVT, 6967 M->getMemOperand()); 6968 SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL, 6969 LoadVT.getScalarType(), BufferLoad); 6970 return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL); 6971 } 6972 6973 // Handle 8 bit and 16 bit buffer stores 6974 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 6975 EVT VDataType, SDLoc DL, 6976 SDValue Ops[], 6977 MemSDNode *M) const { 6978 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 6979 Ops[1] = BufferStoreExt; 6980 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 6981 AMDGPUISD::BUFFER_STORE_SHORT; 6982 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 6983 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 6984 M->getMemOperand()); 6985 } 6986 6987 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 6988 ISD::LoadExtType ExtType, SDValue Op, 6989 const SDLoc &SL, EVT VT) { 6990 if (VT.bitsLT(Op.getValueType())) 6991 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 6992 6993 switch (ExtType) { 6994 case ISD::SEXTLOAD: 6995 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 6996 case ISD::ZEXTLOAD: 6997 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 6998 case ISD::EXTLOAD: 6999 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7000 case ISD::NON_EXTLOAD: 7001 return Op; 7002 } 7003 7004 llvm_unreachable("invalid ext type"); 7005 } 7006 7007 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7008 SelectionDAG &DAG = DCI.DAG; 7009 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7010 return SDValue(); 7011 7012 // FIXME: Constant loads should all be marked invariant. 7013 unsigned AS = Ld->getAddressSpace(); 7014 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7015 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7016 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7017 return SDValue(); 7018 7019 // Don't do this early, since it may interfere with adjacent load merging for 7020 // illegal types. We can avoid losing alignment information for exotic types 7021 // pre-legalize. 7022 EVT MemVT = Ld->getMemoryVT(); 7023 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7024 MemVT.getSizeInBits() >= 32) 7025 return SDValue(); 7026 7027 SDLoc SL(Ld); 7028 7029 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7030 "unexpected vector extload"); 7031 7032 // TODO: Drop only high part of range. 7033 SDValue Ptr = Ld->getBasePtr(); 7034 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7035 MVT::i32, SL, Ld->getChain(), Ptr, 7036 Ld->getOffset(), 7037 Ld->getPointerInfo(), MVT::i32, 7038 Ld->getAlignment(), 7039 Ld->getMemOperand()->getFlags(), 7040 Ld->getAAInfo(), 7041 nullptr); // Drop ranges 7042 7043 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7044 if (MemVT.isFloatingPoint()) { 7045 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7046 "unexpected fp extload"); 7047 TruncVT = MemVT.changeTypeToInteger(); 7048 } 7049 7050 SDValue Cvt = NewLoad; 7051 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7052 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7053 DAG.getValueType(TruncVT)); 7054 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7055 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7056 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7057 } else { 7058 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7059 } 7060 7061 EVT VT = Ld->getValueType(0); 7062 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7063 7064 DCI.AddToWorklist(Cvt.getNode()); 7065 7066 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7067 // the appropriate extension from the 32-bit load. 7068 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7069 DCI.AddToWorklist(Cvt.getNode()); 7070 7071 // Handle conversion back to floating point if necessary. 7072 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7073 7074 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7075 } 7076 7077 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7078 SDLoc DL(Op); 7079 LoadSDNode *Load = cast<LoadSDNode>(Op); 7080 ISD::LoadExtType ExtType = Load->getExtensionType(); 7081 EVT MemVT = Load->getMemoryVT(); 7082 7083 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7084 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7085 return SDValue(); 7086 7087 // FIXME: Copied from PPC 7088 // First, load into 32 bits, then truncate to 1 bit. 7089 7090 SDValue Chain = Load->getChain(); 7091 SDValue BasePtr = Load->getBasePtr(); 7092 MachineMemOperand *MMO = Load->getMemOperand(); 7093 7094 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7095 7096 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7097 BasePtr, RealMemVT, MMO); 7098 7099 if (!MemVT.isVector()) { 7100 SDValue Ops[] = { 7101 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7102 NewLD.getValue(1) 7103 }; 7104 7105 return DAG.getMergeValues(Ops, DL); 7106 } 7107 7108 SmallVector<SDValue, 3> Elts; 7109 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7110 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7111 DAG.getConstant(I, DL, MVT::i32)); 7112 7113 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7114 } 7115 7116 SDValue Ops[] = { 7117 DAG.getBuildVector(MemVT, DL, Elts), 7118 NewLD.getValue(1) 7119 }; 7120 7121 return DAG.getMergeValues(Ops, DL); 7122 } 7123 7124 if (!MemVT.isVector()) 7125 return SDValue(); 7126 7127 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7128 "Custom lowering for non-i32 vectors hasn't been implemented."); 7129 7130 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 7131 *Load->getMemOperand())) { 7132 SDValue Ops[2]; 7133 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7134 return DAG.getMergeValues(Ops, DL); 7135 } 7136 7137 unsigned Alignment = Load->getAlignment(); 7138 unsigned AS = Load->getAddressSpace(); 7139 if (Subtarget->hasLDSMisalignedBug() && 7140 AS == AMDGPUAS::FLAT_ADDRESS && 7141 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7142 return SplitVectorLoad(Op, DAG); 7143 } 7144 7145 MachineFunction &MF = DAG.getMachineFunction(); 7146 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7147 // If there is a possibilty that flat instruction access scratch memory 7148 // then we need to use the same legalization rules we use for private. 7149 if (AS == AMDGPUAS::FLAT_ADDRESS) 7150 AS = MFI->hasFlatScratchInit() ? 7151 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7152 7153 unsigned NumElements = MemVT.getVectorNumElements(); 7154 7155 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7156 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7157 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7158 if (MemVT.isPow2VectorType()) 7159 return SDValue(); 7160 if (NumElements == 3) 7161 return WidenVectorLoad(Op, DAG); 7162 return SplitVectorLoad(Op, DAG); 7163 } 7164 // Non-uniform loads will be selected to MUBUF instructions, so they 7165 // have the same legalization requirements as global and private 7166 // loads. 7167 // 7168 } 7169 7170 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7171 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7172 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7173 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7174 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7175 Alignment >= 4 && NumElements < 32) { 7176 if (MemVT.isPow2VectorType()) 7177 return SDValue(); 7178 if (NumElements == 3) 7179 return WidenVectorLoad(Op, DAG); 7180 return SplitVectorLoad(Op, DAG); 7181 } 7182 // Non-uniform loads will be selected to MUBUF instructions, so they 7183 // have the same legalization requirements as global and private 7184 // loads. 7185 // 7186 } 7187 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7188 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7189 AS == AMDGPUAS::GLOBAL_ADDRESS || 7190 AS == AMDGPUAS::FLAT_ADDRESS) { 7191 if (NumElements > 4) 7192 return SplitVectorLoad(Op, DAG); 7193 // v3 loads not supported on SI. 7194 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7195 return WidenVectorLoad(Op, DAG); 7196 // v3 and v4 loads are supported for private and global memory. 7197 return SDValue(); 7198 } 7199 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7200 // Depending on the setting of the private_element_size field in the 7201 // resource descriptor, we can only make private accesses up to a certain 7202 // size. 7203 switch (Subtarget->getMaxPrivateElementSize()) { 7204 case 4: 7205 return scalarizeVectorLoad(Load, DAG); 7206 case 8: 7207 if (NumElements > 2) 7208 return SplitVectorLoad(Op, DAG); 7209 return SDValue(); 7210 case 16: 7211 // Same as global/flat 7212 if (NumElements > 4) 7213 return SplitVectorLoad(Op, DAG); 7214 // v3 loads not supported on SI. 7215 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7216 return WidenVectorLoad(Op, DAG); 7217 return SDValue(); 7218 default: 7219 llvm_unreachable("unsupported private_element_size"); 7220 } 7221 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7222 // Use ds_read_b128 if possible. 7223 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7224 MemVT.getStoreSize() == 16) 7225 return SDValue(); 7226 7227 if (NumElements > 2) 7228 return SplitVectorLoad(Op, DAG); 7229 7230 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7231 // address is negative, then the instruction is incorrectly treated as 7232 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7233 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7234 // load later in the SILoadStoreOptimizer. 7235 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7236 NumElements == 2 && MemVT.getStoreSize() == 8 && 7237 Load->getAlignment() < 8) { 7238 return SplitVectorLoad(Op, DAG); 7239 } 7240 } 7241 return SDValue(); 7242 } 7243 7244 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7245 EVT VT = Op.getValueType(); 7246 assert(VT.getSizeInBits() == 64); 7247 7248 SDLoc DL(Op); 7249 SDValue Cond = Op.getOperand(0); 7250 7251 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7252 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7253 7254 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7255 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7256 7257 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7258 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7259 7260 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7261 7262 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7263 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7264 7265 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7266 7267 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7268 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7269 } 7270 7271 // Catch division cases where we can use shortcuts with rcp and rsq 7272 // instructions. 7273 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7274 SelectionDAG &DAG) const { 7275 SDLoc SL(Op); 7276 SDValue LHS = Op.getOperand(0); 7277 SDValue RHS = Op.getOperand(1); 7278 EVT VT = Op.getValueType(); 7279 const SDNodeFlags Flags = Op->getFlags(); 7280 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7281 7282 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 7283 return SDValue(); 7284 7285 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7286 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7287 if (CLHS->isExactlyValue(1.0)) { 7288 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7289 // the CI documentation has a worst case error of 1 ulp. 7290 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7291 // use it as long as we aren't trying to use denormals. 7292 // 7293 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7294 7295 // 1.0 / sqrt(x) -> rsq(x) 7296 7297 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7298 // error seems really high at 2^29 ULP. 7299 if (RHS.getOpcode() == ISD::FSQRT) 7300 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7301 7302 // 1.0 / x -> rcp(x) 7303 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7304 } 7305 7306 // Same as for 1.0, but expand the sign out of the constant. 7307 if (CLHS->isExactlyValue(-1.0)) { 7308 // -1.0 / x -> rcp (fneg x) 7309 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7310 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7311 } 7312 } 7313 } 7314 7315 if (Unsafe) { 7316 // Turn into multiply by the reciprocal. 7317 // x / y -> x * (1.0 / y) 7318 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7319 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7320 } 7321 7322 return SDValue(); 7323 } 7324 7325 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7326 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7327 if (GlueChain->getNumValues() <= 1) { 7328 return DAG.getNode(Opcode, SL, VT, A, B); 7329 } 7330 7331 assert(GlueChain->getNumValues() == 3); 7332 7333 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7334 switch (Opcode) { 7335 default: llvm_unreachable("no chain equivalent for opcode"); 7336 case ISD::FMUL: 7337 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7338 break; 7339 } 7340 7341 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7342 GlueChain.getValue(2)); 7343 } 7344 7345 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7346 EVT VT, SDValue A, SDValue B, SDValue C, 7347 SDValue GlueChain) { 7348 if (GlueChain->getNumValues() <= 1) { 7349 return DAG.getNode(Opcode, SL, VT, A, B, C); 7350 } 7351 7352 assert(GlueChain->getNumValues() == 3); 7353 7354 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7355 switch (Opcode) { 7356 default: llvm_unreachable("no chain equivalent for opcode"); 7357 case ISD::FMA: 7358 Opcode = AMDGPUISD::FMA_W_CHAIN; 7359 break; 7360 } 7361 7362 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7363 GlueChain.getValue(2)); 7364 } 7365 7366 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7367 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7368 return FastLowered; 7369 7370 SDLoc SL(Op); 7371 SDValue Src0 = Op.getOperand(0); 7372 SDValue Src1 = Op.getOperand(1); 7373 7374 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7375 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7376 7377 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7378 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7379 7380 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7381 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7382 7383 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7384 } 7385 7386 // Faster 2.5 ULP division that does not support denormals. 7387 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7388 SDLoc SL(Op); 7389 SDValue LHS = Op.getOperand(1); 7390 SDValue RHS = Op.getOperand(2); 7391 7392 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7393 7394 const APFloat K0Val(BitsToFloat(0x6f800000)); 7395 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7396 7397 const APFloat K1Val(BitsToFloat(0x2f800000)); 7398 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7399 7400 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7401 7402 EVT SetCCVT = 7403 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7404 7405 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7406 7407 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7408 7409 // TODO: Should this propagate fast-math-flags? 7410 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7411 7412 // rcp does not support denormals. 7413 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7414 7415 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7416 7417 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7418 } 7419 7420 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7421 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7422 return FastLowered; 7423 7424 SDLoc SL(Op); 7425 SDValue LHS = Op.getOperand(0); 7426 SDValue RHS = Op.getOperand(1); 7427 7428 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7429 7430 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7431 7432 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7433 RHS, RHS, LHS); 7434 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7435 LHS, RHS, LHS); 7436 7437 // Denominator is scaled to not be denormal, so using rcp is ok. 7438 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7439 DenominatorScaled); 7440 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7441 DenominatorScaled); 7442 7443 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7444 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7445 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7446 7447 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7448 7449 if (!Subtarget->hasFP32Denormals()) { 7450 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7451 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7452 SL, MVT::i32); 7453 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7454 DAG.getEntryNode(), 7455 EnableDenormValue, BitField); 7456 SDValue Ops[3] = { 7457 NegDivScale0, 7458 EnableDenorm.getValue(0), 7459 EnableDenorm.getValue(1) 7460 }; 7461 7462 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7463 } 7464 7465 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7466 ApproxRcp, One, NegDivScale0); 7467 7468 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7469 ApproxRcp, Fma0); 7470 7471 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7472 Fma1, Fma1); 7473 7474 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7475 NumeratorScaled, Mul); 7476 7477 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7478 7479 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7480 NumeratorScaled, Fma3); 7481 7482 if (!Subtarget->hasFP32Denormals()) { 7483 const SDValue DisableDenormValue = 7484 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7485 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7486 Fma4.getValue(1), 7487 DisableDenormValue, 7488 BitField, 7489 Fma4.getValue(2)); 7490 7491 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7492 DisableDenorm, DAG.getRoot()); 7493 DAG.setRoot(OutputChain); 7494 } 7495 7496 SDValue Scale = NumeratorScaled.getValue(1); 7497 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7498 Fma4, Fma1, Fma3, Scale); 7499 7500 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7501 } 7502 7503 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7504 if (DAG.getTarget().Options.UnsafeFPMath) 7505 return lowerFastUnsafeFDIV(Op, DAG); 7506 7507 SDLoc SL(Op); 7508 SDValue X = Op.getOperand(0); 7509 SDValue Y = Op.getOperand(1); 7510 7511 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7512 7513 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7514 7515 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7516 7517 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7518 7519 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7520 7521 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7522 7523 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7524 7525 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7526 7527 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7528 7529 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7530 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7531 7532 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7533 NegDivScale0, Mul, DivScale1); 7534 7535 SDValue Scale; 7536 7537 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7538 // Workaround a hardware bug on SI where the condition output from div_scale 7539 // is not usable. 7540 7541 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7542 7543 // Figure out if the scale to use for div_fmas. 7544 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7545 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7546 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7547 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7548 7549 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7550 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7551 7552 SDValue Scale0Hi 7553 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7554 SDValue Scale1Hi 7555 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7556 7557 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7558 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7559 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7560 } else { 7561 Scale = DivScale1.getValue(1); 7562 } 7563 7564 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7565 Fma4, Fma3, Mul, Scale); 7566 7567 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7568 } 7569 7570 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7571 EVT VT = Op.getValueType(); 7572 7573 if (VT == MVT::f32) 7574 return LowerFDIV32(Op, DAG); 7575 7576 if (VT == MVT::f64) 7577 return LowerFDIV64(Op, DAG); 7578 7579 if (VT == MVT::f16) 7580 return LowerFDIV16(Op, DAG); 7581 7582 llvm_unreachable("Unexpected type for fdiv"); 7583 } 7584 7585 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7586 SDLoc DL(Op); 7587 StoreSDNode *Store = cast<StoreSDNode>(Op); 7588 EVT VT = Store->getMemoryVT(); 7589 7590 if (VT == MVT::i1) { 7591 return DAG.getTruncStore(Store->getChain(), DL, 7592 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7593 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7594 } 7595 7596 assert(VT.isVector() && 7597 Store->getValue().getValueType().getScalarType() == MVT::i32); 7598 7599 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7600 *Store->getMemOperand())) { 7601 return expandUnalignedStore(Store, DAG); 7602 } 7603 7604 unsigned AS = Store->getAddressSpace(); 7605 if (Subtarget->hasLDSMisalignedBug() && 7606 AS == AMDGPUAS::FLAT_ADDRESS && 7607 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7608 return SplitVectorStore(Op, DAG); 7609 } 7610 7611 MachineFunction &MF = DAG.getMachineFunction(); 7612 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7613 // If there is a possibilty that flat instruction access scratch memory 7614 // then we need to use the same legalization rules we use for private. 7615 if (AS == AMDGPUAS::FLAT_ADDRESS) 7616 AS = MFI->hasFlatScratchInit() ? 7617 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7618 7619 unsigned NumElements = VT.getVectorNumElements(); 7620 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7621 AS == AMDGPUAS::FLAT_ADDRESS) { 7622 if (NumElements > 4) 7623 return SplitVectorStore(Op, DAG); 7624 // v3 stores not supported on SI. 7625 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7626 return SplitVectorStore(Op, DAG); 7627 return SDValue(); 7628 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7629 switch (Subtarget->getMaxPrivateElementSize()) { 7630 case 4: 7631 return scalarizeVectorStore(Store, DAG); 7632 case 8: 7633 if (NumElements > 2) 7634 return SplitVectorStore(Op, DAG); 7635 return SDValue(); 7636 case 16: 7637 if (NumElements > 4 || NumElements == 3) 7638 return SplitVectorStore(Op, DAG); 7639 return SDValue(); 7640 default: 7641 llvm_unreachable("unsupported private_element_size"); 7642 } 7643 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7644 // Use ds_write_b128 if possible. 7645 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7646 VT.getStoreSize() == 16 && NumElements != 3) 7647 return SDValue(); 7648 7649 if (NumElements > 2) 7650 return SplitVectorStore(Op, DAG); 7651 7652 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7653 // address is negative, then the instruction is incorrectly treated as 7654 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7655 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7656 // store later in the SILoadStoreOptimizer. 7657 if (!Subtarget->hasUsableDSOffset() && 7658 NumElements == 2 && VT.getStoreSize() == 8 && 7659 Store->getAlignment() < 8) { 7660 return SplitVectorStore(Op, DAG); 7661 } 7662 7663 return SDValue(); 7664 } else { 7665 llvm_unreachable("unhandled address space"); 7666 } 7667 } 7668 7669 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7670 SDLoc DL(Op); 7671 EVT VT = Op.getValueType(); 7672 SDValue Arg = Op.getOperand(0); 7673 SDValue TrigVal; 7674 7675 // TODO: Should this propagate fast-math-flags? 7676 7677 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7678 7679 if (Subtarget->hasTrigReducedRange()) { 7680 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7681 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7682 } else { 7683 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7684 } 7685 7686 switch (Op.getOpcode()) { 7687 case ISD::FCOS: 7688 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7689 case ISD::FSIN: 7690 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7691 default: 7692 llvm_unreachable("Wrong trig opcode"); 7693 } 7694 } 7695 7696 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7697 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7698 assert(AtomicNode->isCompareAndSwap()); 7699 unsigned AS = AtomicNode->getAddressSpace(); 7700 7701 // No custom lowering required for local address space 7702 if (!isFlatGlobalAddrSpace(AS)) 7703 return Op; 7704 7705 // Non-local address space requires custom lowering for atomic compare 7706 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7707 SDLoc DL(Op); 7708 SDValue ChainIn = Op.getOperand(0); 7709 SDValue Addr = Op.getOperand(1); 7710 SDValue Old = Op.getOperand(2); 7711 SDValue New = Op.getOperand(3); 7712 EVT VT = Op.getValueType(); 7713 MVT SimpleVT = VT.getSimpleVT(); 7714 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7715 7716 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7717 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7718 7719 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7720 Ops, VT, AtomicNode->getMemOperand()); 7721 } 7722 7723 //===----------------------------------------------------------------------===// 7724 // Custom DAG optimizations 7725 //===----------------------------------------------------------------------===// 7726 7727 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7728 DAGCombinerInfo &DCI) const { 7729 EVT VT = N->getValueType(0); 7730 EVT ScalarVT = VT.getScalarType(); 7731 if (ScalarVT != MVT::f32) 7732 return SDValue(); 7733 7734 SelectionDAG &DAG = DCI.DAG; 7735 SDLoc DL(N); 7736 7737 SDValue Src = N->getOperand(0); 7738 EVT SrcVT = Src.getValueType(); 7739 7740 // TODO: We could try to match extracting the higher bytes, which would be 7741 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7742 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7743 // about in practice. 7744 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7745 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7746 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7747 DCI.AddToWorklist(Cvt.getNode()); 7748 return Cvt; 7749 } 7750 } 7751 7752 return SDValue(); 7753 } 7754 7755 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7756 7757 // This is a variant of 7758 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7759 // 7760 // The normal DAG combiner will do this, but only if the add has one use since 7761 // that would increase the number of instructions. 7762 // 7763 // This prevents us from seeing a constant offset that can be folded into a 7764 // memory instruction's addressing mode. If we know the resulting add offset of 7765 // a pointer can be folded into an addressing offset, we can replace the pointer 7766 // operand with the add of new constant offset. This eliminates one of the uses, 7767 // and may allow the remaining use to also be simplified. 7768 // 7769 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7770 unsigned AddrSpace, 7771 EVT MemVT, 7772 DAGCombinerInfo &DCI) const { 7773 SDValue N0 = N->getOperand(0); 7774 SDValue N1 = N->getOperand(1); 7775 7776 // We only do this to handle cases where it's profitable when there are 7777 // multiple uses of the add, so defer to the standard combine. 7778 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7779 N0->hasOneUse()) 7780 return SDValue(); 7781 7782 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7783 if (!CN1) 7784 return SDValue(); 7785 7786 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7787 if (!CAdd) 7788 return SDValue(); 7789 7790 // If the resulting offset is too large, we can't fold it into the addressing 7791 // mode offset. 7792 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7793 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7794 7795 AddrMode AM; 7796 AM.HasBaseReg = true; 7797 AM.BaseOffs = Offset.getSExtValue(); 7798 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7799 return SDValue(); 7800 7801 SelectionDAG &DAG = DCI.DAG; 7802 SDLoc SL(N); 7803 EVT VT = N->getValueType(0); 7804 7805 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 7806 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 7807 7808 SDNodeFlags Flags; 7809 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 7810 (N0.getOpcode() == ISD::OR || 7811 N0->getFlags().hasNoUnsignedWrap())); 7812 7813 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 7814 } 7815 7816 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 7817 DAGCombinerInfo &DCI) const { 7818 SDValue Ptr = N->getBasePtr(); 7819 SelectionDAG &DAG = DCI.DAG; 7820 SDLoc SL(N); 7821 7822 // TODO: We could also do this for multiplies. 7823 if (Ptr.getOpcode() == ISD::SHL) { 7824 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 7825 N->getMemoryVT(), DCI); 7826 if (NewPtr) { 7827 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 7828 7829 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 7830 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 7831 } 7832 } 7833 7834 return SDValue(); 7835 } 7836 7837 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 7838 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 7839 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 7840 (Opc == ISD::XOR && Val == 0); 7841 } 7842 7843 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 7844 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 7845 // integer combine opportunities since most 64-bit operations are decomposed 7846 // this way. TODO: We won't want this for SALU especially if it is an inline 7847 // immediate. 7848 SDValue SITargetLowering::splitBinaryBitConstantOp( 7849 DAGCombinerInfo &DCI, 7850 const SDLoc &SL, 7851 unsigned Opc, SDValue LHS, 7852 const ConstantSDNode *CRHS) const { 7853 uint64_t Val = CRHS->getZExtValue(); 7854 uint32_t ValLo = Lo_32(Val); 7855 uint32_t ValHi = Hi_32(Val); 7856 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7857 7858 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 7859 bitOpWithConstantIsReducible(Opc, ValHi)) || 7860 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 7861 // If we need to materialize a 64-bit immediate, it will be split up later 7862 // anyway. Avoid creating the harder to understand 64-bit immediate 7863 // materialization. 7864 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 7865 } 7866 7867 return SDValue(); 7868 } 7869 7870 // Returns true if argument is a boolean value which is not serialized into 7871 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 7872 static bool isBoolSGPR(SDValue V) { 7873 if (V.getValueType() != MVT::i1) 7874 return false; 7875 switch (V.getOpcode()) { 7876 default: break; 7877 case ISD::SETCC: 7878 case ISD::AND: 7879 case ISD::OR: 7880 case ISD::XOR: 7881 case AMDGPUISD::FP_CLASS: 7882 return true; 7883 } 7884 return false; 7885 } 7886 7887 // If a constant has all zeroes or all ones within each byte return it. 7888 // Otherwise return 0. 7889 static uint32_t getConstantPermuteMask(uint32_t C) { 7890 // 0xff for any zero byte in the mask 7891 uint32_t ZeroByteMask = 0; 7892 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 7893 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 7894 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 7895 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 7896 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 7897 if ((NonZeroByteMask & C) != NonZeroByteMask) 7898 return 0; // Partial bytes selected. 7899 return C; 7900 } 7901 7902 // Check if a node selects whole bytes from its operand 0 starting at a byte 7903 // boundary while masking the rest. Returns select mask as in the v_perm_b32 7904 // or -1 if not succeeded. 7905 // Note byte select encoding: 7906 // value 0-3 selects corresponding source byte; 7907 // value 0xc selects zero; 7908 // value 0xff selects 0xff. 7909 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 7910 assert(V.getValueSizeInBits() == 32); 7911 7912 if (V.getNumOperands() != 2) 7913 return ~0; 7914 7915 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 7916 if (!N1) 7917 return ~0; 7918 7919 uint32_t C = N1->getZExtValue(); 7920 7921 switch (V.getOpcode()) { 7922 default: 7923 break; 7924 case ISD::AND: 7925 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 7926 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 7927 } 7928 break; 7929 7930 case ISD::OR: 7931 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 7932 return (0x03020100 & ~ConstMask) | ConstMask; 7933 } 7934 break; 7935 7936 case ISD::SHL: 7937 if (C % 8) 7938 return ~0; 7939 7940 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 7941 7942 case ISD::SRL: 7943 if (C % 8) 7944 return ~0; 7945 7946 return uint32_t(0x0c0c0c0c03020100ull >> C); 7947 } 7948 7949 return ~0; 7950 } 7951 7952 SDValue SITargetLowering::performAndCombine(SDNode *N, 7953 DAGCombinerInfo &DCI) const { 7954 if (DCI.isBeforeLegalize()) 7955 return SDValue(); 7956 7957 SelectionDAG &DAG = DCI.DAG; 7958 EVT VT = N->getValueType(0); 7959 SDValue LHS = N->getOperand(0); 7960 SDValue RHS = N->getOperand(1); 7961 7962 7963 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 7964 if (VT == MVT::i64 && CRHS) { 7965 if (SDValue Split 7966 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 7967 return Split; 7968 } 7969 7970 if (CRHS && VT == MVT::i32) { 7971 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 7972 // nb = number of trailing zeroes in mask 7973 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 7974 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 7975 uint64_t Mask = CRHS->getZExtValue(); 7976 unsigned Bits = countPopulation(Mask); 7977 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 7978 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 7979 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 7980 unsigned Shift = CShift->getZExtValue(); 7981 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 7982 unsigned Offset = NB + Shift; 7983 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 7984 SDLoc SL(N); 7985 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 7986 LHS->getOperand(0), 7987 DAG.getConstant(Offset, SL, MVT::i32), 7988 DAG.getConstant(Bits, SL, MVT::i32)); 7989 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 7990 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 7991 DAG.getValueType(NarrowVT)); 7992 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 7993 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 7994 return Shl; 7995 } 7996 } 7997 } 7998 7999 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8000 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8001 isa<ConstantSDNode>(LHS.getOperand(2))) { 8002 uint32_t Sel = getConstantPermuteMask(Mask); 8003 if (!Sel) 8004 return SDValue(); 8005 8006 // Select 0xc for all zero bytes 8007 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8008 SDLoc DL(N); 8009 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8010 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8011 } 8012 } 8013 8014 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8015 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8016 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8017 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8018 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8019 8020 SDValue X = LHS.getOperand(0); 8021 SDValue Y = RHS.getOperand(0); 8022 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8023 return SDValue(); 8024 8025 if (LCC == ISD::SETO) { 8026 if (X != LHS.getOperand(1)) 8027 return SDValue(); 8028 8029 if (RCC == ISD::SETUNE) { 8030 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8031 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8032 return SDValue(); 8033 8034 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8035 SIInstrFlags::N_SUBNORMAL | 8036 SIInstrFlags::N_ZERO | 8037 SIInstrFlags::P_ZERO | 8038 SIInstrFlags::P_SUBNORMAL | 8039 SIInstrFlags::P_NORMAL; 8040 8041 static_assert(((~(SIInstrFlags::S_NAN | 8042 SIInstrFlags::Q_NAN | 8043 SIInstrFlags::N_INFINITY | 8044 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8045 "mask not equal"); 8046 8047 SDLoc DL(N); 8048 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8049 X, DAG.getConstant(Mask, DL, MVT::i32)); 8050 } 8051 } 8052 } 8053 8054 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8055 std::swap(LHS, RHS); 8056 8057 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8058 RHS.hasOneUse()) { 8059 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8060 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8061 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8062 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8063 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8064 (RHS.getOperand(0) == LHS.getOperand(0) && 8065 LHS.getOperand(0) == LHS.getOperand(1))) { 8066 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8067 unsigned NewMask = LCC == ISD::SETO ? 8068 Mask->getZExtValue() & ~OrdMask : 8069 Mask->getZExtValue() & OrdMask; 8070 8071 SDLoc DL(N); 8072 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8073 DAG.getConstant(NewMask, DL, MVT::i32)); 8074 } 8075 } 8076 8077 if (VT == MVT::i32 && 8078 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8079 // and x, (sext cc from i1) => select cc, x, 0 8080 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8081 std::swap(LHS, RHS); 8082 if (isBoolSGPR(RHS.getOperand(0))) 8083 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8084 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8085 } 8086 8087 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8088 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8089 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8090 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8091 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8092 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8093 if (LHSMask != ~0u && RHSMask != ~0u) { 8094 // Canonicalize the expression in an attempt to have fewer unique masks 8095 // and therefore fewer registers used to hold the masks. 8096 if (LHSMask > RHSMask) { 8097 std::swap(LHSMask, RHSMask); 8098 std::swap(LHS, RHS); 8099 } 8100 8101 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8102 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8103 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8104 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8105 8106 // Check of we need to combine values from two sources within a byte. 8107 if (!(LHSUsedLanes & RHSUsedLanes) && 8108 // If we select high and lower word keep it for SDWA. 8109 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8110 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8111 // Each byte in each mask is either selector mask 0-3, or has higher 8112 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8113 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8114 // mask which is not 0xff wins. By anding both masks we have a correct 8115 // result except that 0x0c shall be corrected to give 0x0c only. 8116 uint32_t Mask = LHSMask & RHSMask; 8117 for (unsigned I = 0; I < 32; I += 8) { 8118 uint32_t ByteSel = 0xff << I; 8119 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8120 Mask &= (0x0c << I) & 0xffffffff; 8121 } 8122 8123 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8124 // or 0x0c. 8125 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8126 SDLoc DL(N); 8127 8128 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8129 LHS.getOperand(0), RHS.getOperand(0), 8130 DAG.getConstant(Sel, DL, MVT::i32)); 8131 } 8132 } 8133 } 8134 8135 return SDValue(); 8136 } 8137 8138 SDValue SITargetLowering::performOrCombine(SDNode *N, 8139 DAGCombinerInfo &DCI) const { 8140 SelectionDAG &DAG = DCI.DAG; 8141 SDValue LHS = N->getOperand(0); 8142 SDValue RHS = N->getOperand(1); 8143 8144 EVT VT = N->getValueType(0); 8145 if (VT == MVT::i1) { 8146 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8147 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8148 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8149 SDValue Src = LHS.getOperand(0); 8150 if (Src != RHS.getOperand(0)) 8151 return SDValue(); 8152 8153 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8154 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8155 if (!CLHS || !CRHS) 8156 return SDValue(); 8157 8158 // Only 10 bits are used. 8159 static const uint32_t MaxMask = 0x3ff; 8160 8161 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8162 SDLoc DL(N); 8163 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8164 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8165 } 8166 8167 return SDValue(); 8168 } 8169 8170 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8171 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8172 LHS.getOpcode() == AMDGPUISD::PERM && 8173 isa<ConstantSDNode>(LHS.getOperand(2))) { 8174 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8175 if (!Sel) 8176 return SDValue(); 8177 8178 Sel |= LHS.getConstantOperandVal(2); 8179 SDLoc DL(N); 8180 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8181 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8182 } 8183 8184 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8185 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8186 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8187 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8188 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8189 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8190 if (LHSMask != ~0u && RHSMask != ~0u) { 8191 // Canonicalize the expression in an attempt to have fewer unique masks 8192 // and therefore fewer registers used to hold the masks. 8193 if (LHSMask > RHSMask) { 8194 std::swap(LHSMask, RHSMask); 8195 std::swap(LHS, RHS); 8196 } 8197 8198 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8199 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8200 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8201 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8202 8203 // Check of we need to combine values from two sources within a byte. 8204 if (!(LHSUsedLanes & RHSUsedLanes) && 8205 // If we select high and lower word keep it for SDWA. 8206 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8207 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8208 // Kill zero bytes selected by other mask. Zero value is 0xc. 8209 LHSMask &= ~RHSUsedLanes; 8210 RHSMask &= ~LHSUsedLanes; 8211 // Add 4 to each active LHS lane 8212 LHSMask |= LHSUsedLanes & 0x04040404; 8213 // Combine masks 8214 uint32_t Sel = LHSMask | RHSMask; 8215 SDLoc DL(N); 8216 8217 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8218 LHS.getOperand(0), RHS.getOperand(0), 8219 DAG.getConstant(Sel, DL, MVT::i32)); 8220 } 8221 } 8222 } 8223 8224 if (VT != MVT::i64) 8225 return SDValue(); 8226 8227 // TODO: This could be a generic combine with a predicate for extracting the 8228 // high half of an integer being free. 8229 8230 // (or i64:x, (zero_extend i32:y)) -> 8231 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8232 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8233 RHS.getOpcode() != ISD::ZERO_EXTEND) 8234 std::swap(LHS, RHS); 8235 8236 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8237 SDValue ExtSrc = RHS.getOperand(0); 8238 EVT SrcVT = ExtSrc.getValueType(); 8239 if (SrcVT == MVT::i32) { 8240 SDLoc SL(N); 8241 SDValue LowLHS, HiBits; 8242 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8243 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8244 8245 DCI.AddToWorklist(LowOr.getNode()); 8246 DCI.AddToWorklist(HiBits.getNode()); 8247 8248 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8249 LowOr, HiBits); 8250 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8251 } 8252 } 8253 8254 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8255 if (CRHS) { 8256 if (SDValue Split 8257 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8258 return Split; 8259 } 8260 8261 return SDValue(); 8262 } 8263 8264 SDValue SITargetLowering::performXorCombine(SDNode *N, 8265 DAGCombinerInfo &DCI) const { 8266 EVT VT = N->getValueType(0); 8267 if (VT != MVT::i64) 8268 return SDValue(); 8269 8270 SDValue LHS = N->getOperand(0); 8271 SDValue RHS = N->getOperand(1); 8272 8273 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8274 if (CRHS) { 8275 if (SDValue Split 8276 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8277 return Split; 8278 } 8279 8280 return SDValue(); 8281 } 8282 8283 // Instructions that will be lowered with a final instruction that zeros the 8284 // high result bits. 8285 // XXX - probably only need to list legal operations. 8286 static bool fp16SrcZerosHighBits(unsigned Opc) { 8287 switch (Opc) { 8288 case ISD::FADD: 8289 case ISD::FSUB: 8290 case ISD::FMUL: 8291 case ISD::FDIV: 8292 case ISD::FREM: 8293 case ISD::FMA: 8294 case ISD::FMAD: 8295 case ISD::FCANONICALIZE: 8296 case ISD::FP_ROUND: 8297 case ISD::UINT_TO_FP: 8298 case ISD::SINT_TO_FP: 8299 case ISD::FABS: 8300 // Fabs is lowered to a bit operation, but it's an and which will clear the 8301 // high bits anyway. 8302 case ISD::FSQRT: 8303 case ISD::FSIN: 8304 case ISD::FCOS: 8305 case ISD::FPOWI: 8306 case ISD::FPOW: 8307 case ISD::FLOG: 8308 case ISD::FLOG2: 8309 case ISD::FLOG10: 8310 case ISD::FEXP: 8311 case ISD::FEXP2: 8312 case ISD::FCEIL: 8313 case ISD::FTRUNC: 8314 case ISD::FRINT: 8315 case ISD::FNEARBYINT: 8316 case ISD::FROUND: 8317 case ISD::FFLOOR: 8318 case ISD::FMINNUM: 8319 case ISD::FMAXNUM: 8320 case AMDGPUISD::FRACT: 8321 case AMDGPUISD::CLAMP: 8322 case AMDGPUISD::COS_HW: 8323 case AMDGPUISD::SIN_HW: 8324 case AMDGPUISD::FMIN3: 8325 case AMDGPUISD::FMAX3: 8326 case AMDGPUISD::FMED3: 8327 case AMDGPUISD::FMAD_FTZ: 8328 case AMDGPUISD::RCP: 8329 case AMDGPUISD::RSQ: 8330 case AMDGPUISD::RCP_IFLAG: 8331 case AMDGPUISD::LDEXP: 8332 return true; 8333 default: 8334 // fcopysign, select and others may be lowered to 32-bit bit operations 8335 // which don't zero the high bits. 8336 return false; 8337 } 8338 } 8339 8340 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8341 DAGCombinerInfo &DCI) const { 8342 if (!Subtarget->has16BitInsts() || 8343 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8344 return SDValue(); 8345 8346 EVT VT = N->getValueType(0); 8347 if (VT != MVT::i32) 8348 return SDValue(); 8349 8350 SDValue Src = N->getOperand(0); 8351 if (Src.getValueType() != MVT::i16) 8352 return SDValue(); 8353 8354 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8355 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8356 if (Src.getOpcode() == ISD::BITCAST) { 8357 SDValue BCSrc = Src.getOperand(0); 8358 if (BCSrc.getValueType() == MVT::f16 && 8359 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8360 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8361 } 8362 8363 return SDValue(); 8364 } 8365 8366 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8367 DAGCombinerInfo &DCI) 8368 const { 8369 SDValue Src = N->getOperand(0); 8370 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8371 8372 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8373 VTSign->getVT() == MVT::i8) || 8374 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8375 VTSign->getVT() == MVT::i16)) && 8376 Src.hasOneUse()) { 8377 auto *M = cast<MemSDNode>(Src); 8378 SDValue Ops[] = { 8379 Src.getOperand(0), // Chain 8380 Src.getOperand(1), // rsrc 8381 Src.getOperand(2), // vindex 8382 Src.getOperand(3), // voffset 8383 Src.getOperand(4), // soffset 8384 Src.getOperand(5), // offset 8385 Src.getOperand(6), 8386 Src.getOperand(7) 8387 }; 8388 // replace with BUFFER_LOAD_BYTE/SHORT 8389 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8390 Src.getOperand(0).getValueType()); 8391 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8392 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8393 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8394 ResList, 8395 Ops, M->getMemoryVT(), 8396 M->getMemOperand()); 8397 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8398 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8399 } 8400 return SDValue(); 8401 } 8402 8403 SDValue SITargetLowering::performClassCombine(SDNode *N, 8404 DAGCombinerInfo &DCI) const { 8405 SelectionDAG &DAG = DCI.DAG; 8406 SDValue Mask = N->getOperand(1); 8407 8408 // fp_class x, 0 -> false 8409 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8410 if (CMask->isNullValue()) 8411 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8412 } 8413 8414 if (N->getOperand(0).isUndef()) 8415 return DAG.getUNDEF(MVT::i1); 8416 8417 return SDValue(); 8418 } 8419 8420 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8421 DAGCombinerInfo &DCI) const { 8422 EVT VT = N->getValueType(0); 8423 SDValue N0 = N->getOperand(0); 8424 8425 if (N0.isUndef()) 8426 return N0; 8427 8428 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8429 N0.getOpcode() == ISD::SINT_TO_FP)) { 8430 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8431 N->getFlags()); 8432 } 8433 8434 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8435 } 8436 8437 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8438 unsigned MaxDepth) const { 8439 unsigned Opcode = Op.getOpcode(); 8440 if (Opcode == ISD::FCANONICALIZE) 8441 return true; 8442 8443 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8444 auto F = CFP->getValueAPF(); 8445 if (F.isNaN() && F.isSignaling()) 8446 return false; 8447 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 8448 } 8449 8450 // If source is a result of another standard FP operation it is already in 8451 // canonical form. 8452 if (MaxDepth == 0) 8453 return false; 8454 8455 switch (Opcode) { 8456 // These will flush denorms if required. 8457 case ISD::FADD: 8458 case ISD::FSUB: 8459 case ISD::FMUL: 8460 case ISD::FCEIL: 8461 case ISD::FFLOOR: 8462 case ISD::FMA: 8463 case ISD::FMAD: 8464 case ISD::FSQRT: 8465 case ISD::FDIV: 8466 case ISD::FREM: 8467 case ISD::FP_ROUND: 8468 case ISD::FP_EXTEND: 8469 case AMDGPUISD::FMUL_LEGACY: 8470 case AMDGPUISD::FMAD_FTZ: 8471 case AMDGPUISD::RCP: 8472 case AMDGPUISD::RSQ: 8473 case AMDGPUISD::RSQ_CLAMP: 8474 case AMDGPUISD::RCP_LEGACY: 8475 case AMDGPUISD::RSQ_LEGACY: 8476 case AMDGPUISD::RCP_IFLAG: 8477 case AMDGPUISD::TRIG_PREOP: 8478 case AMDGPUISD::DIV_SCALE: 8479 case AMDGPUISD::DIV_FMAS: 8480 case AMDGPUISD::DIV_FIXUP: 8481 case AMDGPUISD::FRACT: 8482 case AMDGPUISD::LDEXP: 8483 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8484 case AMDGPUISD::CVT_F32_UBYTE0: 8485 case AMDGPUISD::CVT_F32_UBYTE1: 8486 case AMDGPUISD::CVT_F32_UBYTE2: 8487 case AMDGPUISD::CVT_F32_UBYTE3: 8488 return true; 8489 8490 // It can/will be lowered or combined as a bit operation. 8491 // Need to check their input recursively to handle. 8492 case ISD::FNEG: 8493 case ISD::FABS: 8494 case ISD::FCOPYSIGN: 8495 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8496 8497 case ISD::FSIN: 8498 case ISD::FCOS: 8499 case ISD::FSINCOS: 8500 return Op.getValueType().getScalarType() != MVT::f16; 8501 8502 case ISD::FMINNUM: 8503 case ISD::FMAXNUM: 8504 case ISD::FMINNUM_IEEE: 8505 case ISD::FMAXNUM_IEEE: 8506 case AMDGPUISD::CLAMP: 8507 case AMDGPUISD::FMED3: 8508 case AMDGPUISD::FMAX3: 8509 case AMDGPUISD::FMIN3: { 8510 // FIXME: Shouldn't treat the generic operations different based these. 8511 // However, we aren't really required to flush the result from 8512 // minnum/maxnum.. 8513 8514 // snans will be quieted, so we only need to worry about denormals. 8515 if (Subtarget->supportsMinMaxDenormModes() || 8516 denormalsEnabledForType(Op.getValueType())) 8517 return true; 8518 8519 // Flushing may be required. 8520 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8521 // targets need to check their input recursively. 8522 8523 // FIXME: Does this apply with clamp? It's implemented with max. 8524 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8525 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8526 return false; 8527 } 8528 8529 return true; 8530 } 8531 case ISD::SELECT: { 8532 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8533 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8534 } 8535 case ISD::BUILD_VECTOR: { 8536 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8537 SDValue SrcOp = Op.getOperand(i); 8538 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8539 return false; 8540 } 8541 8542 return true; 8543 } 8544 case ISD::EXTRACT_VECTOR_ELT: 8545 case ISD::EXTRACT_SUBVECTOR: { 8546 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8547 } 8548 case ISD::INSERT_VECTOR_ELT: { 8549 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8550 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8551 } 8552 case ISD::UNDEF: 8553 // Could be anything. 8554 return false; 8555 8556 case ISD::BITCAST: { 8557 // Hack round the mess we make when legalizing extract_vector_elt 8558 SDValue Src = Op.getOperand(0); 8559 if (Src.getValueType() == MVT::i16 && 8560 Src.getOpcode() == ISD::TRUNCATE) { 8561 SDValue TruncSrc = Src.getOperand(0); 8562 if (TruncSrc.getValueType() == MVT::i32 && 8563 TruncSrc.getOpcode() == ISD::BITCAST && 8564 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8565 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8566 } 8567 } 8568 8569 return false; 8570 } 8571 case ISD::INTRINSIC_WO_CHAIN: { 8572 unsigned IntrinsicID 8573 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8574 // TODO: Handle more intrinsics 8575 switch (IntrinsicID) { 8576 case Intrinsic::amdgcn_cvt_pkrtz: 8577 case Intrinsic::amdgcn_cubeid: 8578 case Intrinsic::amdgcn_frexp_mant: 8579 case Intrinsic::amdgcn_fdot2: 8580 return true; 8581 default: 8582 break; 8583 } 8584 8585 LLVM_FALLTHROUGH; 8586 } 8587 default: 8588 return denormalsEnabledForType(Op.getValueType()) && 8589 DAG.isKnownNeverSNaN(Op); 8590 } 8591 8592 llvm_unreachable("invalid operation"); 8593 } 8594 8595 // Constant fold canonicalize. 8596 SDValue SITargetLowering::getCanonicalConstantFP( 8597 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8598 // Flush denormals to 0 if not enabled. 8599 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8600 return DAG.getConstantFP(0.0, SL, VT); 8601 8602 if (C.isNaN()) { 8603 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8604 if (C.isSignaling()) { 8605 // Quiet a signaling NaN. 8606 // FIXME: Is this supposed to preserve payload bits? 8607 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8608 } 8609 8610 // Make sure it is the canonical NaN bitpattern. 8611 // 8612 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8613 // immediate? 8614 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8615 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8616 } 8617 8618 // Already canonical. 8619 return DAG.getConstantFP(C, SL, VT); 8620 } 8621 8622 static bool vectorEltWillFoldAway(SDValue Op) { 8623 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8624 } 8625 8626 SDValue SITargetLowering::performFCanonicalizeCombine( 8627 SDNode *N, 8628 DAGCombinerInfo &DCI) const { 8629 SelectionDAG &DAG = DCI.DAG; 8630 SDValue N0 = N->getOperand(0); 8631 EVT VT = N->getValueType(0); 8632 8633 // fcanonicalize undef -> qnan 8634 if (N0.isUndef()) { 8635 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8636 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8637 } 8638 8639 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8640 EVT VT = N->getValueType(0); 8641 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8642 } 8643 8644 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8645 // (fcanonicalize k) 8646 // 8647 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8648 8649 // TODO: This could be better with wider vectors that will be split to v2f16, 8650 // and to consider uses since there aren't that many packed operations. 8651 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8652 isTypeLegal(MVT::v2f16)) { 8653 SDLoc SL(N); 8654 SDValue NewElts[2]; 8655 SDValue Lo = N0.getOperand(0); 8656 SDValue Hi = N0.getOperand(1); 8657 EVT EltVT = Lo.getValueType(); 8658 8659 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8660 for (unsigned I = 0; I != 2; ++I) { 8661 SDValue Op = N0.getOperand(I); 8662 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8663 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8664 CFP->getValueAPF()); 8665 } else if (Op.isUndef()) { 8666 // Handled below based on what the other operand is. 8667 NewElts[I] = Op; 8668 } else { 8669 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8670 } 8671 } 8672 8673 // If one half is undef, and one is constant, perfer a splat vector rather 8674 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8675 // cheaper to use and may be free with a packed operation. 8676 if (NewElts[0].isUndef()) { 8677 if (isa<ConstantFPSDNode>(NewElts[1])) 8678 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8679 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8680 } 8681 8682 if (NewElts[1].isUndef()) { 8683 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8684 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8685 } 8686 8687 return DAG.getBuildVector(VT, SL, NewElts); 8688 } 8689 } 8690 8691 unsigned SrcOpc = N0.getOpcode(); 8692 8693 // If it's free to do so, push canonicalizes further up the source, which may 8694 // find a canonical source. 8695 // 8696 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8697 // sNaNs. 8698 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8699 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8700 if (CRHS && N0.hasOneUse()) { 8701 SDLoc SL(N); 8702 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8703 N0.getOperand(0)); 8704 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8705 DCI.AddToWorklist(Canon0.getNode()); 8706 8707 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8708 } 8709 } 8710 8711 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8712 } 8713 8714 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8715 switch (Opc) { 8716 case ISD::FMAXNUM: 8717 case ISD::FMAXNUM_IEEE: 8718 return AMDGPUISD::FMAX3; 8719 case ISD::SMAX: 8720 return AMDGPUISD::SMAX3; 8721 case ISD::UMAX: 8722 return AMDGPUISD::UMAX3; 8723 case ISD::FMINNUM: 8724 case ISD::FMINNUM_IEEE: 8725 return AMDGPUISD::FMIN3; 8726 case ISD::SMIN: 8727 return AMDGPUISD::SMIN3; 8728 case ISD::UMIN: 8729 return AMDGPUISD::UMIN3; 8730 default: 8731 llvm_unreachable("Not a min/max opcode"); 8732 } 8733 } 8734 8735 SDValue SITargetLowering::performIntMed3ImmCombine( 8736 SelectionDAG &DAG, const SDLoc &SL, 8737 SDValue Op0, SDValue Op1, bool Signed) const { 8738 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8739 if (!K1) 8740 return SDValue(); 8741 8742 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8743 if (!K0) 8744 return SDValue(); 8745 8746 if (Signed) { 8747 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8748 return SDValue(); 8749 } else { 8750 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8751 return SDValue(); 8752 } 8753 8754 EVT VT = K0->getValueType(0); 8755 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8756 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8757 return DAG.getNode(Med3Opc, SL, VT, 8758 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8759 } 8760 8761 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8762 MVT NVT = MVT::i32; 8763 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8764 8765 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8766 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8767 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8768 8769 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8770 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8771 } 8772 8773 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8774 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8775 return C; 8776 8777 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8778 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8779 return C; 8780 } 8781 8782 return nullptr; 8783 } 8784 8785 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8786 const SDLoc &SL, 8787 SDValue Op0, 8788 SDValue Op1) const { 8789 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8790 if (!K1) 8791 return SDValue(); 8792 8793 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8794 if (!K0) 8795 return SDValue(); 8796 8797 // Ordered >= (although NaN inputs should have folded away by now). 8798 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 8799 if (Cmp == APFloat::cmpGreaterThan) 8800 return SDValue(); 8801 8802 const MachineFunction &MF = DAG.getMachineFunction(); 8803 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8804 8805 // TODO: Check IEEE bit enabled? 8806 EVT VT = Op0.getValueType(); 8807 if (Info->getMode().DX10Clamp) { 8808 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 8809 // hardware fmed3 behavior converting to a min. 8810 // FIXME: Should this be allowing -0.0? 8811 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 8812 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 8813 } 8814 8815 // med3 for f16 is only available on gfx9+, and not available for v2f16. 8816 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 8817 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 8818 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 8819 // then give the other result, which is different from med3 with a NaN 8820 // input. 8821 SDValue Var = Op0.getOperand(0); 8822 if (!DAG.isKnownNeverSNaN(Var)) 8823 return SDValue(); 8824 8825 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8826 8827 if ((!K0->hasOneUse() || 8828 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 8829 (!K1->hasOneUse() || 8830 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 8831 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 8832 Var, SDValue(K0, 0), SDValue(K1, 0)); 8833 } 8834 } 8835 8836 return SDValue(); 8837 } 8838 8839 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 8840 DAGCombinerInfo &DCI) const { 8841 SelectionDAG &DAG = DCI.DAG; 8842 8843 EVT VT = N->getValueType(0); 8844 unsigned Opc = N->getOpcode(); 8845 SDValue Op0 = N->getOperand(0); 8846 SDValue Op1 = N->getOperand(1); 8847 8848 // Only do this if the inner op has one use since this will just increases 8849 // register pressure for no benefit. 8850 8851 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 8852 !VT.isVector() && 8853 (VT == MVT::i32 || VT == MVT::f32 || 8854 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 8855 // max(max(a, b), c) -> max3(a, b, c) 8856 // min(min(a, b), c) -> min3(a, b, c) 8857 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 8858 SDLoc DL(N); 8859 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8860 DL, 8861 N->getValueType(0), 8862 Op0.getOperand(0), 8863 Op0.getOperand(1), 8864 Op1); 8865 } 8866 8867 // Try commuted. 8868 // max(a, max(b, c)) -> max3(a, b, c) 8869 // min(a, min(b, c)) -> min3(a, b, c) 8870 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 8871 SDLoc DL(N); 8872 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8873 DL, 8874 N->getValueType(0), 8875 Op0, 8876 Op1.getOperand(0), 8877 Op1.getOperand(1)); 8878 } 8879 } 8880 8881 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 8882 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 8883 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 8884 return Med3; 8885 } 8886 8887 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 8888 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 8889 return Med3; 8890 } 8891 8892 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 8893 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 8894 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 8895 (Opc == AMDGPUISD::FMIN_LEGACY && 8896 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 8897 (VT == MVT::f32 || VT == MVT::f64 || 8898 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 8899 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 8900 Op0.hasOneUse()) { 8901 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 8902 return Res; 8903 } 8904 8905 return SDValue(); 8906 } 8907 8908 static bool isClampZeroToOne(SDValue A, SDValue B) { 8909 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 8910 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 8911 // FIXME: Should this be allowing -0.0? 8912 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 8913 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 8914 } 8915 } 8916 8917 return false; 8918 } 8919 8920 // FIXME: Should only worry about snans for version with chain. 8921 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 8922 DAGCombinerInfo &DCI) const { 8923 EVT VT = N->getValueType(0); 8924 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 8925 // NaNs. With a NaN input, the order of the operands may change the result. 8926 8927 SelectionDAG &DAG = DCI.DAG; 8928 SDLoc SL(N); 8929 8930 SDValue Src0 = N->getOperand(0); 8931 SDValue Src1 = N->getOperand(1); 8932 SDValue Src2 = N->getOperand(2); 8933 8934 if (isClampZeroToOne(Src0, Src1)) { 8935 // const_a, const_b, x -> clamp is safe in all cases including signaling 8936 // nans. 8937 // FIXME: Should this be allowing -0.0? 8938 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 8939 } 8940 8941 const MachineFunction &MF = DAG.getMachineFunction(); 8942 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8943 8944 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 8945 // handling no dx10-clamp? 8946 if (Info->getMode().DX10Clamp) { 8947 // If NaNs is clamped to 0, we are free to reorder the inputs. 8948 8949 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 8950 std::swap(Src0, Src1); 8951 8952 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 8953 std::swap(Src1, Src2); 8954 8955 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 8956 std::swap(Src0, Src1); 8957 8958 if (isClampZeroToOne(Src1, Src2)) 8959 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 8960 } 8961 8962 return SDValue(); 8963 } 8964 8965 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 8966 DAGCombinerInfo &DCI) const { 8967 SDValue Src0 = N->getOperand(0); 8968 SDValue Src1 = N->getOperand(1); 8969 if (Src0.isUndef() && Src1.isUndef()) 8970 return DCI.DAG.getUNDEF(N->getValueType(0)); 8971 return SDValue(); 8972 } 8973 8974 SDValue SITargetLowering::performExtractVectorEltCombine( 8975 SDNode *N, DAGCombinerInfo &DCI) const { 8976 SDValue Vec = N->getOperand(0); 8977 SelectionDAG &DAG = DCI.DAG; 8978 8979 EVT VecVT = Vec.getValueType(); 8980 EVT EltVT = VecVT.getVectorElementType(); 8981 8982 if ((Vec.getOpcode() == ISD::FNEG || 8983 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 8984 SDLoc SL(N); 8985 EVT EltVT = N->getValueType(0); 8986 SDValue Idx = N->getOperand(1); 8987 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 8988 Vec.getOperand(0), Idx); 8989 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 8990 } 8991 8992 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 8993 // => 8994 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 8995 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 8996 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 8997 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 8998 SDLoc SL(N); 8999 EVT EltVT = N->getValueType(0); 9000 SDValue Idx = N->getOperand(1); 9001 unsigned Opc = Vec.getOpcode(); 9002 9003 switch(Opc) { 9004 default: 9005 break; 9006 // TODO: Support other binary operations. 9007 case ISD::FADD: 9008 case ISD::FSUB: 9009 case ISD::FMUL: 9010 case ISD::ADD: 9011 case ISD::UMIN: 9012 case ISD::UMAX: 9013 case ISD::SMIN: 9014 case ISD::SMAX: 9015 case ISD::FMAXNUM: 9016 case ISD::FMINNUM: 9017 case ISD::FMAXNUM_IEEE: 9018 case ISD::FMINNUM_IEEE: { 9019 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9020 Vec.getOperand(0), Idx); 9021 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9022 Vec.getOperand(1), Idx); 9023 9024 DCI.AddToWorklist(Elt0.getNode()); 9025 DCI.AddToWorklist(Elt1.getNode()); 9026 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9027 } 9028 } 9029 } 9030 9031 unsigned VecSize = VecVT.getSizeInBits(); 9032 unsigned EltSize = EltVT.getSizeInBits(); 9033 9034 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9035 // This elminates non-constant index and subsequent movrel or scratch access. 9036 // Sub-dword vectors of size 2 dword or less have better implementation. 9037 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9038 // instructions. 9039 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9040 !isa<ConstantSDNode>(N->getOperand(1))) { 9041 SDLoc SL(N); 9042 SDValue Idx = N->getOperand(1); 9043 EVT IdxVT = Idx.getValueType(); 9044 SDValue V; 9045 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9046 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9047 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9048 if (I == 0) 9049 V = Elt; 9050 else 9051 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9052 } 9053 return V; 9054 } 9055 9056 if (!DCI.isBeforeLegalize()) 9057 return SDValue(); 9058 9059 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9060 // elements. This exposes more load reduction opportunities by replacing 9061 // multiple small extract_vector_elements with a single 32-bit extract. 9062 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9063 if (isa<MemSDNode>(Vec) && 9064 EltSize <= 16 && 9065 EltVT.isByteSized() && 9066 VecSize > 32 && 9067 VecSize % 32 == 0 && 9068 Idx) { 9069 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9070 9071 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9072 unsigned EltIdx = BitIndex / 32; 9073 unsigned LeftoverBitIdx = BitIndex % 32; 9074 SDLoc SL(N); 9075 9076 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9077 DCI.AddToWorklist(Cast.getNode()); 9078 9079 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9080 DAG.getConstant(EltIdx, SL, MVT::i32)); 9081 DCI.AddToWorklist(Elt.getNode()); 9082 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9083 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9084 DCI.AddToWorklist(Srl.getNode()); 9085 9086 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9087 DCI.AddToWorklist(Trunc.getNode()); 9088 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9089 } 9090 9091 return SDValue(); 9092 } 9093 9094 SDValue 9095 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9096 DAGCombinerInfo &DCI) const { 9097 SDValue Vec = N->getOperand(0); 9098 SDValue Idx = N->getOperand(2); 9099 EVT VecVT = Vec.getValueType(); 9100 EVT EltVT = VecVT.getVectorElementType(); 9101 unsigned VecSize = VecVT.getSizeInBits(); 9102 unsigned EltSize = EltVT.getSizeInBits(); 9103 9104 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9105 // => BUILD_VECTOR n x select (e, const-idx) 9106 // This elminates non-constant index and subsequent movrel or scratch access. 9107 // Sub-dword vectors of size 2 dword or less have better implementation. 9108 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9109 // instructions. 9110 if (isa<ConstantSDNode>(Idx) || 9111 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9112 return SDValue(); 9113 9114 SelectionDAG &DAG = DCI.DAG; 9115 SDLoc SL(N); 9116 SDValue Ins = N->getOperand(1); 9117 EVT IdxVT = Idx.getValueType(); 9118 9119 SmallVector<SDValue, 16> Ops; 9120 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9121 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9122 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9123 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9124 Ops.push_back(V); 9125 } 9126 9127 return DAG.getBuildVector(VecVT, SL, Ops); 9128 } 9129 9130 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9131 const SDNode *N0, 9132 const SDNode *N1) const { 9133 EVT VT = N0->getValueType(0); 9134 9135 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9136 // support denormals ever. 9137 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 9138 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() && 9139 getSubtarget()->hasMadF16())) && 9140 isOperationLegal(ISD::FMAD, VT)) 9141 return ISD::FMAD; 9142 9143 const TargetOptions &Options = DAG.getTarget().Options; 9144 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9145 (N0->getFlags().hasAllowContract() && 9146 N1->getFlags().hasAllowContract())) && 9147 isFMAFasterThanFMulAndFAdd(VT)) { 9148 return ISD::FMA; 9149 } 9150 9151 return 0; 9152 } 9153 9154 // For a reassociatable opcode perform: 9155 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9156 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9157 SelectionDAG &DAG) const { 9158 EVT VT = N->getValueType(0); 9159 if (VT != MVT::i32 && VT != MVT::i64) 9160 return SDValue(); 9161 9162 unsigned Opc = N->getOpcode(); 9163 SDValue Op0 = N->getOperand(0); 9164 SDValue Op1 = N->getOperand(1); 9165 9166 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9167 return SDValue(); 9168 9169 if (Op0->isDivergent()) 9170 std::swap(Op0, Op1); 9171 9172 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9173 return SDValue(); 9174 9175 SDValue Op2 = Op1.getOperand(1); 9176 Op1 = Op1.getOperand(0); 9177 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9178 return SDValue(); 9179 9180 if (Op1->isDivergent()) 9181 std::swap(Op1, Op2); 9182 9183 // If either operand is constant this will conflict with 9184 // DAGCombiner::ReassociateOps(). 9185 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9186 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9187 return SDValue(); 9188 9189 SDLoc SL(N); 9190 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9191 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9192 } 9193 9194 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9195 EVT VT, 9196 SDValue N0, SDValue N1, SDValue N2, 9197 bool Signed) { 9198 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9199 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9200 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9201 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9202 } 9203 9204 SDValue SITargetLowering::performAddCombine(SDNode *N, 9205 DAGCombinerInfo &DCI) const { 9206 SelectionDAG &DAG = DCI.DAG; 9207 EVT VT = N->getValueType(0); 9208 SDLoc SL(N); 9209 SDValue LHS = N->getOperand(0); 9210 SDValue RHS = N->getOperand(1); 9211 9212 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9213 && Subtarget->hasMad64_32() && 9214 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9215 VT.getScalarSizeInBits() <= 64) { 9216 if (LHS.getOpcode() != ISD::MUL) 9217 std::swap(LHS, RHS); 9218 9219 SDValue MulLHS = LHS.getOperand(0); 9220 SDValue MulRHS = LHS.getOperand(1); 9221 SDValue AddRHS = RHS; 9222 9223 // TODO: Maybe restrict if SGPR inputs. 9224 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9225 numBitsUnsigned(MulRHS, DAG) <= 32) { 9226 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9227 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9228 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9229 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9230 } 9231 9232 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9233 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9234 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9235 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9236 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9237 } 9238 9239 return SDValue(); 9240 } 9241 9242 if (SDValue V = reassociateScalarOps(N, DAG)) { 9243 return V; 9244 } 9245 9246 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9247 return SDValue(); 9248 9249 // add x, zext (setcc) => addcarry x, 0, setcc 9250 // add x, sext (setcc) => subcarry x, 0, setcc 9251 unsigned Opc = LHS.getOpcode(); 9252 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9253 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9254 std::swap(RHS, LHS); 9255 9256 Opc = RHS.getOpcode(); 9257 switch (Opc) { 9258 default: break; 9259 case ISD::ZERO_EXTEND: 9260 case ISD::SIGN_EXTEND: 9261 case ISD::ANY_EXTEND: { 9262 auto Cond = RHS.getOperand(0); 9263 if (!isBoolSGPR(Cond)) 9264 break; 9265 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9266 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9267 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9268 return DAG.getNode(Opc, SL, VTList, Args); 9269 } 9270 case ISD::ADDCARRY: { 9271 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9272 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9273 if (!C || C->getZExtValue() != 0) break; 9274 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9275 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9276 } 9277 } 9278 return SDValue(); 9279 } 9280 9281 SDValue SITargetLowering::performSubCombine(SDNode *N, 9282 DAGCombinerInfo &DCI) const { 9283 SelectionDAG &DAG = DCI.DAG; 9284 EVT VT = N->getValueType(0); 9285 9286 if (VT != MVT::i32) 9287 return SDValue(); 9288 9289 SDLoc SL(N); 9290 SDValue LHS = N->getOperand(0); 9291 SDValue RHS = N->getOperand(1); 9292 9293 if (LHS.getOpcode() == ISD::SUBCARRY) { 9294 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9295 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9296 if (!C || !C->isNullValue()) 9297 return SDValue(); 9298 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9299 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9300 } 9301 return SDValue(); 9302 } 9303 9304 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9305 DAGCombinerInfo &DCI) const { 9306 9307 if (N->getValueType(0) != MVT::i32) 9308 return SDValue(); 9309 9310 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9311 if (!C || C->getZExtValue() != 0) 9312 return SDValue(); 9313 9314 SelectionDAG &DAG = DCI.DAG; 9315 SDValue LHS = N->getOperand(0); 9316 9317 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9318 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9319 unsigned LHSOpc = LHS.getOpcode(); 9320 unsigned Opc = N->getOpcode(); 9321 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9322 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9323 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9324 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9325 } 9326 return SDValue(); 9327 } 9328 9329 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9330 DAGCombinerInfo &DCI) const { 9331 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9332 return SDValue(); 9333 9334 SelectionDAG &DAG = DCI.DAG; 9335 EVT VT = N->getValueType(0); 9336 9337 SDLoc SL(N); 9338 SDValue LHS = N->getOperand(0); 9339 SDValue RHS = N->getOperand(1); 9340 9341 // These should really be instruction patterns, but writing patterns with 9342 // source modiifiers is a pain. 9343 9344 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9345 if (LHS.getOpcode() == ISD::FADD) { 9346 SDValue A = LHS.getOperand(0); 9347 if (A == LHS.getOperand(1)) { 9348 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9349 if (FusedOp != 0) { 9350 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9351 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9352 } 9353 } 9354 } 9355 9356 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9357 if (RHS.getOpcode() == ISD::FADD) { 9358 SDValue A = RHS.getOperand(0); 9359 if (A == RHS.getOperand(1)) { 9360 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9361 if (FusedOp != 0) { 9362 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9363 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9364 } 9365 } 9366 } 9367 9368 return SDValue(); 9369 } 9370 9371 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9372 DAGCombinerInfo &DCI) const { 9373 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9374 return SDValue(); 9375 9376 SelectionDAG &DAG = DCI.DAG; 9377 SDLoc SL(N); 9378 EVT VT = N->getValueType(0); 9379 assert(!VT.isVector()); 9380 9381 // Try to get the fneg to fold into the source modifier. This undoes generic 9382 // DAG combines and folds them into the mad. 9383 // 9384 // Only do this if we are not trying to support denormals. v_mad_f32 does 9385 // not support denormals ever. 9386 SDValue LHS = N->getOperand(0); 9387 SDValue RHS = N->getOperand(1); 9388 if (LHS.getOpcode() == ISD::FADD) { 9389 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9390 SDValue A = LHS.getOperand(0); 9391 if (A == LHS.getOperand(1)) { 9392 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9393 if (FusedOp != 0){ 9394 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9395 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9396 9397 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9398 } 9399 } 9400 } 9401 9402 if (RHS.getOpcode() == ISD::FADD) { 9403 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9404 9405 SDValue A = RHS.getOperand(0); 9406 if (A == RHS.getOperand(1)) { 9407 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9408 if (FusedOp != 0){ 9409 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9410 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9411 } 9412 } 9413 } 9414 9415 return SDValue(); 9416 } 9417 9418 SDValue SITargetLowering::performFMACombine(SDNode *N, 9419 DAGCombinerInfo &DCI) const { 9420 SelectionDAG &DAG = DCI.DAG; 9421 EVT VT = N->getValueType(0); 9422 SDLoc SL(N); 9423 9424 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9425 return SDValue(); 9426 9427 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9428 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9429 SDValue Op1 = N->getOperand(0); 9430 SDValue Op2 = N->getOperand(1); 9431 SDValue FMA = N->getOperand(2); 9432 9433 if (FMA.getOpcode() != ISD::FMA || 9434 Op1.getOpcode() != ISD::FP_EXTEND || 9435 Op2.getOpcode() != ISD::FP_EXTEND) 9436 return SDValue(); 9437 9438 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9439 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9440 // is sufficient to allow generaing fdot2. 9441 const TargetOptions &Options = DAG.getTarget().Options; 9442 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9443 (N->getFlags().hasAllowContract() && 9444 FMA->getFlags().hasAllowContract())) { 9445 Op1 = Op1.getOperand(0); 9446 Op2 = Op2.getOperand(0); 9447 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9448 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9449 return SDValue(); 9450 9451 SDValue Vec1 = Op1.getOperand(0); 9452 SDValue Idx1 = Op1.getOperand(1); 9453 SDValue Vec2 = Op2.getOperand(0); 9454 9455 SDValue FMAOp1 = FMA.getOperand(0); 9456 SDValue FMAOp2 = FMA.getOperand(1); 9457 SDValue FMAAcc = FMA.getOperand(2); 9458 9459 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9460 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9461 return SDValue(); 9462 9463 FMAOp1 = FMAOp1.getOperand(0); 9464 FMAOp2 = FMAOp2.getOperand(0); 9465 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9466 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9467 return SDValue(); 9468 9469 SDValue Vec3 = FMAOp1.getOperand(0); 9470 SDValue Vec4 = FMAOp2.getOperand(0); 9471 SDValue Idx2 = FMAOp1.getOperand(1); 9472 9473 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9474 // Idx1 and Idx2 cannot be the same. 9475 Idx1 == Idx2) 9476 return SDValue(); 9477 9478 if (Vec1 == Vec2 || Vec3 == Vec4) 9479 return SDValue(); 9480 9481 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9482 return SDValue(); 9483 9484 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9485 (Vec1 == Vec4 && Vec2 == Vec3)) { 9486 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9487 DAG.getTargetConstant(0, SL, MVT::i1)); 9488 } 9489 } 9490 return SDValue(); 9491 } 9492 9493 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9494 DAGCombinerInfo &DCI) const { 9495 SelectionDAG &DAG = DCI.DAG; 9496 SDLoc SL(N); 9497 9498 SDValue LHS = N->getOperand(0); 9499 SDValue RHS = N->getOperand(1); 9500 EVT VT = LHS.getValueType(); 9501 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9502 9503 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9504 if (!CRHS) { 9505 CRHS = dyn_cast<ConstantSDNode>(LHS); 9506 if (CRHS) { 9507 std::swap(LHS, RHS); 9508 CC = getSetCCSwappedOperands(CC); 9509 } 9510 } 9511 9512 if (CRHS) { 9513 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9514 isBoolSGPR(LHS.getOperand(0))) { 9515 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9516 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9517 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9518 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9519 if ((CRHS->isAllOnesValue() && 9520 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9521 (CRHS->isNullValue() && 9522 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9523 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9524 DAG.getConstant(-1, SL, MVT::i1)); 9525 if ((CRHS->isAllOnesValue() && 9526 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9527 (CRHS->isNullValue() && 9528 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9529 return LHS.getOperand(0); 9530 } 9531 9532 uint64_t CRHSVal = CRHS->getZExtValue(); 9533 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9534 LHS.getOpcode() == ISD::SELECT && 9535 isa<ConstantSDNode>(LHS.getOperand(1)) && 9536 isa<ConstantSDNode>(LHS.getOperand(2)) && 9537 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9538 isBoolSGPR(LHS.getOperand(0))) { 9539 // Given CT != FT: 9540 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9541 // setcc (select cc, CT, CF), CF, ne => cc 9542 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9543 // setcc (select cc, CT, CF), CT, eq => cc 9544 uint64_t CT = LHS.getConstantOperandVal(1); 9545 uint64_t CF = LHS.getConstantOperandVal(2); 9546 9547 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9548 (CT == CRHSVal && CC == ISD::SETNE)) 9549 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9550 DAG.getConstant(-1, SL, MVT::i1)); 9551 if ((CF == CRHSVal && CC == ISD::SETNE) || 9552 (CT == CRHSVal && CC == ISD::SETEQ)) 9553 return LHS.getOperand(0); 9554 } 9555 } 9556 9557 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9558 VT != MVT::f16)) 9559 return SDValue(); 9560 9561 // Match isinf/isfinite pattern 9562 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9563 // (fcmp one (fabs x), inf) -> (fp_class x, 9564 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9565 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9566 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9567 if (!CRHS) 9568 return SDValue(); 9569 9570 const APFloat &APF = CRHS->getValueAPF(); 9571 if (APF.isInfinity() && !APF.isNegative()) { 9572 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9573 SIInstrFlags::N_INFINITY; 9574 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9575 SIInstrFlags::P_ZERO | 9576 SIInstrFlags::N_NORMAL | 9577 SIInstrFlags::P_NORMAL | 9578 SIInstrFlags::N_SUBNORMAL | 9579 SIInstrFlags::P_SUBNORMAL; 9580 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9581 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9582 DAG.getConstant(Mask, SL, MVT::i32)); 9583 } 9584 } 9585 9586 return SDValue(); 9587 } 9588 9589 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9590 DAGCombinerInfo &DCI) const { 9591 SelectionDAG &DAG = DCI.DAG; 9592 SDLoc SL(N); 9593 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9594 9595 SDValue Src = N->getOperand(0); 9596 SDValue Srl = N->getOperand(0); 9597 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9598 Srl = Srl.getOperand(0); 9599 9600 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9601 if (Srl.getOpcode() == ISD::SRL) { 9602 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9603 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9604 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9605 9606 if (const ConstantSDNode *C = 9607 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9608 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9609 EVT(MVT::i32)); 9610 9611 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9612 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9613 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9614 MVT::f32, Srl); 9615 } 9616 } 9617 } 9618 9619 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9620 9621 KnownBits Known; 9622 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9623 !DCI.isBeforeLegalizeOps()); 9624 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9625 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9626 DCI.CommitTargetLoweringOpt(TLO); 9627 } 9628 9629 return SDValue(); 9630 } 9631 9632 SDValue SITargetLowering::performClampCombine(SDNode *N, 9633 DAGCombinerInfo &DCI) const { 9634 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9635 if (!CSrc) 9636 return SDValue(); 9637 9638 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9639 const APFloat &F = CSrc->getValueAPF(); 9640 APFloat Zero = APFloat::getZero(F.getSemantics()); 9641 APFloat::cmpResult Cmp0 = F.compare(Zero); 9642 if (Cmp0 == APFloat::cmpLessThan || 9643 (Cmp0 == APFloat::cmpUnordered && 9644 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9645 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9646 } 9647 9648 APFloat One(F.getSemantics(), "1.0"); 9649 APFloat::cmpResult Cmp1 = F.compare(One); 9650 if (Cmp1 == APFloat::cmpGreaterThan) 9651 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9652 9653 return SDValue(CSrc, 0); 9654 } 9655 9656 9657 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9658 DAGCombinerInfo &DCI) const { 9659 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9660 return SDValue(); 9661 switch (N->getOpcode()) { 9662 default: 9663 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9664 case ISD::ADD: 9665 return performAddCombine(N, DCI); 9666 case ISD::SUB: 9667 return performSubCombine(N, DCI); 9668 case ISD::ADDCARRY: 9669 case ISD::SUBCARRY: 9670 return performAddCarrySubCarryCombine(N, DCI); 9671 case ISD::FADD: 9672 return performFAddCombine(N, DCI); 9673 case ISD::FSUB: 9674 return performFSubCombine(N, DCI); 9675 case ISD::SETCC: 9676 return performSetCCCombine(N, DCI); 9677 case ISD::FMAXNUM: 9678 case ISD::FMINNUM: 9679 case ISD::FMAXNUM_IEEE: 9680 case ISD::FMINNUM_IEEE: 9681 case ISD::SMAX: 9682 case ISD::SMIN: 9683 case ISD::UMAX: 9684 case ISD::UMIN: 9685 case AMDGPUISD::FMIN_LEGACY: 9686 case AMDGPUISD::FMAX_LEGACY: 9687 return performMinMaxCombine(N, DCI); 9688 case ISD::FMA: 9689 return performFMACombine(N, DCI); 9690 case ISD::LOAD: { 9691 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9692 return Widended; 9693 LLVM_FALLTHROUGH; 9694 } 9695 case ISD::STORE: 9696 case ISD::ATOMIC_LOAD: 9697 case ISD::ATOMIC_STORE: 9698 case ISD::ATOMIC_CMP_SWAP: 9699 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9700 case ISD::ATOMIC_SWAP: 9701 case ISD::ATOMIC_LOAD_ADD: 9702 case ISD::ATOMIC_LOAD_SUB: 9703 case ISD::ATOMIC_LOAD_AND: 9704 case ISD::ATOMIC_LOAD_OR: 9705 case ISD::ATOMIC_LOAD_XOR: 9706 case ISD::ATOMIC_LOAD_NAND: 9707 case ISD::ATOMIC_LOAD_MIN: 9708 case ISD::ATOMIC_LOAD_MAX: 9709 case ISD::ATOMIC_LOAD_UMIN: 9710 case ISD::ATOMIC_LOAD_UMAX: 9711 case ISD::ATOMIC_LOAD_FADD: 9712 case AMDGPUISD::ATOMIC_INC: 9713 case AMDGPUISD::ATOMIC_DEC: 9714 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9715 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9716 if (DCI.isBeforeLegalize()) 9717 break; 9718 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9719 case ISD::AND: 9720 return performAndCombine(N, DCI); 9721 case ISD::OR: 9722 return performOrCombine(N, DCI); 9723 case ISD::XOR: 9724 return performXorCombine(N, DCI); 9725 case ISD::ZERO_EXTEND: 9726 return performZeroExtendCombine(N, DCI); 9727 case ISD::SIGN_EXTEND_INREG: 9728 return performSignExtendInRegCombine(N , DCI); 9729 case AMDGPUISD::FP_CLASS: 9730 return performClassCombine(N, DCI); 9731 case ISD::FCANONICALIZE: 9732 return performFCanonicalizeCombine(N, DCI); 9733 case AMDGPUISD::RCP: 9734 return performRcpCombine(N, DCI); 9735 case AMDGPUISD::FRACT: 9736 case AMDGPUISD::RSQ: 9737 case AMDGPUISD::RCP_LEGACY: 9738 case AMDGPUISD::RSQ_LEGACY: 9739 case AMDGPUISD::RCP_IFLAG: 9740 case AMDGPUISD::RSQ_CLAMP: 9741 case AMDGPUISD::LDEXP: { 9742 SDValue Src = N->getOperand(0); 9743 if (Src.isUndef()) 9744 return Src; 9745 break; 9746 } 9747 case ISD::SINT_TO_FP: 9748 case ISD::UINT_TO_FP: 9749 return performUCharToFloatCombine(N, DCI); 9750 case AMDGPUISD::CVT_F32_UBYTE0: 9751 case AMDGPUISD::CVT_F32_UBYTE1: 9752 case AMDGPUISD::CVT_F32_UBYTE2: 9753 case AMDGPUISD::CVT_F32_UBYTE3: 9754 return performCvtF32UByteNCombine(N, DCI); 9755 case AMDGPUISD::FMED3: 9756 return performFMed3Combine(N, DCI); 9757 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9758 return performCvtPkRTZCombine(N, DCI); 9759 case AMDGPUISD::CLAMP: 9760 return performClampCombine(N, DCI); 9761 case ISD::SCALAR_TO_VECTOR: { 9762 SelectionDAG &DAG = DCI.DAG; 9763 EVT VT = N->getValueType(0); 9764 9765 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9766 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9767 SDLoc SL(N); 9768 SDValue Src = N->getOperand(0); 9769 EVT EltVT = Src.getValueType(); 9770 if (EltVT == MVT::f16) 9771 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 9772 9773 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 9774 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 9775 } 9776 9777 break; 9778 } 9779 case ISD::EXTRACT_VECTOR_ELT: 9780 return performExtractVectorEltCombine(N, DCI); 9781 case ISD::INSERT_VECTOR_ELT: 9782 return performInsertVectorEltCombine(N, DCI); 9783 } 9784 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9785 } 9786 9787 /// Helper function for adjustWritemask 9788 static unsigned SubIdx2Lane(unsigned Idx) { 9789 switch (Idx) { 9790 default: return 0; 9791 case AMDGPU::sub0: return 0; 9792 case AMDGPU::sub1: return 1; 9793 case AMDGPU::sub2: return 2; 9794 case AMDGPU::sub3: return 3; 9795 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 9796 } 9797 } 9798 9799 /// Adjust the writemask of MIMG instructions 9800 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 9801 SelectionDAG &DAG) const { 9802 unsigned Opcode = Node->getMachineOpcode(); 9803 9804 // Subtract 1 because the vdata output is not a MachineSDNode operand. 9805 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 9806 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 9807 return Node; // not implemented for D16 9808 9809 SDNode *Users[5] = { nullptr }; 9810 unsigned Lane = 0; 9811 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 9812 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 9813 unsigned NewDmask = 0; 9814 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 9815 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 9816 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 9817 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 9818 unsigned TFCLane = 0; 9819 bool HasChain = Node->getNumValues() > 1; 9820 9821 if (OldDmask == 0) { 9822 // These are folded out, but on the chance it happens don't assert. 9823 return Node; 9824 } 9825 9826 unsigned OldBitsSet = countPopulation(OldDmask); 9827 // Work out which is the TFE/LWE lane if that is enabled. 9828 if (UsesTFC) { 9829 TFCLane = OldBitsSet; 9830 } 9831 9832 // Try to figure out the used register components 9833 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 9834 I != E; ++I) { 9835 9836 // Don't look at users of the chain. 9837 if (I.getUse().getResNo() != 0) 9838 continue; 9839 9840 // Abort if we can't understand the usage 9841 if (!I->isMachineOpcode() || 9842 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 9843 return Node; 9844 9845 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 9846 // Note that subregs are packed, i.e. Lane==0 is the first bit set 9847 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 9848 // set, etc. 9849 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 9850 9851 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 9852 if (UsesTFC && Lane == TFCLane) { 9853 Users[Lane] = *I; 9854 } else { 9855 // Set which texture component corresponds to the lane. 9856 unsigned Comp; 9857 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 9858 Comp = countTrailingZeros(Dmask); 9859 Dmask &= ~(1 << Comp); 9860 } 9861 9862 // Abort if we have more than one user per component. 9863 if (Users[Lane]) 9864 return Node; 9865 9866 Users[Lane] = *I; 9867 NewDmask |= 1 << Comp; 9868 } 9869 } 9870 9871 // Don't allow 0 dmask, as hardware assumes one channel enabled. 9872 bool NoChannels = !NewDmask; 9873 if (NoChannels) { 9874 if (!UsesTFC) { 9875 // No uses of the result and not using TFC. Then do nothing. 9876 return Node; 9877 } 9878 // If the original dmask has one channel - then nothing to do 9879 if (OldBitsSet == 1) 9880 return Node; 9881 // Use an arbitrary dmask - required for the instruction to work 9882 NewDmask = 1; 9883 } 9884 // Abort if there's no change 9885 if (NewDmask == OldDmask) 9886 return Node; 9887 9888 unsigned BitsSet = countPopulation(NewDmask); 9889 9890 // Check for TFE or LWE - increase the number of channels by one to account 9891 // for the extra return value 9892 // This will need adjustment for D16 if this is also included in 9893 // adjustWriteMask (this function) but at present D16 are excluded. 9894 unsigned NewChannels = BitsSet + UsesTFC; 9895 9896 int NewOpcode = 9897 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 9898 assert(NewOpcode != -1 && 9899 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 9900 "failed to find equivalent MIMG op"); 9901 9902 // Adjust the writemask in the node 9903 SmallVector<SDValue, 12> Ops; 9904 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 9905 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 9906 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 9907 9908 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 9909 9910 MVT ResultVT = NewChannels == 1 ? 9911 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 9912 NewChannels == 5 ? 8 : NewChannels); 9913 SDVTList NewVTList = HasChain ? 9914 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 9915 9916 9917 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 9918 NewVTList, Ops); 9919 9920 if (HasChain) { 9921 // Update chain. 9922 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 9923 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 9924 } 9925 9926 if (NewChannels == 1) { 9927 assert(Node->hasNUsesOfValue(1, 0)); 9928 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 9929 SDLoc(Node), Users[Lane]->getValueType(0), 9930 SDValue(NewNode, 0)); 9931 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 9932 return nullptr; 9933 } 9934 9935 // Update the users of the node with the new indices 9936 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 9937 SDNode *User = Users[i]; 9938 if (!User) { 9939 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 9940 // Users[0] is still nullptr because channel 0 doesn't really have a use. 9941 if (i || !NoChannels) 9942 continue; 9943 } else { 9944 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 9945 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 9946 } 9947 9948 switch (Idx) { 9949 default: break; 9950 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 9951 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 9952 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 9953 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 9954 } 9955 } 9956 9957 DAG.RemoveDeadNode(Node); 9958 return nullptr; 9959 } 9960 9961 static bool isFrameIndexOp(SDValue Op) { 9962 if (Op.getOpcode() == ISD::AssertZext) 9963 Op = Op.getOperand(0); 9964 9965 return isa<FrameIndexSDNode>(Op); 9966 } 9967 9968 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 9969 /// with frame index operands. 9970 /// LLVM assumes that inputs are to these instructions are registers. 9971 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 9972 SelectionDAG &DAG) const { 9973 if (Node->getOpcode() == ISD::CopyToReg) { 9974 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 9975 SDValue SrcVal = Node->getOperand(2); 9976 9977 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 9978 // to try understanding copies to physical registers. 9979 if (SrcVal.getValueType() == MVT::i1 && 9980 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 9981 SDLoc SL(Node); 9982 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 9983 SDValue VReg = DAG.getRegister( 9984 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 9985 9986 SDNode *Glued = Node->getGluedNode(); 9987 SDValue ToVReg 9988 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 9989 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 9990 SDValue ToResultReg 9991 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 9992 VReg, ToVReg.getValue(1)); 9993 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 9994 DAG.RemoveDeadNode(Node); 9995 return ToResultReg.getNode(); 9996 } 9997 } 9998 9999 SmallVector<SDValue, 8> Ops; 10000 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10001 if (!isFrameIndexOp(Node->getOperand(i))) { 10002 Ops.push_back(Node->getOperand(i)); 10003 continue; 10004 } 10005 10006 SDLoc DL(Node); 10007 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10008 Node->getOperand(i).getValueType(), 10009 Node->getOperand(i)), 0)); 10010 } 10011 10012 return DAG.UpdateNodeOperands(Node, Ops); 10013 } 10014 10015 /// Fold the instructions after selecting them. 10016 /// Returns null if users were already updated. 10017 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10018 SelectionDAG &DAG) const { 10019 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10020 unsigned Opcode = Node->getMachineOpcode(); 10021 10022 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10023 !TII->isGather4(Opcode)) { 10024 return adjustWritemask(Node, DAG); 10025 } 10026 10027 if (Opcode == AMDGPU::INSERT_SUBREG || 10028 Opcode == AMDGPU::REG_SEQUENCE) { 10029 legalizeTargetIndependentNode(Node, DAG); 10030 return Node; 10031 } 10032 10033 switch (Opcode) { 10034 case AMDGPU::V_DIV_SCALE_F32: 10035 case AMDGPU::V_DIV_SCALE_F64: { 10036 // Satisfy the operand register constraint when one of the inputs is 10037 // undefined. Ordinarily each undef value will have its own implicit_def of 10038 // a vreg, so force these to use a single register. 10039 SDValue Src0 = Node->getOperand(0); 10040 SDValue Src1 = Node->getOperand(1); 10041 SDValue Src2 = Node->getOperand(2); 10042 10043 if ((Src0.isMachineOpcode() && 10044 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10045 (Src0 == Src1 || Src0 == Src2)) 10046 break; 10047 10048 MVT VT = Src0.getValueType().getSimpleVT(); 10049 const TargetRegisterClass *RC = 10050 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10051 10052 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10053 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10054 10055 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10056 UndefReg, Src0, SDValue()); 10057 10058 // src0 must be the same register as src1 or src2, even if the value is 10059 // undefined, so make sure we don't violate this constraint. 10060 if (Src0.isMachineOpcode() && 10061 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10062 if (Src1.isMachineOpcode() && 10063 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10064 Src0 = Src1; 10065 else if (Src2.isMachineOpcode() && 10066 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10067 Src0 = Src2; 10068 else { 10069 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10070 Src0 = UndefReg; 10071 Src1 = UndefReg; 10072 } 10073 } else 10074 break; 10075 10076 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10077 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10078 Ops.push_back(Node->getOperand(I)); 10079 10080 Ops.push_back(ImpDef.getValue(1)); 10081 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10082 } 10083 case AMDGPU::V_PERMLANE16_B32: 10084 case AMDGPU::V_PERMLANEX16_B32: { 10085 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10086 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10087 if (!FI->getZExtValue() && !BC->getZExtValue()) 10088 break; 10089 SDValue VDstIn = Node->getOperand(6); 10090 if (VDstIn.isMachineOpcode() 10091 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10092 break; 10093 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10094 SDLoc(Node), MVT::i32); 10095 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10096 SDValue(BC, 0), Node->getOperand(3), 10097 Node->getOperand(4), Node->getOperand(5), 10098 SDValue(ImpDef, 0), Node->getOperand(7) }; 10099 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10100 } 10101 default: 10102 break; 10103 } 10104 10105 return Node; 10106 } 10107 10108 /// Assign the register class depending on the number of 10109 /// bits set in the writemask 10110 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10111 SDNode *Node) const { 10112 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10113 10114 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10115 10116 if (TII->isVOP3(MI.getOpcode())) { 10117 // Make sure constant bus requirements are respected. 10118 TII->legalizeOperandsVOP3(MRI, MI); 10119 return; 10120 } 10121 10122 // Replace unused atomics with the no return version. 10123 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10124 if (NoRetAtomicOp != -1) { 10125 if (!Node->hasAnyUseOfValue(0)) { 10126 MI.setDesc(TII->get(NoRetAtomicOp)); 10127 MI.RemoveOperand(0); 10128 return; 10129 } 10130 10131 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10132 // instruction, because the return type of these instructions is a vec2 of 10133 // the memory type, so it can be tied to the input operand. 10134 // This means these instructions always have a use, so we need to add a 10135 // special case to check if the atomic has only one extract_subreg use, 10136 // which itself has no uses. 10137 if ((Node->hasNUsesOfValue(1, 0) && 10138 Node->use_begin()->isMachineOpcode() && 10139 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10140 !Node->use_begin()->hasAnyUseOfValue(0))) { 10141 unsigned Def = MI.getOperand(0).getReg(); 10142 10143 // Change this into a noret atomic. 10144 MI.setDesc(TII->get(NoRetAtomicOp)); 10145 MI.RemoveOperand(0); 10146 10147 // If we only remove the def operand from the atomic instruction, the 10148 // extract_subreg will be left with a use of a vreg without a def. 10149 // So we need to insert an implicit_def to avoid machine verifier 10150 // errors. 10151 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10152 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10153 } 10154 return; 10155 } 10156 } 10157 10158 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10159 uint64_t Val) { 10160 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10161 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10162 } 10163 10164 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10165 const SDLoc &DL, 10166 SDValue Ptr) const { 10167 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10168 10169 // Build the half of the subregister with the constants before building the 10170 // full 128-bit register. If we are building multiple resource descriptors, 10171 // this will allow CSEing of the 2-component register. 10172 const SDValue Ops0[] = { 10173 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10174 buildSMovImm32(DAG, DL, 0), 10175 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10176 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10177 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10178 }; 10179 10180 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10181 MVT::v2i32, Ops0), 0); 10182 10183 // Combine the constants and the pointer. 10184 const SDValue Ops1[] = { 10185 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10186 Ptr, 10187 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10188 SubRegHi, 10189 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10190 }; 10191 10192 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10193 } 10194 10195 /// Return a resource descriptor with the 'Add TID' bit enabled 10196 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10197 /// of the resource descriptor) to create an offset, which is added to 10198 /// the resource pointer. 10199 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10200 SDValue Ptr, uint32_t RsrcDword1, 10201 uint64_t RsrcDword2And3) const { 10202 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10203 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10204 if (RsrcDword1) { 10205 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10206 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10207 0); 10208 } 10209 10210 SDValue DataLo = buildSMovImm32(DAG, DL, 10211 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10212 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10213 10214 const SDValue Ops[] = { 10215 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10216 PtrLo, 10217 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10218 PtrHi, 10219 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10220 DataLo, 10221 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10222 DataHi, 10223 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10224 }; 10225 10226 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10227 } 10228 10229 //===----------------------------------------------------------------------===// 10230 // SI Inline Assembly Support 10231 //===----------------------------------------------------------------------===// 10232 10233 std::pair<unsigned, const TargetRegisterClass *> 10234 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10235 StringRef Constraint, 10236 MVT VT) const { 10237 const TargetRegisterClass *RC = nullptr; 10238 if (Constraint.size() == 1) { 10239 switch (Constraint[0]) { 10240 default: 10241 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10242 case 's': 10243 case 'r': 10244 switch (VT.getSizeInBits()) { 10245 default: 10246 return std::make_pair(0U, nullptr); 10247 case 32: 10248 case 16: 10249 RC = &AMDGPU::SReg_32_XM0RegClass; 10250 break; 10251 case 64: 10252 RC = &AMDGPU::SGPR_64RegClass; 10253 break; 10254 case 96: 10255 RC = &AMDGPU::SReg_96RegClass; 10256 break; 10257 case 128: 10258 RC = &AMDGPU::SReg_128RegClass; 10259 break; 10260 case 160: 10261 RC = &AMDGPU::SReg_160RegClass; 10262 break; 10263 case 256: 10264 RC = &AMDGPU::SReg_256RegClass; 10265 break; 10266 case 512: 10267 RC = &AMDGPU::SReg_512RegClass; 10268 break; 10269 } 10270 break; 10271 case 'v': 10272 switch (VT.getSizeInBits()) { 10273 default: 10274 return std::make_pair(0U, nullptr); 10275 case 32: 10276 case 16: 10277 RC = &AMDGPU::VGPR_32RegClass; 10278 break; 10279 case 64: 10280 RC = &AMDGPU::VReg_64RegClass; 10281 break; 10282 case 96: 10283 RC = &AMDGPU::VReg_96RegClass; 10284 break; 10285 case 128: 10286 RC = &AMDGPU::VReg_128RegClass; 10287 break; 10288 case 160: 10289 RC = &AMDGPU::VReg_160RegClass; 10290 break; 10291 case 256: 10292 RC = &AMDGPU::VReg_256RegClass; 10293 break; 10294 case 512: 10295 RC = &AMDGPU::VReg_512RegClass; 10296 break; 10297 } 10298 break; 10299 } 10300 // We actually support i128, i16 and f16 as inline parameters 10301 // even if they are not reported as legal 10302 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10303 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10304 return std::make_pair(0U, RC); 10305 } 10306 10307 if (Constraint.size() > 1) { 10308 if (Constraint[1] == 'v') { 10309 RC = &AMDGPU::VGPR_32RegClass; 10310 } else if (Constraint[1] == 's') { 10311 RC = &AMDGPU::SGPR_32RegClass; 10312 } 10313 10314 if (RC) { 10315 uint32_t Idx; 10316 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10317 if (!Failed && Idx < RC->getNumRegs()) 10318 return std::make_pair(RC->getRegister(Idx), RC); 10319 } 10320 } 10321 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10322 } 10323 10324 SITargetLowering::ConstraintType 10325 SITargetLowering::getConstraintType(StringRef Constraint) const { 10326 if (Constraint.size() == 1) { 10327 switch (Constraint[0]) { 10328 default: break; 10329 case 's': 10330 case 'v': 10331 return C_RegisterClass; 10332 } 10333 } 10334 return TargetLowering::getConstraintType(Constraint); 10335 } 10336 10337 // Figure out which registers should be reserved for stack access. Only after 10338 // the function is legalized do we know all of the non-spill stack objects or if 10339 // calls are present. 10340 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10341 MachineRegisterInfo &MRI = MF.getRegInfo(); 10342 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10343 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10344 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10345 10346 if (Info->isEntryFunction()) { 10347 // Callable functions have fixed registers used for stack access. 10348 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10349 } 10350 10351 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10352 Info->getStackPtrOffsetReg())); 10353 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10354 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10355 10356 // We need to worry about replacing the default register with itself in case 10357 // of MIR testcases missing the MFI. 10358 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10359 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10360 10361 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10362 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10363 10364 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10365 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10366 Info->getScratchWaveOffsetReg()); 10367 } 10368 10369 Info->limitOccupancy(MF); 10370 10371 if (ST.isWave32() && !MF.empty()) { 10372 // Add VCC_HI def because many instructions marked as imp-use VCC where 10373 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10374 // having a use of undef. 10375 10376 const SIInstrInfo *TII = ST.getInstrInfo(); 10377 DebugLoc DL; 10378 10379 MachineBasicBlock &MBB = MF.front(); 10380 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10381 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10382 10383 for (auto &MBB : MF) { 10384 for (auto &MI : MBB) { 10385 TII->fixImplicitOperands(MI); 10386 } 10387 } 10388 } 10389 10390 TargetLoweringBase::finalizeLowering(MF); 10391 } 10392 10393 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10394 KnownBits &Known, 10395 const APInt &DemandedElts, 10396 const SelectionDAG &DAG, 10397 unsigned Depth) const { 10398 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10399 DAG, Depth); 10400 10401 // Set the high bits to zero based on the maximum allowed scratch size per 10402 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10403 // calculation won't overflow, so assume the sign bit is never set. 10404 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10405 } 10406 10407 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10408 const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10409 const unsigned CacheLineAlign = 6; // log2(64) 10410 10411 // Pre-GFX10 target did not benefit from loop alignment 10412 if (!ML || DisableLoopAlignment || 10413 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10414 getSubtarget()->hasInstFwdPrefetchBug()) 10415 return PrefAlign; 10416 10417 // On GFX10 I$ is 4 x 64 bytes cache lines. 10418 // By default prefetcher keeps one cache line behind and reads two ahead. 10419 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10420 // behind and one ahead. 10421 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10422 // If loop fits 64 bytes it always spans no more than two cache lines and 10423 // does not need an alignment. 10424 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10425 // Else if loop is less or equal 192 bytes we need two lines behind. 10426 10427 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10428 const MachineBasicBlock *Header = ML->getHeader(); 10429 if (Header->getAlignment() != PrefAlign) 10430 return Header->getAlignment(); // Already processed. 10431 10432 unsigned LoopSize = 0; 10433 for (const MachineBasicBlock *MBB : ML->blocks()) { 10434 // If inner loop block is aligned assume in average half of the alignment 10435 // size to be added as nops. 10436 if (MBB != Header) 10437 LoopSize += (1 << MBB->getAlignment()) / 2; 10438 10439 for (const MachineInstr &MI : *MBB) { 10440 LoopSize += TII->getInstSizeInBytes(MI); 10441 if (LoopSize > 192) 10442 return PrefAlign; 10443 } 10444 } 10445 10446 if (LoopSize <= 64) 10447 return PrefAlign; 10448 10449 if (LoopSize <= 128) 10450 return CacheLineAlign; 10451 10452 // If any of parent loops is surrounded by prefetch instructions do not 10453 // insert new for inner loop, which would reset parent's settings. 10454 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10455 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10456 auto I = Exit->getFirstNonDebugInstr(); 10457 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10458 return CacheLineAlign; 10459 } 10460 } 10461 10462 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10463 MachineBasicBlock *Exit = ML->getExitBlock(); 10464 10465 if (Pre && Exit) { 10466 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10467 TII->get(AMDGPU::S_INST_PREFETCH)) 10468 .addImm(1); // prefetch 2 lines behind PC 10469 10470 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10471 TII->get(AMDGPU::S_INST_PREFETCH)) 10472 .addImm(2); // prefetch 1 line behind PC 10473 } 10474 10475 return CacheLineAlign; 10476 } 10477 10478 LLVM_ATTRIBUTE_UNUSED 10479 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10480 assert(N->getOpcode() == ISD::CopyFromReg); 10481 do { 10482 // Follow the chain until we find an INLINEASM node. 10483 N = N->getOperand(0).getNode(); 10484 if (N->getOpcode() == ISD::INLINEASM || 10485 N->getOpcode() == ISD::INLINEASM_BR) 10486 return true; 10487 } while (N->getOpcode() == ISD::CopyFromReg); 10488 return false; 10489 } 10490 10491 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10492 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10493 { 10494 switch (N->getOpcode()) { 10495 case ISD::CopyFromReg: 10496 { 10497 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10498 const MachineFunction * MF = FLI->MF; 10499 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10500 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10501 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10502 unsigned Reg = R->getReg(); 10503 if (TRI.isPhysicalRegister(Reg)) 10504 return !TRI.isSGPRReg(MRI, Reg); 10505 10506 if (MRI.isLiveIn(Reg)) { 10507 // workitem.id.x workitem.id.y workitem.id.z 10508 // Any VGPR formal argument is also considered divergent 10509 if (!TRI.isSGPRReg(MRI, Reg)) 10510 return true; 10511 // Formal arguments of non-entry functions 10512 // are conservatively considered divergent 10513 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10514 return true; 10515 return false; 10516 } 10517 const Value *V = FLI->getValueFromVirtualReg(Reg); 10518 if (V) 10519 return KDA->isDivergent(V); 10520 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10521 return !TRI.isSGPRReg(MRI, Reg); 10522 } 10523 break; 10524 case ISD::LOAD: { 10525 const LoadSDNode *L = cast<LoadSDNode>(N); 10526 unsigned AS = L->getAddressSpace(); 10527 // A flat load may access private memory. 10528 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10529 } break; 10530 case ISD::CALLSEQ_END: 10531 return true; 10532 break; 10533 case ISD::INTRINSIC_WO_CHAIN: 10534 { 10535 10536 } 10537 return AMDGPU::isIntrinsicSourceOfDivergence( 10538 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10539 case ISD::INTRINSIC_W_CHAIN: 10540 return AMDGPU::isIntrinsicSourceOfDivergence( 10541 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10542 // In some cases intrinsics that are a source of divergence have been 10543 // lowered to AMDGPUISD so we also need to check those too. 10544 case AMDGPUISD::INTERP_MOV: 10545 case AMDGPUISD::INTERP_P1: 10546 case AMDGPUISD::INTERP_P2: 10547 return true; 10548 } 10549 return false; 10550 } 10551 10552 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 10553 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10554 case MVT::f32: 10555 return Subtarget->hasFP32Denormals(); 10556 case MVT::f64: 10557 return Subtarget->hasFP64Denormals(); 10558 case MVT::f16: 10559 return Subtarget->hasFP16Denormals(); 10560 default: 10561 return false; 10562 } 10563 } 10564 10565 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10566 const SelectionDAG &DAG, 10567 bool SNaN, 10568 unsigned Depth) const { 10569 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10570 const MachineFunction &MF = DAG.getMachineFunction(); 10571 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10572 10573 if (Info->getMode().DX10Clamp) 10574 return true; // Clamped to 0. 10575 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10576 } 10577 10578 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10579 SNaN, Depth); 10580 } 10581 10582 TargetLowering::AtomicExpansionKind 10583 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10584 switch (RMW->getOperation()) { 10585 case AtomicRMWInst::FAdd: { 10586 Type *Ty = RMW->getType(); 10587 10588 // We don't have a way to support 16-bit atomics now, so just leave them 10589 // as-is. 10590 if (Ty->isHalfTy()) 10591 return AtomicExpansionKind::None; 10592 10593 if (!Ty->isFloatTy()) 10594 return AtomicExpansionKind::CmpXChg; 10595 10596 // TODO: Do have these for flat. Older targets also had them for buffers. 10597 unsigned AS = RMW->getPointerAddressSpace(); 10598 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10599 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10600 } 10601 default: 10602 break; 10603 } 10604 10605 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10606 } 10607