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::SGPR_128RegClass); 129 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 130 131 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_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 if (Subtarget->hasMAIInsts()) { 155 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 156 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 157 } 158 159 computeRegisterProperties(Subtarget->getRegisterInfo()); 160 161 // We need to custom lower vector stores from local memory 162 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 164 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 165 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 166 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 167 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 168 setOperationAction(ISD::LOAD, MVT::i1, Custom); 169 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 170 171 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 174 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 175 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 176 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 177 setOperationAction(ISD::STORE, MVT::i1, Custom); 178 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 179 180 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 181 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 182 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 183 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 184 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 185 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 186 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 187 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 188 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 189 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 190 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 191 192 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 193 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 194 195 setOperationAction(ISD::SELECT, MVT::i1, Promote); 196 setOperationAction(ISD::SELECT, MVT::i64, Custom); 197 setOperationAction(ISD::SELECT, MVT::f64, Promote); 198 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 199 200 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 201 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 202 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 203 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 204 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 205 206 setOperationAction(ISD::SETCC, MVT::i1, Promote); 207 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 208 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 209 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 210 211 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 212 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 213 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 219 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 220 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 221 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 222 223 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 224 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 225 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 226 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 227 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 228 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 229 230 setOperationAction(ISD::UADDO, MVT::i32, Legal); 231 setOperationAction(ISD::USUBO, MVT::i32, Legal); 232 233 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 234 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 235 236 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 237 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 238 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 239 240 #if 0 241 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 242 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 243 #endif 244 245 // We only support LOAD/STORE and vector manipulation ops for vectors 246 // with > 4 elements. 247 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 248 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 249 MVT::v32i32, MVT::v32f32 }) { 250 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 251 switch (Op) { 252 case ISD::LOAD: 253 case ISD::STORE: 254 case ISD::BUILD_VECTOR: 255 case ISD::BITCAST: 256 case ISD::EXTRACT_VECTOR_ELT: 257 case ISD::INSERT_VECTOR_ELT: 258 case ISD::INSERT_SUBVECTOR: 259 case ISD::EXTRACT_SUBVECTOR: 260 case ISD::SCALAR_TO_VECTOR: 261 break; 262 case ISD::CONCAT_VECTORS: 263 setOperationAction(Op, VT, Custom); 264 break; 265 default: 266 setOperationAction(Op, VT, Expand); 267 break; 268 } 269 } 270 } 271 272 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 273 274 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 275 // is expanded to avoid having two separate loops in case the index is a VGPR. 276 277 // Most operations are naturally 32-bit vector operations. We only support 278 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 279 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 280 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 281 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 282 283 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 284 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 285 286 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 287 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 288 289 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 290 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 291 } 292 293 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 294 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 295 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 296 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 297 298 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 299 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 300 301 // Avoid stack access for these. 302 // TODO: Generalize to more vector types. 303 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 304 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 305 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 306 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 307 308 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 309 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 310 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 311 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 312 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 313 314 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 315 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 316 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 317 318 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 319 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 321 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 322 323 // Deal with vec3 vector operations when widened to vec4. 324 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 325 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 326 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 327 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 328 329 // Deal with vec5 vector operations when widened to vec8. 330 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 331 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 332 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 333 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 334 335 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 336 // and output demarshalling 337 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 338 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 339 340 // We can't return success/failure, only the old value, 341 // let LLVM add the comparison 342 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 343 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 344 345 if (Subtarget->hasFlatAddressSpace()) { 346 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 347 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 348 } 349 350 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 351 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 352 353 // On SI this is s_memtime and s_memrealtime on VI. 354 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 355 setOperationAction(ISD::TRAP, MVT::Other, Custom); 356 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 357 358 if (Subtarget->has16BitInsts()) { 359 setOperationAction(ISD::FLOG, MVT::f16, Custom); 360 setOperationAction(ISD::FEXP, MVT::f16, Custom); 361 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 362 } 363 364 // v_mad_f32 does not support denormals according to some sources. 365 if (!Subtarget->hasFP32Denormals()) 366 setOperationAction(ISD::FMAD, MVT::f32, Legal); 367 368 if (!Subtarget->hasBFI()) { 369 // fcopysign can be done in a single instruction with BFI. 370 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 371 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 372 } 373 374 if (!Subtarget->hasBCNT(32)) 375 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 376 377 if (!Subtarget->hasBCNT(64)) 378 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 379 380 if (Subtarget->hasFFBH()) 381 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 382 383 if (Subtarget->hasFFBL()) 384 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 385 386 // We only really have 32-bit BFE instructions (and 16-bit on VI). 387 // 388 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 389 // effort to match them now. We want this to be false for i64 cases when the 390 // extraction isn't restricted to the upper or lower half. Ideally we would 391 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 392 // span the midpoint are probably relatively rare, so don't worry about them 393 // for now. 394 if (Subtarget->hasBFE()) 395 setHasExtractBitsInsn(true); 396 397 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 398 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 399 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 400 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 401 402 403 // These are really only legal for ieee_mode functions. We should be avoiding 404 // them for functions that don't have ieee_mode enabled, so just say they are 405 // legal. 406 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 407 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 408 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 409 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 410 411 412 if (Subtarget->haveRoundOpsF64()) { 413 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 414 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 415 setOperationAction(ISD::FRINT, MVT::f64, Legal); 416 } else { 417 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 418 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 419 setOperationAction(ISD::FRINT, MVT::f64, Custom); 420 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 421 } 422 423 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 424 425 setOperationAction(ISD::FSIN, MVT::f32, Custom); 426 setOperationAction(ISD::FCOS, MVT::f32, Custom); 427 setOperationAction(ISD::FDIV, MVT::f32, Custom); 428 setOperationAction(ISD::FDIV, MVT::f64, Custom); 429 430 if (Subtarget->has16BitInsts()) { 431 setOperationAction(ISD::Constant, MVT::i16, Legal); 432 433 setOperationAction(ISD::SMIN, MVT::i16, Legal); 434 setOperationAction(ISD::SMAX, MVT::i16, Legal); 435 436 setOperationAction(ISD::UMIN, MVT::i16, Legal); 437 setOperationAction(ISD::UMAX, MVT::i16, Legal); 438 439 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 440 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 441 442 setOperationAction(ISD::ROTR, MVT::i16, Promote); 443 setOperationAction(ISD::ROTL, MVT::i16, Promote); 444 445 setOperationAction(ISD::SDIV, MVT::i16, Promote); 446 setOperationAction(ISD::UDIV, MVT::i16, Promote); 447 setOperationAction(ISD::SREM, MVT::i16, Promote); 448 setOperationAction(ISD::UREM, MVT::i16, Promote); 449 450 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 451 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 452 453 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 454 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 455 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 456 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 457 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 458 459 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 460 461 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 462 463 setOperationAction(ISD::LOAD, MVT::i16, Custom); 464 465 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 466 467 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 468 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 469 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 470 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 471 472 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 473 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 474 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 475 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 476 477 // F16 - Constant Actions. 478 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 479 480 // F16 - Load/Store Actions. 481 setOperationAction(ISD::LOAD, MVT::f16, Promote); 482 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 483 setOperationAction(ISD::STORE, MVT::f16, Promote); 484 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 485 486 // F16 - VOP1 Actions. 487 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 488 setOperationAction(ISD::FCOS, MVT::f16, Promote); 489 setOperationAction(ISD::FSIN, MVT::f16, Promote); 490 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 491 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 492 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 493 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 494 setOperationAction(ISD::FROUND, MVT::f16, Custom); 495 496 // F16 - VOP2 Actions. 497 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 498 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 499 500 setOperationAction(ISD::FDIV, MVT::f16, Custom); 501 502 // F16 - VOP3 Actions. 503 setOperationAction(ISD::FMA, MVT::f16, Legal); 504 if (!Subtarget->hasFP16Denormals() && STI.hasMadF16()) 505 setOperationAction(ISD::FMAD, MVT::f16, Legal); 506 507 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 508 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 509 switch (Op) { 510 case ISD::LOAD: 511 case ISD::STORE: 512 case ISD::BUILD_VECTOR: 513 case ISD::BITCAST: 514 case ISD::EXTRACT_VECTOR_ELT: 515 case ISD::INSERT_VECTOR_ELT: 516 case ISD::INSERT_SUBVECTOR: 517 case ISD::EXTRACT_SUBVECTOR: 518 case ISD::SCALAR_TO_VECTOR: 519 break; 520 case ISD::CONCAT_VECTORS: 521 setOperationAction(Op, VT, Custom); 522 break; 523 default: 524 setOperationAction(Op, VT, Expand); 525 break; 526 } 527 } 528 } 529 530 // XXX - Do these do anything? Vector constants turn into build_vector. 531 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 532 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 533 534 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 535 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 536 537 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 538 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 539 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 540 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 541 542 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 543 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 544 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 545 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 546 547 setOperationAction(ISD::AND, MVT::v2i16, Promote); 548 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 549 setOperationAction(ISD::OR, MVT::v2i16, Promote); 550 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 551 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 552 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 553 554 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 555 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 556 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 557 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 558 559 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 560 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 561 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 562 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 563 564 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 565 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 566 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 567 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 568 569 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 570 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 571 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 572 573 if (!Subtarget->hasVOP3PInsts()) { 574 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 575 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 576 } 577 578 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 579 // This isn't really legal, but this avoids the legalizer unrolling it (and 580 // allows matching fneg (fabs x) patterns) 581 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 582 583 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 584 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 585 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 586 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 587 588 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 589 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 590 591 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 592 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 593 } 594 595 if (Subtarget->hasVOP3PInsts()) { 596 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 597 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 598 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 599 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 600 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 601 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 602 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 603 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 604 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 605 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 606 607 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 608 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 609 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 610 611 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 612 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 613 614 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 615 616 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 617 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 618 619 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 620 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 621 622 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 623 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 624 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 625 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 626 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 627 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 628 629 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 630 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 631 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 632 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 633 634 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 635 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 636 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 637 638 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 639 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 640 641 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 642 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 643 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 644 645 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 646 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 647 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 648 } 649 650 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 651 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 652 653 if (Subtarget->has16BitInsts()) { 654 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 655 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 656 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 657 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 658 } else { 659 // Legalization hack. 660 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 661 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 662 663 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 664 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 665 } 666 667 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 668 setOperationAction(ISD::SELECT, VT, Custom); 669 } 670 671 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 672 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 673 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 674 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 675 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 676 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 677 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 678 679 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 680 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 681 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 682 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 683 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 684 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 685 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 686 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 687 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 688 689 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 690 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 691 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 692 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 693 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 694 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 695 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 696 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 697 698 setTargetDAGCombine(ISD::ADD); 699 setTargetDAGCombine(ISD::ADDCARRY); 700 setTargetDAGCombine(ISD::SUB); 701 setTargetDAGCombine(ISD::SUBCARRY); 702 setTargetDAGCombine(ISD::FADD); 703 setTargetDAGCombine(ISD::FSUB); 704 setTargetDAGCombine(ISD::FMINNUM); 705 setTargetDAGCombine(ISD::FMAXNUM); 706 setTargetDAGCombine(ISD::FMINNUM_IEEE); 707 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 708 setTargetDAGCombine(ISD::FMA); 709 setTargetDAGCombine(ISD::SMIN); 710 setTargetDAGCombine(ISD::SMAX); 711 setTargetDAGCombine(ISD::UMIN); 712 setTargetDAGCombine(ISD::UMAX); 713 setTargetDAGCombine(ISD::SETCC); 714 setTargetDAGCombine(ISD::AND); 715 setTargetDAGCombine(ISD::OR); 716 setTargetDAGCombine(ISD::XOR); 717 setTargetDAGCombine(ISD::SINT_TO_FP); 718 setTargetDAGCombine(ISD::UINT_TO_FP); 719 setTargetDAGCombine(ISD::FCANONICALIZE); 720 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 721 setTargetDAGCombine(ISD::ZERO_EXTEND); 722 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 723 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 724 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 725 726 // All memory operations. Some folding on the pointer operand is done to help 727 // matching the constant offsets in the addressing modes. 728 setTargetDAGCombine(ISD::LOAD); 729 setTargetDAGCombine(ISD::STORE); 730 setTargetDAGCombine(ISD::ATOMIC_LOAD); 731 setTargetDAGCombine(ISD::ATOMIC_STORE); 732 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 733 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 734 setTargetDAGCombine(ISD::ATOMIC_SWAP); 735 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 736 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 737 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 738 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 739 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 740 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 741 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 742 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 743 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 744 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 745 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 746 747 setSchedulingPreference(Sched::RegPressure); 748 } 749 750 const GCNSubtarget *SITargetLowering::getSubtarget() const { 751 return Subtarget; 752 } 753 754 //===----------------------------------------------------------------------===// 755 // TargetLowering queries 756 //===----------------------------------------------------------------------===// 757 758 // v_mad_mix* support a conversion from f16 to f32. 759 // 760 // There is only one special case when denormals are enabled we don't currently, 761 // where this is OK to use. 762 bool SITargetLowering::isFPExtFoldable(unsigned Opcode, 763 EVT DestVT, EVT SrcVT) const { 764 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 765 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 766 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() && 767 SrcVT.getScalarType() == MVT::f16; 768 } 769 770 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 771 // SI has some legal vector types, but no legal vector operations. Say no 772 // shuffles are legal in order to prefer scalarizing some vector operations. 773 return false; 774 } 775 776 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 777 CallingConv::ID CC, 778 EVT VT) const { 779 if (CC == CallingConv::AMDGPU_KERNEL) 780 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 781 782 if (VT.isVector()) { 783 EVT ScalarVT = VT.getScalarType(); 784 unsigned Size = ScalarVT.getSizeInBits(); 785 if (Size == 32) 786 return ScalarVT.getSimpleVT(); 787 788 if (Size > 32) 789 return MVT::i32; 790 791 if (Size == 16 && Subtarget->has16BitInsts()) 792 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 793 } else if (VT.getSizeInBits() > 32) 794 return MVT::i32; 795 796 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 797 } 798 799 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 800 CallingConv::ID CC, 801 EVT VT) const { 802 if (CC == CallingConv::AMDGPU_KERNEL) 803 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 804 805 if (VT.isVector()) { 806 unsigned NumElts = VT.getVectorNumElements(); 807 EVT ScalarVT = VT.getScalarType(); 808 unsigned Size = ScalarVT.getSizeInBits(); 809 810 if (Size == 32) 811 return NumElts; 812 813 if (Size > 32) 814 return NumElts * ((Size + 31) / 32); 815 816 if (Size == 16 && Subtarget->has16BitInsts()) 817 return (NumElts + 1) / 2; 818 } else if (VT.getSizeInBits() > 32) 819 return (VT.getSizeInBits() + 31) / 32; 820 821 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 822 } 823 824 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 825 LLVMContext &Context, CallingConv::ID CC, 826 EVT VT, EVT &IntermediateVT, 827 unsigned &NumIntermediates, MVT &RegisterVT) const { 828 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 829 unsigned NumElts = VT.getVectorNumElements(); 830 EVT ScalarVT = VT.getScalarType(); 831 unsigned Size = ScalarVT.getSizeInBits(); 832 if (Size == 32) { 833 RegisterVT = ScalarVT.getSimpleVT(); 834 IntermediateVT = RegisterVT; 835 NumIntermediates = NumElts; 836 return NumIntermediates; 837 } 838 839 if (Size > 32) { 840 RegisterVT = MVT::i32; 841 IntermediateVT = RegisterVT; 842 NumIntermediates = NumElts * ((Size + 31) / 32); 843 return NumIntermediates; 844 } 845 846 // FIXME: We should fix the ABI to be the same on targets without 16-bit 847 // support, but unless we can properly handle 3-vectors, it will be still be 848 // inconsistent. 849 if (Size == 16 && Subtarget->has16BitInsts()) { 850 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 851 IntermediateVT = RegisterVT; 852 NumIntermediates = (NumElts + 1) / 2; 853 return NumIntermediates; 854 } 855 } 856 857 return TargetLowering::getVectorTypeBreakdownForCallingConv( 858 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 859 } 860 861 static MVT memVTFromAggregate(Type *Ty) { 862 // Only limited forms of aggregate type currently expected. 863 assert(Ty->isStructTy() && "Expected struct type"); 864 865 866 Type *ElementType = nullptr; 867 unsigned NumElts; 868 if (Ty->getContainedType(0)->isVectorTy()) { 869 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 870 ElementType = VecComponent->getElementType(); 871 NumElts = VecComponent->getNumElements(); 872 } else { 873 ElementType = Ty->getContainedType(0); 874 NumElts = 1; 875 } 876 877 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 878 879 // Calculate the size of the memVT type from the aggregate 880 unsigned Pow2Elts = 0; 881 unsigned ElementSize; 882 switch (ElementType->getTypeID()) { 883 default: 884 llvm_unreachable("Unknown type!"); 885 case Type::IntegerTyID: 886 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 887 break; 888 case Type::HalfTyID: 889 ElementSize = 16; 890 break; 891 case Type::FloatTyID: 892 ElementSize = 32; 893 break; 894 } 895 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 896 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 897 898 return MVT::getVectorVT(MVT::getVT(ElementType, false), 899 Pow2Elts); 900 } 901 902 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 903 const CallInst &CI, 904 MachineFunction &MF, 905 unsigned IntrID) const { 906 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 907 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 908 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 909 (Intrinsic::ID)IntrID); 910 if (Attr.hasFnAttribute(Attribute::ReadNone)) 911 return false; 912 913 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 914 915 if (RsrcIntr->IsImage) { 916 Info.ptrVal = MFI->getImagePSV( 917 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 918 CI.getArgOperand(RsrcIntr->RsrcArg)); 919 Info.align.reset(); 920 } else { 921 Info.ptrVal = MFI->getBufferPSV( 922 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 923 CI.getArgOperand(RsrcIntr->RsrcArg)); 924 } 925 926 Info.flags = MachineMemOperand::MODereferenceable; 927 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 928 Info.opc = ISD::INTRINSIC_W_CHAIN; 929 Info.memVT = MVT::getVT(CI.getType(), true); 930 if (Info.memVT == MVT::Other) { 931 // Some intrinsics return an aggregate type - special case to work out 932 // the correct memVT 933 Info.memVT = memVTFromAggregate(CI.getType()); 934 } 935 Info.flags |= MachineMemOperand::MOLoad; 936 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 937 Info.opc = ISD::INTRINSIC_VOID; 938 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 939 Info.flags |= MachineMemOperand::MOStore; 940 } else { 941 // Atomic 942 Info.opc = ISD::INTRINSIC_W_CHAIN; 943 Info.memVT = MVT::getVT(CI.getType()); 944 Info.flags = MachineMemOperand::MOLoad | 945 MachineMemOperand::MOStore | 946 MachineMemOperand::MODereferenceable; 947 948 // XXX - Should this be volatile without known ordering? 949 Info.flags |= MachineMemOperand::MOVolatile; 950 } 951 return true; 952 } 953 954 switch (IntrID) { 955 case Intrinsic::amdgcn_atomic_inc: 956 case Intrinsic::amdgcn_atomic_dec: 957 case Intrinsic::amdgcn_ds_ordered_add: 958 case Intrinsic::amdgcn_ds_ordered_swap: 959 case Intrinsic::amdgcn_ds_fadd: 960 case Intrinsic::amdgcn_ds_fmin: 961 case Intrinsic::amdgcn_ds_fmax: { 962 Info.opc = ISD::INTRINSIC_W_CHAIN; 963 Info.memVT = MVT::getVT(CI.getType()); 964 Info.ptrVal = CI.getOperand(0); 965 Info.align.reset(); 966 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 967 968 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 969 if (!Vol->isZero()) 970 Info.flags |= MachineMemOperand::MOVolatile; 971 972 return true; 973 } 974 case Intrinsic::amdgcn_buffer_atomic_fadd: { 975 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 976 977 Info.opc = ISD::INTRINSIC_VOID; 978 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 979 Info.ptrVal = MFI->getBufferPSV( 980 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 981 CI.getArgOperand(1)); 982 Info.align.reset(); 983 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 984 985 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 986 if (!Vol || !Vol->isZero()) 987 Info.flags |= MachineMemOperand::MOVolatile; 988 989 return true; 990 } 991 case Intrinsic::amdgcn_global_atomic_fadd: { 992 Info.opc = ISD::INTRINSIC_VOID; 993 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 994 ->getPointerElementType()); 995 Info.ptrVal = CI.getOperand(0); 996 Info.align.reset(); 997 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 998 999 return true; 1000 } 1001 case Intrinsic::amdgcn_ds_append: 1002 case Intrinsic::amdgcn_ds_consume: { 1003 Info.opc = ISD::INTRINSIC_W_CHAIN; 1004 Info.memVT = MVT::getVT(CI.getType()); 1005 Info.ptrVal = CI.getOperand(0); 1006 Info.align.reset(); 1007 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1008 1009 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1010 if (!Vol->isZero()) 1011 Info.flags |= MachineMemOperand::MOVolatile; 1012 1013 return true; 1014 } 1015 case Intrinsic::amdgcn_ds_gws_init: 1016 case Intrinsic::amdgcn_ds_gws_barrier: 1017 case Intrinsic::amdgcn_ds_gws_sema_v: 1018 case Intrinsic::amdgcn_ds_gws_sema_br: 1019 case Intrinsic::amdgcn_ds_gws_sema_p: 1020 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1021 Info.opc = ISD::INTRINSIC_VOID; 1022 1023 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1024 Info.ptrVal = 1025 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1026 1027 // This is an abstract access, but we need to specify a type and size. 1028 Info.memVT = MVT::i32; 1029 Info.size = 4; 1030 Info.align = Align(4); 1031 1032 Info.flags = MachineMemOperand::MOStore; 1033 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1034 Info.flags = MachineMemOperand::MOLoad; 1035 return true; 1036 } 1037 default: 1038 return false; 1039 } 1040 } 1041 1042 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1043 SmallVectorImpl<Value*> &Ops, 1044 Type *&AccessTy) const { 1045 switch (II->getIntrinsicID()) { 1046 case Intrinsic::amdgcn_atomic_inc: 1047 case Intrinsic::amdgcn_atomic_dec: 1048 case Intrinsic::amdgcn_ds_ordered_add: 1049 case Intrinsic::amdgcn_ds_ordered_swap: 1050 case Intrinsic::amdgcn_ds_fadd: 1051 case Intrinsic::amdgcn_ds_fmin: 1052 case Intrinsic::amdgcn_ds_fmax: { 1053 Value *Ptr = II->getArgOperand(0); 1054 AccessTy = II->getType(); 1055 Ops.push_back(Ptr); 1056 return true; 1057 } 1058 default: 1059 return false; 1060 } 1061 } 1062 1063 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1064 if (!Subtarget->hasFlatInstOffsets()) { 1065 // Flat instructions do not have offsets, and only have the register 1066 // address. 1067 return AM.BaseOffs == 0 && AM.Scale == 0; 1068 } 1069 1070 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 1071 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 1072 1073 // GFX10 shrinked signed offset to 12 bits. When using regular flat 1074 // instructions, the sign bit is also ignored and is treated as 11-bit 1075 // unsigned offset. 1076 1077 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 1078 return isUInt<11>(AM.BaseOffs) && AM.Scale == 0; 1079 1080 // Just r + i 1081 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 1082 } 1083 1084 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1085 if (Subtarget->hasFlatGlobalInsts()) 1086 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 1087 1088 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1089 // Assume the we will use FLAT for all global memory accesses 1090 // on VI. 1091 // FIXME: This assumption is currently wrong. On VI we still use 1092 // MUBUF instructions for the r + i addressing mode. As currently 1093 // implemented, the MUBUF instructions only work on buffer < 4GB. 1094 // It may be possible to support > 4GB buffers with MUBUF instructions, 1095 // by setting the stride value in the resource descriptor which would 1096 // increase the size limit to (stride * 4GB). However, this is risky, 1097 // because it has never been validated. 1098 return isLegalFlatAddressingMode(AM); 1099 } 1100 1101 return isLegalMUBUFAddressingMode(AM); 1102 } 1103 1104 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1105 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1106 // additionally can do r + r + i with addr64. 32-bit has more addressing 1107 // mode options. Depending on the resource constant, it can also do 1108 // (i64 r0) + (i32 r1) * (i14 i). 1109 // 1110 // Private arrays end up using a scratch buffer most of the time, so also 1111 // assume those use MUBUF instructions. Scratch loads / stores are currently 1112 // implemented as mubuf instructions with offen bit set, so slightly 1113 // different than the normal addr64. 1114 if (!isUInt<12>(AM.BaseOffs)) 1115 return false; 1116 1117 // FIXME: Since we can split immediate into soffset and immediate offset, 1118 // would it make sense to allow any immediate? 1119 1120 switch (AM.Scale) { 1121 case 0: // r + i or just i, depending on HasBaseReg. 1122 return true; 1123 case 1: 1124 return true; // We have r + r or r + i. 1125 case 2: 1126 if (AM.HasBaseReg) { 1127 // Reject 2 * r + r. 1128 return false; 1129 } 1130 1131 // Allow 2 * r as r + r 1132 // Or 2 * r + i is allowed as r + r + i. 1133 return true; 1134 default: // Don't allow n * r 1135 return false; 1136 } 1137 } 1138 1139 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1140 const AddrMode &AM, Type *Ty, 1141 unsigned AS, Instruction *I) const { 1142 // No global is ever allowed as a base. 1143 if (AM.BaseGV) 1144 return false; 1145 1146 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1147 return isLegalGlobalAddressingMode(AM); 1148 1149 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1150 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1151 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1152 // If the offset isn't a multiple of 4, it probably isn't going to be 1153 // correctly aligned. 1154 // FIXME: Can we get the real alignment here? 1155 if (AM.BaseOffs % 4 != 0) 1156 return isLegalMUBUFAddressingMode(AM); 1157 1158 // There are no SMRD extloads, so if we have to do a small type access we 1159 // will use a MUBUF load. 1160 // FIXME?: We also need to do this if unaligned, but we don't know the 1161 // alignment here. 1162 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1163 return isLegalGlobalAddressingMode(AM); 1164 1165 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1166 // SMRD instructions have an 8-bit, dword offset on SI. 1167 if (!isUInt<8>(AM.BaseOffs / 4)) 1168 return false; 1169 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1170 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1171 // in 8-bits, it can use a smaller encoding. 1172 if (!isUInt<32>(AM.BaseOffs / 4)) 1173 return false; 1174 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1175 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1176 if (!isUInt<20>(AM.BaseOffs)) 1177 return false; 1178 } else 1179 llvm_unreachable("unhandled generation"); 1180 1181 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1182 return true; 1183 1184 if (AM.Scale == 1 && AM.HasBaseReg) 1185 return true; 1186 1187 return false; 1188 1189 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1190 return isLegalMUBUFAddressingMode(AM); 1191 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1192 AS == AMDGPUAS::REGION_ADDRESS) { 1193 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1194 // field. 1195 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1196 // an 8-bit dword offset but we don't know the alignment here. 1197 if (!isUInt<16>(AM.BaseOffs)) 1198 return false; 1199 1200 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1201 return true; 1202 1203 if (AM.Scale == 1 && AM.HasBaseReg) 1204 return true; 1205 1206 return false; 1207 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1208 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1209 // For an unknown address space, this usually means that this is for some 1210 // reason being used for pure arithmetic, and not based on some addressing 1211 // computation. We don't have instructions that compute pointers with any 1212 // addressing modes, so treat them as having no offset like flat 1213 // instructions. 1214 return isLegalFlatAddressingMode(AM); 1215 } else { 1216 llvm_unreachable("unhandled address space"); 1217 } 1218 } 1219 1220 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1221 const SelectionDAG &DAG) const { 1222 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1223 return (MemVT.getSizeInBits() <= 4 * 32); 1224 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1225 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1226 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1227 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1228 return (MemVT.getSizeInBits() <= 2 * 32); 1229 } 1230 return true; 1231 } 1232 1233 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1234 unsigned Size, unsigned AddrSpace, unsigned Align, 1235 MachineMemOperand::Flags Flags, bool *IsFast) const { 1236 if (IsFast) 1237 *IsFast = false; 1238 1239 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1240 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1241 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1242 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1243 // with adjacent offsets. 1244 bool AlignedBy4 = (Align % 4 == 0); 1245 if (IsFast) 1246 *IsFast = AlignedBy4; 1247 1248 return AlignedBy4; 1249 } 1250 1251 // FIXME: We have to be conservative here and assume that flat operations 1252 // will access scratch. If we had access to the IR function, then we 1253 // could determine if any private memory was used in the function. 1254 if (!Subtarget->hasUnalignedScratchAccess() && 1255 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1256 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1257 bool AlignedBy4 = Align >= 4; 1258 if (IsFast) 1259 *IsFast = AlignedBy4; 1260 1261 return AlignedBy4; 1262 } 1263 1264 if (Subtarget->hasUnalignedBufferAccess()) { 1265 // If we have an uniform constant load, it still requires using a slow 1266 // buffer instruction if unaligned. 1267 if (IsFast) { 1268 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1269 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1270 (Align % 4 == 0) : true; 1271 } 1272 1273 return true; 1274 } 1275 1276 // Smaller than dword value must be aligned. 1277 if (Size < 32) 1278 return false; 1279 1280 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1281 // byte-address are ignored, thus forcing Dword alignment. 1282 // This applies to private, global, and constant memory. 1283 if (IsFast) 1284 *IsFast = true; 1285 1286 return Size >= 32 && Align >= 4; 1287 } 1288 1289 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1290 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1291 bool *IsFast) const { 1292 if (IsFast) 1293 *IsFast = false; 1294 1295 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1296 // which isn't a simple VT. 1297 // Until MVT is extended to handle this, simply check for the size and 1298 // rely on the condition below: allow accesses if the size is a multiple of 4. 1299 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1300 VT.getStoreSize() > 16)) { 1301 return false; 1302 } 1303 1304 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1305 Align, Flags, IsFast); 1306 } 1307 1308 EVT SITargetLowering::getOptimalMemOpType( 1309 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1310 bool ZeroMemset, bool MemcpyStrSrc, 1311 const AttributeList &FuncAttributes) const { 1312 // FIXME: Should account for address space here. 1313 1314 // The default fallback uses the private pointer size as a guess for a type to 1315 // use. Make sure we switch these to 64-bit accesses. 1316 1317 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1318 return MVT::v4i32; 1319 1320 if (Size >= 8 && DstAlign >= 4) 1321 return MVT::v2i32; 1322 1323 // Use the default. 1324 return MVT::Other; 1325 } 1326 1327 static bool isFlatGlobalAddrSpace(unsigned AS) { 1328 return AS == AMDGPUAS::GLOBAL_ADDRESS || 1329 AS == AMDGPUAS::FLAT_ADDRESS || 1330 AS == AMDGPUAS::CONSTANT_ADDRESS || 1331 AS > AMDGPUAS::MAX_AMDGPU_ADDRESS; 1332 } 1333 1334 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1335 unsigned DestAS) const { 1336 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1337 } 1338 1339 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1340 const MemSDNode *MemNode = cast<MemSDNode>(N); 1341 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1342 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1343 return I && I->getMetadata("amdgpu.noclobber"); 1344 } 1345 1346 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1347 unsigned DestAS) const { 1348 // Flat -> private/local is a simple truncate. 1349 // Flat -> global is no-op 1350 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1351 return true; 1352 1353 return isNoopAddrSpaceCast(SrcAS, DestAS); 1354 } 1355 1356 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1357 const MemSDNode *MemNode = cast<MemSDNode>(N); 1358 1359 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1360 } 1361 1362 TargetLoweringBase::LegalizeTypeAction 1363 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1364 int NumElts = VT.getVectorNumElements(); 1365 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1366 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1367 return TargetLoweringBase::getPreferredVectorAction(VT); 1368 } 1369 1370 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1371 Type *Ty) const { 1372 // FIXME: Could be smarter if called for vector constants. 1373 return true; 1374 } 1375 1376 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1377 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1378 switch (Op) { 1379 case ISD::LOAD: 1380 case ISD::STORE: 1381 1382 // These operations are done with 32-bit instructions anyway. 1383 case ISD::AND: 1384 case ISD::OR: 1385 case ISD::XOR: 1386 case ISD::SELECT: 1387 // TODO: Extensions? 1388 return true; 1389 default: 1390 return false; 1391 } 1392 } 1393 1394 // SimplifySetCC uses this function to determine whether or not it should 1395 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1396 if (VT == MVT::i1 && Op == ISD::SETCC) 1397 return false; 1398 1399 return TargetLowering::isTypeDesirableForOp(Op, VT); 1400 } 1401 1402 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1403 const SDLoc &SL, 1404 SDValue Chain, 1405 uint64_t Offset) const { 1406 const DataLayout &DL = DAG.getDataLayout(); 1407 MachineFunction &MF = DAG.getMachineFunction(); 1408 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1409 1410 const ArgDescriptor *InputPtrReg; 1411 const TargetRegisterClass *RC; 1412 1413 std::tie(InputPtrReg, RC) 1414 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1415 1416 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1417 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1418 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1419 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1420 1421 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1422 } 1423 1424 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1425 const SDLoc &SL) const { 1426 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1427 FIRST_IMPLICIT); 1428 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1429 } 1430 1431 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1432 const SDLoc &SL, SDValue Val, 1433 bool Signed, 1434 const ISD::InputArg *Arg) const { 1435 // First, if it is a widened vector, narrow it. 1436 if (VT.isVector() && 1437 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1438 EVT NarrowedVT = 1439 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1440 VT.getVectorNumElements()); 1441 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1442 DAG.getConstant(0, SL, MVT::i32)); 1443 } 1444 1445 // Then convert the vector elements or scalar value. 1446 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1447 VT.bitsLT(MemVT)) { 1448 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1449 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1450 } 1451 1452 if (MemVT.isFloatingPoint()) 1453 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1454 else if (Signed) 1455 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1456 else 1457 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1458 1459 return Val; 1460 } 1461 1462 SDValue SITargetLowering::lowerKernargMemParameter( 1463 SelectionDAG &DAG, EVT VT, EVT MemVT, 1464 const SDLoc &SL, SDValue Chain, 1465 uint64_t Offset, unsigned Align, bool Signed, 1466 const ISD::InputArg *Arg) const { 1467 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1468 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1469 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1470 1471 // Try to avoid using an extload by loading earlier than the argument address, 1472 // and extracting the relevant bits. The load should hopefully be merged with 1473 // the previous argument. 1474 if (MemVT.getStoreSize() < 4 && Align < 4) { 1475 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1476 int64_t AlignDownOffset = alignDown(Offset, 4); 1477 int64_t OffsetDiff = Offset - AlignDownOffset; 1478 1479 EVT IntVT = MemVT.changeTypeToInteger(); 1480 1481 // TODO: If we passed in the base kernel offset we could have a better 1482 // alignment than 4, but we don't really need it. 1483 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1484 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1485 MachineMemOperand::MODereferenceable | 1486 MachineMemOperand::MOInvariant); 1487 1488 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1489 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1490 1491 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1492 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1493 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1494 1495 1496 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1497 } 1498 1499 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1500 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1501 MachineMemOperand::MODereferenceable | 1502 MachineMemOperand::MOInvariant); 1503 1504 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1505 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1506 } 1507 1508 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1509 const SDLoc &SL, SDValue Chain, 1510 const ISD::InputArg &Arg) const { 1511 MachineFunction &MF = DAG.getMachineFunction(); 1512 MachineFrameInfo &MFI = MF.getFrameInfo(); 1513 1514 if (Arg.Flags.isByVal()) { 1515 unsigned Size = Arg.Flags.getByValSize(); 1516 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1517 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1518 } 1519 1520 unsigned ArgOffset = VA.getLocMemOffset(); 1521 unsigned ArgSize = VA.getValVT().getStoreSize(); 1522 1523 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1524 1525 // Create load nodes to retrieve arguments from the stack. 1526 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1527 SDValue ArgValue; 1528 1529 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1530 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1531 MVT MemVT = VA.getValVT(); 1532 1533 switch (VA.getLocInfo()) { 1534 default: 1535 break; 1536 case CCValAssign::BCvt: 1537 MemVT = VA.getLocVT(); 1538 break; 1539 case CCValAssign::SExt: 1540 ExtType = ISD::SEXTLOAD; 1541 break; 1542 case CCValAssign::ZExt: 1543 ExtType = ISD::ZEXTLOAD; 1544 break; 1545 case CCValAssign::AExt: 1546 ExtType = ISD::EXTLOAD; 1547 break; 1548 } 1549 1550 ArgValue = DAG.getExtLoad( 1551 ExtType, SL, VA.getLocVT(), Chain, FIN, 1552 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1553 MemVT); 1554 return ArgValue; 1555 } 1556 1557 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1558 const SIMachineFunctionInfo &MFI, 1559 EVT VT, 1560 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1561 const ArgDescriptor *Reg; 1562 const TargetRegisterClass *RC; 1563 1564 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1565 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1566 } 1567 1568 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1569 CallingConv::ID CallConv, 1570 ArrayRef<ISD::InputArg> Ins, 1571 BitVector &Skipped, 1572 FunctionType *FType, 1573 SIMachineFunctionInfo *Info) { 1574 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1575 const ISD::InputArg *Arg = &Ins[I]; 1576 1577 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1578 "vector type argument should have been split"); 1579 1580 // First check if it's a PS input addr. 1581 if (CallConv == CallingConv::AMDGPU_PS && 1582 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1583 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1584 1585 // Inconveniently only the first part of the split is marked as isSplit, 1586 // so skip to the end. We only want to increment PSInputNum once for the 1587 // entire split argument. 1588 if (Arg->Flags.isSplit()) { 1589 while (!Arg->Flags.isSplitEnd()) { 1590 assert((!Arg->VT.isVector() || 1591 Arg->VT.getScalarSizeInBits() == 16) && 1592 "unexpected vector split in ps argument type"); 1593 if (!SkipArg) 1594 Splits.push_back(*Arg); 1595 Arg = &Ins[++I]; 1596 } 1597 } 1598 1599 if (SkipArg) { 1600 // We can safely skip PS inputs. 1601 Skipped.set(Arg->getOrigArgIndex()); 1602 ++PSInputNum; 1603 continue; 1604 } 1605 1606 Info->markPSInputAllocated(PSInputNum); 1607 if (Arg->Used) 1608 Info->markPSInputEnabled(PSInputNum); 1609 1610 ++PSInputNum; 1611 } 1612 1613 Splits.push_back(*Arg); 1614 } 1615 } 1616 1617 // Allocate special inputs passed in VGPRs. 1618 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1619 MachineFunction &MF, 1620 const SIRegisterInfo &TRI, 1621 SIMachineFunctionInfo &Info) const { 1622 const LLT S32 = LLT::scalar(32); 1623 MachineRegisterInfo &MRI = MF.getRegInfo(); 1624 1625 if (Info.hasWorkItemIDX()) { 1626 Register Reg = AMDGPU::VGPR0; 1627 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1628 1629 CCInfo.AllocateReg(Reg); 1630 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1631 } 1632 1633 if (Info.hasWorkItemIDY()) { 1634 Register Reg = AMDGPU::VGPR1; 1635 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1636 1637 CCInfo.AllocateReg(Reg); 1638 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1639 } 1640 1641 if (Info.hasWorkItemIDZ()) { 1642 Register Reg = AMDGPU::VGPR2; 1643 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1644 1645 CCInfo.AllocateReg(Reg); 1646 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1647 } 1648 } 1649 1650 // Try to allocate a VGPR at the end of the argument list, or if no argument 1651 // VGPRs are left allocating a stack slot. 1652 // If \p Mask is is given it indicates bitfield position in the register. 1653 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1654 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1655 ArgDescriptor Arg = ArgDescriptor()) { 1656 if (Arg.isSet()) 1657 return ArgDescriptor::createArg(Arg, Mask); 1658 1659 ArrayRef<MCPhysReg> ArgVGPRs 1660 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1661 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1662 if (RegIdx == ArgVGPRs.size()) { 1663 // Spill to stack required. 1664 int64_t Offset = CCInfo.AllocateStack(4, 4); 1665 1666 return ArgDescriptor::createStack(Offset, Mask); 1667 } 1668 1669 unsigned Reg = ArgVGPRs[RegIdx]; 1670 Reg = CCInfo.AllocateReg(Reg); 1671 assert(Reg != AMDGPU::NoRegister); 1672 1673 MachineFunction &MF = CCInfo.getMachineFunction(); 1674 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1675 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1676 return ArgDescriptor::createRegister(Reg, Mask); 1677 } 1678 1679 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1680 const TargetRegisterClass *RC, 1681 unsigned NumArgRegs) { 1682 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1683 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1684 if (RegIdx == ArgSGPRs.size()) 1685 report_fatal_error("ran out of SGPRs for arguments"); 1686 1687 unsigned Reg = ArgSGPRs[RegIdx]; 1688 Reg = CCInfo.AllocateReg(Reg); 1689 assert(Reg != AMDGPU::NoRegister); 1690 1691 MachineFunction &MF = CCInfo.getMachineFunction(); 1692 MF.addLiveIn(Reg, RC); 1693 return ArgDescriptor::createRegister(Reg); 1694 } 1695 1696 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1697 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1698 } 1699 1700 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1701 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1702 } 1703 1704 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo, 1705 MachineFunction &MF, 1706 const SIRegisterInfo &TRI, 1707 SIMachineFunctionInfo &Info) const { 1708 const unsigned Mask = 0x3ff; 1709 ArgDescriptor Arg; 1710 1711 if (Info.hasWorkItemIDX()) { 1712 Arg = allocateVGPR32Input(CCInfo, Mask); 1713 Info.setWorkItemIDX(Arg); 1714 } 1715 1716 if (Info.hasWorkItemIDY()) { 1717 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1718 Info.setWorkItemIDY(Arg); 1719 } 1720 1721 if (Info.hasWorkItemIDZ()) 1722 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1723 } 1724 1725 void SITargetLowering::allocateSpecialInputSGPRs( 1726 CCState &CCInfo, 1727 MachineFunction &MF, 1728 const SIRegisterInfo &TRI, 1729 SIMachineFunctionInfo &Info) const { 1730 auto &ArgInfo = Info.getArgInfo(); 1731 1732 // TODO: Unify handling with private memory pointers. 1733 1734 if (Info.hasDispatchPtr()) 1735 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1736 1737 if (Info.hasQueuePtr()) 1738 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1739 1740 if (Info.hasKernargSegmentPtr()) 1741 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1742 1743 if (Info.hasDispatchID()) 1744 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1745 1746 // flat_scratch_init is not applicable for non-kernel functions. 1747 1748 if (Info.hasWorkGroupIDX()) 1749 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1750 1751 if (Info.hasWorkGroupIDY()) 1752 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1753 1754 if (Info.hasWorkGroupIDZ()) 1755 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1756 1757 if (Info.hasImplicitArgPtr()) 1758 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1759 } 1760 1761 // Allocate special inputs passed in user SGPRs. 1762 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1763 MachineFunction &MF, 1764 const SIRegisterInfo &TRI, 1765 SIMachineFunctionInfo &Info) const { 1766 if (Info.hasImplicitBufferPtr()) { 1767 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1768 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1769 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1770 } 1771 1772 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1773 if (Info.hasPrivateSegmentBuffer()) { 1774 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1775 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1776 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1777 } 1778 1779 if (Info.hasDispatchPtr()) { 1780 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1781 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1782 CCInfo.AllocateReg(DispatchPtrReg); 1783 } 1784 1785 if (Info.hasQueuePtr()) { 1786 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1787 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1788 CCInfo.AllocateReg(QueuePtrReg); 1789 } 1790 1791 if (Info.hasKernargSegmentPtr()) { 1792 MachineRegisterInfo &MRI = MF.getRegInfo(); 1793 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1794 CCInfo.AllocateReg(InputPtrReg); 1795 1796 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1797 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1798 } 1799 1800 if (Info.hasDispatchID()) { 1801 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1802 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1803 CCInfo.AllocateReg(DispatchIDReg); 1804 } 1805 1806 if (Info.hasFlatScratchInit()) { 1807 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1808 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1809 CCInfo.AllocateReg(FlatScratchInitReg); 1810 } 1811 1812 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1813 // these from the dispatch pointer. 1814 } 1815 1816 // Allocate special input registers that are initialized per-wave. 1817 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1818 MachineFunction &MF, 1819 SIMachineFunctionInfo &Info, 1820 CallingConv::ID CallConv, 1821 bool IsShader) const { 1822 if (Info.hasWorkGroupIDX()) { 1823 unsigned Reg = Info.addWorkGroupIDX(); 1824 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1825 CCInfo.AllocateReg(Reg); 1826 } 1827 1828 if (Info.hasWorkGroupIDY()) { 1829 unsigned Reg = Info.addWorkGroupIDY(); 1830 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1831 CCInfo.AllocateReg(Reg); 1832 } 1833 1834 if (Info.hasWorkGroupIDZ()) { 1835 unsigned Reg = Info.addWorkGroupIDZ(); 1836 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1837 CCInfo.AllocateReg(Reg); 1838 } 1839 1840 if (Info.hasWorkGroupInfo()) { 1841 unsigned Reg = Info.addWorkGroupInfo(); 1842 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1843 CCInfo.AllocateReg(Reg); 1844 } 1845 1846 if (Info.hasPrivateSegmentWaveByteOffset()) { 1847 // Scratch wave offset passed in system SGPR. 1848 unsigned PrivateSegmentWaveByteOffsetReg; 1849 1850 if (IsShader) { 1851 PrivateSegmentWaveByteOffsetReg = 1852 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1853 1854 // This is true if the scratch wave byte offset doesn't have a fixed 1855 // location. 1856 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1857 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1858 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1859 } 1860 } else 1861 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1862 1863 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1864 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1865 } 1866 } 1867 1868 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1869 MachineFunction &MF, 1870 const SIRegisterInfo &TRI, 1871 SIMachineFunctionInfo &Info) { 1872 // Now that we've figured out where the scratch register inputs are, see if 1873 // should reserve the arguments and use them directly. 1874 MachineFrameInfo &MFI = MF.getFrameInfo(); 1875 bool HasStackObjects = MFI.hasStackObjects(); 1876 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1877 1878 // Record that we know we have non-spill stack objects so we don't need to 1879 // check all stack objects later. 1880 if (HasStackObjects) 1881 Info.setHasNonSpillStackObjects(true); 1882 1883 // Everything live out of a block is spilled with fast regalloc, so it's 1884 // almost certain that spilling will be required. 1885 if (TM.getOptLevel() == CodeGenOpt::None) 1886 HasStackObjects = true; 1887 1888 // For now assume stack access is needed in any callee functions, so we need 1889 // the scratch registers to pass in. 1890 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1891 1892 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1893 // If we have stack objects, we unquestionably need the private buffer 1894 // resource. For the Code Object V2 ABI, this will be the first 4 user 1895 // SGPR inputs. We can reserve those and use them directly. 1896 1897 Register PrivateSegmentBufferReg = 1898 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1899 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1900 } else { 1901 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1902 // We tentatively reserve the last registers (skipping the last registers 1903 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1904 // we'll replace these with the ones immediately after those which were 1905 // really allocated. In the prologue copies will be inserted from the 1906 // argument to these reserved registers. 1907 1908 // Without HSA, relocations are used for the scratch pointer and the 1909 // buffer resource setup is always inserted in the prologue. Scratch wave 1910 // offset is still in an input SGPR. 1911 Info.setScratchRSrcReg(ReservedBufferReg); 1912 } 1913 1914 // hasFP should be accurate for kernels even before the frame is finalized. 1915 if (ST.getFrameLowering()->hasFP(MF)) { 1916 MachineRegisterInfo &MRI = MF.getRegInfo(); 1917 1918 // Try to use s32 as the SP, but move it if it would interfere with input 1919 // arguments. This won't work with calls though. 1920 // 1921 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1922 // registers. 1923 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1924 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1925 } else { 1926 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1927 1928 if (MFI.hasCalls()) 1929 report_fatal_error("call in graphics shader with too many input SGPRs"); 1930 1931 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1932 if (!MRI.isLiveIn(Reg)) { 1933 Info.setStackPtrOffsetReg(Reg); 1934 break; 1935 } 1936 } 1937 1938 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1939 report_fatal_error("failed to find register for SP"); 1940 } 1941 1942 if (MFI.hasCalls()) { 1943 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1944 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1945 } else { 1946 unsigned ReservedOffsetReg = 1947 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1948 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1949 Info.setFrameOffsetReg(ReservedOffsetReg); 1950 } 1951 } else if (RequiresStackAccess) { 1952 assert(!MFI.hasCalls()); 1953 // We know there are accesses and they will be done relative to SP, so just 1954 // pin it to the input. 1955 // 1956 // FIXME: Should not do this if inline asm is reading/writing these 1957 // registers. 1958 Register PreloadedSP = Info.getPreloadedReg( 1959 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1960 1961 Info.setStackPtrOffsetReg(PreloadedSP); 1962 Info.setScratchWaveOffsetReg(PreloadedSP); 1963 Info.setFrameOffsetReg(PreloadedSP); 1964 } else { 1965 assert(!MFI.hasCalls()); 1966 1967 // There may not be stack access at all. There may still be spills, or 1968 // access of a constant pointer (in which cases an extra copy will be 1969 // emitted in the prolog). 1970 unsigned ReservedOffsetReg 1971 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1972 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1973 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1974 Info.setFrameOffsetReg(ReservedOffsetReg); 1975 } 1976 } 1977 1978 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1979 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1980 return !Info->isEntryFunction(); 1981 } 1982 1983 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1984 1985 } 1986 1987 void SITargetLowering::insertCopiesSplitCSR( 1988 MachineBasicBlock *Entry, 1989 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1990 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1991 1992 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1993 if (!IStart) 1994 return; 1995 1996 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1997 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1998 MachineBasicBlock::iterator MBBI = Entry->begin(); 1999 for (const MCPhysReg *I = IStart; *I; ++I) { 2000 const TargetRegisterClass *RC = nullptr; 2001 if (AMDGPU::SReg_64RegClass.contains(*I)) 2002 RC = &AMDGPU::SGPR_64RegClass; 2003 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2004 RC = &AMDGPU::SGPR_32RegClass; 2005 else 2006 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2007 2008 Register NewVR = MRI->createVirtualRegister(RC); 2009 // Create copy from CSR to a virtual register. 2010 Entry->addLiveIn(*I); 2011 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2012 .addReg(*I); 2013 2014 // Insert the copy-back instructions right before the terminator. 2015 for (auto *Exit : Exits) 2016 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2017 TII->get(TargetOpcode::COPY), *I) 2018 .addReg(NewVR); 2019 } 2020 } 2021 2022 SDValue SITargetLowering::LowerFormalArguments( 2023 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2024 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2025 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2026 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2027 2028 MachineFunction &MF = DAG.getMachineFunction(); 2029 const Function &Fn = MF.getFunction(); 2030 FunctionType *FType = MF.getFunction().getFunctionType(); 2031 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2032 2033 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2034 DiagnosticInfoUnsupported NoGraphicsHSA( 2035 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2036 DAG.getContext()->diagnose(NoGraphicsHSA); 2037 return DAG.getEntryNode(); 2038 } 2039 2040 SmallVector<ISD::InputArg, 16> Splits; 2041 SmallVector<CCValAssign, 16> ArgLocs; 2042 BitVector Skipped(Ins.size()); 2043 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2044 *DAG.getContext()); 2045 2046 bool IsShader = AMDGPU::isShader(CallConv); 2047 bool IsKernel = AMDGPU::isKernel(CallConv); 2048 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2049 2050 if (IsShader) { 2051 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2052 2053 // At least one interpolation mode must be enabled or else the GPU will 2054 // hang. 2055 // 2056 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2057 // set PSInputAddr, the user wants to enable some bits after the compilation 2058 // based on run-time states. Since we can't know what the final PSInputEna 2059 // will look like, so we shouldn't do anything here and the user should take 2060 // responsibility for the correct programming. 2061 // 2062 // Otherwise, the following restrictions apply: 2063 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2064 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2065 // enabled too. 2066 if (CallConv == CallingConv::AMDGPU_PS) { 2067 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2068 ((Info->getPSInputAddr() & 0xF) == 0 && 2069 Info->isPSInputAllocated(11))) { 2070 CCInfo.AllocateReg(AMDGPU::VGPR0); 2071 CCInfo.AllocateReg(AMDGPU::VGPR1); 2072 Info->markPSInputAllocated(0); 2073 Info->markPSInputEnabled(0); 2074 } 2075 if (Subtarget->isAmdPalOS()) { 2076 // For isAmdPalOS, the user does not enable some bits after compilation 2077 // based on run-time states; the register values being generated here are 2078 // the final ones set in hardware. Therefore we need to apply the 2079 // workaround to PSInputAddr and PSInputEnable together. (The case where 2080 // a bit is set in PSInputAddr but not PSInputEnable is where the 2081 // frontend set up an input arg for a particular interpolation mode, but 2082 // nothing uses that input arg. Really we should have an earlier pass 2083 // that removes such an arg.) 2084 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2085 if ((PsInputBits & 0x7F) == 0 || 2086 ((PsInputBits & 0xF) == 0 && 2087 (PsInputBits >> 11 & 1))) 2088 Info->markPSInputEnabled( 2089 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2090 } 2091 } 2092 2093 assert(!Info->hasDispatchPtr() && 2094 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2095 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2096 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2097 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2098 !Info->hasWorkItemIDZ()); 2099 } else if (IsKernel) { 2100 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2101 } else { 2102 Splits.append(Ins.begin(), Ins.end()); 2103 } 2104 2105 if (IsEntryFunc) { 2106 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2107 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2108 } 2109 2110 if (IsKernel) { 2111 analyzeFormalArgumentsCompute(CCInfo, Ins); 2112 } else { 2113 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2114 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2115 } 2116 2117 SmallVector<SDValue, 16> Chains; 2118 2119 // FIXME: This is the minimum kernel argument alignment. We should improve 2120 // this to the maximum alignment of the arguments. 2121 // 2122 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2123 // kern arg offset. 2124 const unsigned KernelArgBaseAlign = 16; 2125 2126 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2127 const ISD::InputArg &Arg = Ins[i]; 2128 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2129 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2130 continue; 2131 } 2132 2133 CCValAssign &VA = ArgLocs[ArgIdx++]; 2134 MVT VT = VA.getLocVT(); 2135 2136 if (IsEntryFunc && VA.isMemLoc()) { 2137 VT = Ins[i].VT; 2138 EVT MemVT = VA.getLocVT(); 2139 2140 const uint64_t Offset = VA.getLocMemOffset(); 2141 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2142 2143 SDValue Arg = lowerKernargMemParameter( 2144 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2145 Chains.push_back(Arg.getValue(1)); 2146 2147 auto *ParamTy = 2148 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2149 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2150 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2151 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2152 // On SI local pointers are just offsets into LDS, so they are always 2153 // less than 16-bits. On CI and newer they could potentially be 2154 // real pointers, so we can't guarantee their size. 2155 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2156 DAG.getValueType(MVT::i16)); 2157 } 2158 2159 InVals.push_back(Arg); 2160 continue; 2161 } else if (!IsEntryFunc && VA.isMemLoc()) { 2162 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2163 InVals.push_back(Val); 2164 if (!Arg.Flags.isByVal()) 2165 Chains.push_back(Val.getValue(1)); 2166 continue; 2167 } 2168 2169 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2170 2171 Register Reg = VA.getLocReg(); 2172 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2173 EVT ValVT = VA.getValVT(); 2174 2175 Reg = MF.addLiveIn(Reg, RC); 2176 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2177 2178 if (Arg.Flags.isSRet()) { 2179 // The return object should be reasonably addressable. 2180 2181 // FIXME: This helps when the return is a real sret. If it is a 2182 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2183 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2184 unsigned NumBits 2185 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2186 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2187 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2188 } 2189 2190 // If this is an 8 or 16-bit value, it is really passed promoted 2191 // to 32 bits. Insert an assert[sz]ext to capture this, then 2192 // truncate to the right size. 2193 switch (VA.getLocInfo()) { 2194 case CCValAssign::Full: 2195 break; 2196 case CCValAssign::BCvt: 2197 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2198 break; 2199 case CCValAssign::SExt: 2200 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2201 DAG.getValueType(ValVT)); 2202 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2203 break; 2204 case CCValAssign::ZExt: 2205 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2206 DAG.getValueType(ValVT)); 2207 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2208 break; 2209 case CCValAssign::AExt: 2210 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2211 break; 2212 default: 2213 llvm_unreachable("Unknown loc info!"); 2214 } 2215 2216 InVals.push_back(Val); 2217 } 2218 2219 if (!IsEntryFunc) { 2220 // Special inputs come after user arguments. 2221 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2222 } 2223 2224 // Start adding system SGPRs. 2225 if (IsEntryFunc) { 2226 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2227 } else { 2228 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2229 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2230 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2231 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2232 } 2233 2234 auto &ArgUsageInfo = 2235 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2236 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2237 2238 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2239 Info->setBytesInStackArgArea(StackArgSize); 2240 2241 return Chains.empty() ? Chain : 2242 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2243 } 2244 2245 // TODO: If return values can't fit in registers, we should return as many as 2246 // possible in registers before passing on stack. 2247 bool SITargetLowering::CanLowerReturn( 2248 CallingConv::ID CallConv, 2249 MachineFunction &MF, bool IsVarArg, 2250 const SmallVectorImpl<ISD::OutputArg> &Outs, 2251 LLVMContext &Context) const { 2252 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2253 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2254 // for shaders. Vector types should be explicitly handled by CC. 2255 if (AMDGPU::isEntryFunctionCC(CallConv)) 2256 return true; 2257 2258 SmallVector<CCValAssign, 16> RVLocs; 2259 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2260 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2261 } 2262 2263 SDValue 2264 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2265 bool isVarArg, 2266 const SmallVectorImpl<ISD::OutputArg> &Outs, 2267 const SmallVectorImpl<SDValue> &OutVals, 2268 const SDLoc &DL, SelectionDAG &DAG) const { 2269 MachineFunction &MF = DAG.getMachineFunction(); 2270 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2271 2272 if (AMDGPU::isKernel(CallConv)) { 2273 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2274 OutVals, DL, DAG); 2275 } 2276 2277 bool IsShader = AMDGPU::isShader(CallConv); 2278 2279 Info->setIfReturnsVoid(Outs.empty()); 2280 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2281 2282 // CCValAssign - represent the assignment of the return value to a location. 2283 SmallVector<CCValAssign, 48> RVLocs; 2284 SmallVector<ISD::OutputArg, 48> Splits; 2285 2286 // CCState - Info about the registers and stack slots. 2287 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2288 *DAG.getContext()); 2289 2290 // Analyze outgoing return values. 2291 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2292 2293 SDValue Flag; 2294 SmallVector<SDValue, 48> RetOps; 2295 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2296 2297 // Add return address for callable functions. 2298 if (!Info->isEntryFunction()) { 2299 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2300 SDValue ReturnAddrReg = CreateLiveInRegister( 2301 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2302 2303 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2304 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2305 MVT::i64); 2306 Chain = 2307 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2308 Flag = Chain.getValue(1); 2309 RetOps.push_back(ReturnAddrVirtualReg); 2310 } 2311 2312 // Copy the result values into the output registers. 2313 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2314 ++I, ++RealRVLocIdx) { 2315 CCValAssign &VA = RVLocs[I]; 2316 assert(VA.isRegLoc() && "Can only return in registers!"); 2317 // TODO: Partially return in registers if return values don't fit. 2318 SDValue Arg = OutVals[RealRVLocIdx]; 2319 2320 // Copied from other backends. 2321 switch (VA.getLocInfo()) { 2322 case CCValAssign::Full: 2323 break; 2324 case CCValAssign::BCvt: 2325 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2326 break; 2327 case CCValAssign::SExt: 2328 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2329 break; 2330 case CCValAssign::ZExt: 2331 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2332 break; 2333 case CCValAssign::AExt: 2334 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2335 break; 2336 default: 2337 llvm_unreachable("Unknown loc info!"); 2338 } 2339 2340 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2341 Flag = Chain.getValue(1); 2342 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2343 } 2344 2345 // FIXME: Does sret work properly? 2346 if (!Info->isEntryFunction()) { 2347 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2348 const MCPhysReg *I = 2349 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2350 if (I) { 2351 for (; *I; ++I) { 2352 if (AMDGPU::SReg_64RegClass.contains(*I)) 2353 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2354 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2355 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2356 else 2357 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2358 } 2359 } 2360 } 2361 2362 // Update chain and glue. 2363 RetOps[0] = Chain; 2364 if (Flag.getNode()) 2365 RetOps.push_back(Flag); 2366 2367 unsigned Opc = AMDGPUISD::ENDPGM; 2368 if (!IsWaveEnd) 2369 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2370 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2371 } 2372 2373 SDValue SITargetLowering::LowerCallResult( 2374 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2375 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2376 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2377 SDValue ThisVal) const { 2378 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2379 2380 // Assign locations to each value returned by this call. 2381 SmallVector<CCValAssign, 16> RVLocs; 2382 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2383 *DAG.getContext()); 2384 CCInfo.AnalyzeCallResult(Ins, RetCC); 2385 2386 // Copy all of the result registers out of their specified physreg. 2387 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2388 CCValAssign VA = RVLocs[i]; 2389 SDValue Val; 2390 2391 if (VA.isRegLoc()) { 2392 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2393 Chain = Val.getValue(1); 2394 InFlag = Val.getValue(2); 2395 } else if (VA.isMemLoc()) { 2396 report_fatal_error("TODO: return values in memory"); 2397 } else 2398 llvm_unreachable("unknown argument location type"); 2399 2400 switch (VA.getLocInfo()) { 2401 case CCValAssign::Full: 2402 break; 2403 case CCValAssign::BCvt: 2404 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2405 break; 2406 case CCValAssign::ZExt: 2407 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2408 DAG.getValueType(VA.getValVT())); 2409 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2410 break; 2411 case CCValAssign::SExt: 2412 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2413 DAG.getValueType(VA.getValVT())); 2414 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2415 break; 2416 case CCValAssign::AExt: 2417 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2418 break; 2419 default: 2420 llvm_unreachable("Unknown loc info!"); 2421 } 2422 2423 InVals.push_back(Val); 2424 } 2425 2426 return Chain; 2427 } 2428 2429 // Add code to pass special inputs required depending on used features separate 2430 // from the explicit user arguments present in the IR. 2431 void SITargetLowering::passSpecialInputs( 2432 CallLoweringInfo &CLI, 2433 CCState &CCInfo, 2434 const SIMachineFunctionInfo &Info, 2435 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2436 SmallVectorImpl<SDValue> &MemOpChains, 2437 SDValue Chain) const { 2438 // If we don't have a call site, this was a call inserted by 2439 // legalization. These can never use special inputs. 2440 if (!CLI.CS) 2441 return; 2442 2443 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2444 assert(CalleeFunc); 2445 2446 SelectionDAG &DAG = CLI.DAG; 2447 const SDLoc &DL = CLI.DL; 2448 2449 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2450 2451 auto &ArgUsageInfo = 2452 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2453 const AMDGPUFunctionArgInfo &CalleeArgInfo 2454 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2455 2456 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2457 2458 // TODO: Unify with private memory register handling. This is complicated by 2459 // the fact that at least in kernels, the input argument is not necessarily 2460 // in the same location as the input. 2461 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2462 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2463 AMDGPUFunctionArgInfo::QUEUE_PTR, 2464 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2465 AMDGPUFunctionArgInfo::DISPATCH_ID, 2466 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2467 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2468 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2469 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2470 }; 2471 2472 for (auto InputID : InputRegs) { 2473 const ArgDescriptor *OutgoingArg; 2474 const TargetRegisterClass *ArgRC; 2475 2476 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2477 if (!OutgoingArg) 2478 continue; 2479 2480 const ArgDescriptor *IncomingArg; 2481 const TargetRegisterClass *IncomingArgRC; 2482 std::tie(IncomingArg, IncomingArgRC) 2483 = CallerArgInfo.getPreloadedValue(InputID); 2484 assert(IncomingArgRC == ArgRC); 2485 2486 // All special arguments are ints for now. 2487 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2488 SDValue InputReg; 2489 2490 if (IncomingArg) { 2491 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2492 } else { 2493 // The implicit arg ptr is special because it doesn't have a corresponding 2494 // input for kernels, and is computed from the kernarg segment pointer. 2495 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2496 InputReg = getImplicitArgPtr(DAG, DL); 2497 } 2498 2499 if (OutgoingArg->isRegister()) { 2500 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2501 } else { 2502 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2503 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2504 SpecialArgOffset); 2505 MemOpChains.push_back(ArgStore); 2506 } 2507 } 2508 2509 // Pack workitem IDs into a single register or pass it as is if already 2510 // packed. 2511 const ArgDescriptor *OutgoingArg; 2512 const TargetRegisterClass *ArgRC; 2513 2514 std::tie(OutgoingArg, ArgRC) = 2515 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2516 if (!OutgoingArg) 2517 std::tie(OutgoingArg, ArgRC) = 2518 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2519 if (!OutgoingArg) 2520 std::tie(OutgoingArg, ArgRC) = 2521 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2522 if (!OutgoingArg) 2523 return; 2524 2525 const ArgDescriptor *IncomingArgX 2526 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2527 const ArgDescriptor *IncomingArgY 2528 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2529 const ArgDescriptor *IncomingArgZ 2530 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2531 2532 SDValue InputReg; 2533 SDLoc SL; 2534 2535 // If incoming ids are not packed we need to pack them. 2536 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2537 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2538 2539 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2540 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2541 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2542 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2543 InputReg = InputReg.getNode() ? 2544 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2545 } 2546 2547 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2548 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2549 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2550 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2551 InputReg = InputReg.getNode() ? 2552 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2553 } 2554 2555 if (!InputReg.getNode()) { 2556 // Workitem ids are already packed, any of present incoming arguments 2557 // will carry all required fields. 2558 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2559 IncomingArgX ? *IncomingArgX : 2560 IncomingArgY ? *IncomingArgY : 2561 *IncomingArgZ, ~0u); 2562 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2563 } 2564 2565 if (OutgoingArg->isRegister()) { 2566 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2567 } else { 2568 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2569 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2570 SpecialArgOffset); 2571 MemOpChains.push_back(ArgStore); 2572 } 2573 } 2574 2575 static bool canGuaranteeTCO(CallingConv::ID CC) { 2576 return CC == CallingConv::Fast; 2577 } 2578 2579 /// Return true if we might ever do TCO for calls with this calling convention. 2580 static bool mayTailCallThisCC(CallingConv::ID CC) { 2581 switch (CC) { 2582 case CallingConv::C: 2583 return true; 2584 default: 2585 return canGuaranteeTCO(CC); 2586 } 2587 } 2588 2589 bool SITargetLowering::isEligibleForTailCallOptimization( 2590 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2591 const SmallVectorImpl<ISD::OutputArg> &Outs, 2592 const SmallVectorImpl<SDValue> &OutVals, 2593 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2594 if (!mayTailCallThisCC(CalleeCC)) 2595 return false; 2596 2597 MachineFunction &MF = DAG.getMachineFunction(); 2598 const Function &CallerF = MF.getFunction(); 2599 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2600 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2601 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2602 2603 // Kernels aren't callable, and don't have a live in return address so it 2604 // doesn't make sense to do a tail call with entry functions. 2605 if (!CallerPreserved) 2606 return false; 2607 2608 bool CCMatch = CallerCC == CalleeCC; 2609 2610 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2611 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2612 return true; 2613 return false; 2614 } 2615 2616 // TODO: Can we handle var args? 2617 if (IsVarArg) 2618 return false; 2619 2620 for (const Argument &Arg : CallerF.args()) { 2621 if (Arg.hasByValAttr()) 2622 return false; 2623 } 2624 2625 LLVMContext &Ctx = *DAG.getContext(); 2626 2627 // Check that the call results are passed in the same way. 2628 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2629 CCAssignFnForCall(CalleeCC, IsVarArg), 2630 CCAssignFnForCall(CallerCC, IsVarArg))) 2631 return false; 2632 2633 // The callee has to preserve all registers the caller needs to preserve. 2634 if (!CCMatch) { 2635 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2636 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2637 return false; 2638 } 2639 2640 // Nothing more to check if the callee is taking no arguments. 2641 if (Outs.empty()) 2642 return true; 2643 2644 SmallVector<CCValAssign, 16> ArgLocs; 2645 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2646 2647 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2648 2649 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2650 // If the stack arguments for this call do not fit into our own save area then 2651 // the call cannot be made tail. 2652 // TODO: Is this really necessary? 2653 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2654 return false; 2655 2656 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2657 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2658 } 2659 2660 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2661 if (!CI->isTailCall()) 2662 return false; 2663 2664 const Function *ParentFn = CI->getParent()->getParent(); 2665 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2666 return false; 2667 2668 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2669 return (Attr.getValueAsString() != "true"); 2670 } 2671 2672 // The wave scratch offset register is used as the global base pointer. 2673 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2674 SmallVectorImpl<SDValue> &InVals) const { 2675 SelectionDAG &DAG = CLI.DAG; 2676 const SDLoc &DL = CLI.DL; 2677 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2678 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2679 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2680 SDValue Chain = CLI.Chain; 2681 SDValue Callee = CLI.Callee; 2682 bool &IsTailCall = CLI.IsTailCall; 2683 CallingConv::ID CallConv = CLI.CallConv; 2684 bool IsVarArg = CLI.IsVarArg; 2685 bool IsSibCall = false; 2686 bool IsThisReturn = false; 2687 MachineFunction &MF = DAG.getMachineFunction(); 2688 2689 if (IsVarArg) { 2690 return lowerUnhandledCall(CLI, InVals, 2691 "unsupported call to variadic function "); 2692 } 2693 2694 if (!CLI.CS.getInstruction()) 2695 report_fatal_error("unsupported libcall legalization"); 2696 2697 if (!CLI.CS.getCalledFunction()) { 2698 return lowerUnhandledCall(CLI, InVals, 2699 "unsupported indirect call to function "); 2700 } 2701 2702 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2703 return lowerUnhandledCall(CLI, InVals, 2704 "unsupported required tail call to function "); 2705 } 2706 2707 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2708 // Note the issue is with the CC of the calling function, not of the call 2709 // itself. 2710 return lowerUnhandledCall(CLI, InVals, 2711 "unsupported call from graphics shader of function "); 2712 } 2713 2714 if (IsTailCall) { 2715 IsTailCall = isEligibleForTailCallOptimization( 2716 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2717 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2718 report_fatal_error("failed to perform tail call elimination on a call " 2719 "site marked musttail"); 2720 } 2721 2722 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2723 2724 // A sibling call is one where we're under the usual C ABI and not planning 2725 // to change that but can still do a tail call: 2726 if (!TailCallOpt && IsTailCall) 2727 IsSibCall = true; 2728 2729 if (IsTailCall) 2730 ++NumTailCalls; 2731 } 2732 2733 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2734 2735 // Analyze operands of the call, assigning locations to each operand. 2736 SmallVector<CCValAssign, 16> ArgLocs; 2737 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2738 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2739 2740 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2741 2742 // Get a count of how many bytes are to be pushed on the stack. 2743 unsigned NumBytes = CCInfo.getNextStackOffset(); 2744 2745 if (IsSibCall) { 2746 // Since we're not changing the ABI to make this a tail call, the memory 2747 // operands are already available in the caller's incoming argument space. 2748 NumBytes = 0; 2749 } 2750 2751 // FPDiff is the byte offset of the call's argument area from the callee's. 2752 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2753 // by this amount for a tail call. In a sibling call it must be 0 because the 2754 // caller will deallocate the entire stack and the callee still expects its 2755 // arguments to begin at SP+0. Completely unused for non-tail calls. 2756 int32_t FPDiff = 0; 2757 MachineFrameInfo &MFI = MF.getFrameInfo(); 2758 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2759 2760 // Adjust the stack pointer for the new arguments... 2761 // These operations are automatically eliminated by the prolog/epilog pass 2762 if (!IsSibCall) { 2763 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2764 2765 SmallVector<SDValue, 4> CopyFromChains; 2766 2767 // In the HSA case, this should be an identity copy. 2768 SDValue ScratchRSrcReg 2769 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2770 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2771 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2772 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2773 } 2774 2775 SmallVector<SDValue, 8> MemOpChains; 2776 MVT PtrVT = MVT::i32; 2777 2778 // Walk the register/memloc assignments, inserting copies/loads. 2779 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2780 ++i, ++realArgIdx) { 2781 CCValAssign &VA = ArgLocs[i]; 2782 SDValue Arg = OutVals[realArgIdx]; 2783 2784 // Promote the value if needed. 2785 switch (VA.getLocInfo()) { 2786 case CCValAssign::Full: 2787 break; 2788 case CCValAssign::BCvt: 2789 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2790 break; 2791 case CCValAssign::ZExt: 2792 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2793 break; 2794 case CCValAssign::SExt: 2795 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2796 break; 2797 case CCValAssign::AExt: 2798 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2799 break; 2800 case CCValAssign::FPExt: 2801 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2802 break; 2803 default: 2804 llvm_unreachable("Unknown loc info!"); 2805 } 2806 2807 if (VA.isRegLoc()) { 2808 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2809 } else { 2810 assert(VA.isMemLoc()); 2811 2812 SDValue DstAddr; 2813 MachinePointerInfo DstInfo; 2814 2815 unsigned LocMemOffset = VA.getLocMemOffset(); 2816 int32_t Offset = LocMemOffset; 2817 2818 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2819 MaybeAlign Alignment; 2820 2821 if (IsTailCall) { 2822 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2823 unsigned OpSize = Flags.isByVal() ? 2824 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2825 2826 // FIXME: We can have better than the minimum byval required alignment. 2827 Alignment = 2828 Flags.isByVal() 2829 ? MaybeAlign(Flags.getByValAlign()) 2830 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2831 2832 Offset = Offset + FPDiff; 2833 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2834 2835 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2836 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2837 2838 // Make sure any stack arguments overlapping with where we're storing 2839 // are loaded before this eventual operation. Otherwise they'll be 2840 // clobbered. 2841 2842 // FIXME: Why is this really necessary? This seems to just result in a 2843 // lot of code to copy the stack and write them back to the same 2844 // locations, which are supposed to be immutable? 2845 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2846 } else { 2847 DstAddr = PtrOff; 2848 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2849 Alignment = 2850 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2851 } 2852 2853 if (Outs[i].Flags.isByVal()) { 2854 SDValue SizeNode = 2855 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2856 SDValue Cpy = DAG.getMemcpy( 2857 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2858 /*isVol = */ false, /*AlwaysInline = */ true, 2859 /*isTailCall = */ false, DstInfo, 2860 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2861 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS)))); 2862 2863 MemOpChains.push_back(Cpy); 2864 } else { 2865 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2866 Alignment ? Alignment->value() : 0); 2867 MemOpChains.push_back(Store); 2868 } 2869 } 2870 } 2871 2872 // Copy special input registers after user input arguments. 2873 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2874 2875 if (!MemOpChains.empty()) 2876 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2877 2878 // Build a sequence of copy-to-reg nodes chained together with token chain 2879 // and flag operands which copy the outgoing args into the appropriate regs. 2880 SDValue InFlag; 2881 for (auto &RegToPass : RegsToPass) { 2882 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2883 RegToPass.second, InFlag); 2884 InFlag = Chain.getValue(1); 2885 } 2886 2887 2888 SDValue PhysReturnAddrReg; 2889 if (IsTailCall) { 2890 // Since the return is being combined with the call, we need to pass on the 2891 // return address. 2892 2893 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2894 SDValue ReturnAddrReg = CreateLiveInRegister( 2895 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2896 2897 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2898 MVT::i64); 2899 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2900 InFlag = Chain.getValue(1); 2901 } 2902 2903 // We don't usually want to end the call-sequence here because we would tidy 2904 // the frame up *after* the call, however in the ABI-changing tail-call case 2905 // we've carefully laid out the parameters so that when sp is reset they'll be 2906 // in the correct location. 2907 if (IsTailCall && !IsSibCall) { 2908 Chain = DAG.getCALLSEQ_END(Chain, 2909 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2910 DAG.getTargetConstant(0, DL, MVT::i32), 2911 InFlag, DL); 2912 InFlag = Chain.getValue(1); 2913 } 2914 2915 std::vector<SDValue> Ops; 2916 Ops.push_back(Chain); 2917 Ops.push_back(Callee); 2918 // Add a redundant copy of the callee global which will not be legalized, as 2919 // we need direct access to the callee later. 2920 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2921 const GlobalValue *GV = GSD->getGlobal(); 2922 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2923 2924 if (IsTailCall) { 2925 // Each tail call may have to adjust the stack by a different amount, so 2926 // this information must travel along with the operation for eventual 2927 // consumption by emitEpilogue. 2928 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2929 2930 Ops.push_back(PhysReturnAddrReg); 2931 } 2932 2933 // Add argument registers to the end of the list so that they are known live 2934 // into the call. 2935 for (auto &RegToPass : RegsToPass) { 2936 Ops.push_back(DAG.getRegister(RegToPass.first, 2937 RegToPass.second.getValueType())); 2938 } 2939 2940 // Add a register mask operand representing the call-preserved registers. 2941 2942 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2943 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2944 assert(Mask && "Missing call preserved mask for calling convention"); 2945 Ops.push_back(DAG.getRegisterMask(Mask)); 2946 2947 if (InFlag.getNode()) 2948 Ops.push_back(InFlag); 2949 2950 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2951 2952 // If we're doing a tall call, use a TC_RETURN here rather than an 2953 // actual call instruction. 2954 if (IsTailCall) { 2955 MFI.setHasTailCall(); 2956 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2957 } 2958 2959 // Returns a chain and a flag for retval copy to use. 2960 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2961 Chain = Call.getValue(0); 2962 InFlag = Call.getValue(1); 2963 2964 uint64_t CalleePopBytes = NumBytes; 2965 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2966 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2967 InFlag, DL); 2968 if (!Ins.empty()) 2969 InFlag = Chain.getValue(1); 2970 2971 // Handle result values, copying them out of physregs into vregs that we 2972 // return. 2973 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2974 InVals, IsThisReturn, 2975 IsThisReturn ? OutVals[0] : SDValue()); 2976 } 2977 2978 Register SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2979 const MachineFunction &MF) const { 2980 Register Reg = StringSwitch<Register>(RegName) 2981 .Case("m0", AMDGPU::M0) 2982 .Case("exec", AMDGPU::EXEC) 2983 .Case("exec_lo", AMDGPU::EXEC_LO) 2984 .Case("exec_hi", AMDGPU::EXEC_HI) 2985 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2986 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2987 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2988 .Default(Register()); 2989 2990 if (Reg == AMDGPU::NoRegister) { 2991 report_fatal_error(Twine("invalid register name \"" 2992 + StringRef(RegName) + "\".")); 2993 2994 } 2995 2996 if (!Subtarget->hasFlatScrRegister() && 2997 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2998 report_fatal_error(Twine("invalid register \"" 2999 + StringRef(RegName) + "\" for subtarget.")); 3000 } 3001 3002 switch (Reg) { 3003 case AMDGPU::M0: 3004 case AMDGPU::EXEC_LO: 3005 case AMDGPU::EXEC_HI: 3006 case AMDGPU::FLAT_SCR_LO: 3007 case AMDGPU::FLAT_SCR_HI: 3008 if (VT.getSizeInBits() == 32) 3009 return Reg; 3010 break; 3011 case AMDGPU::EXEC: 3012 case AMDGPU::FLAT_SCR: 3013 if (VT.getSizeInBits() == 64) 3014 return Reg; 3015 break; 3016 default: 3017 llvm_unreachable("missing register type checking"); 3018 } 3019 3020 report_fatal_error(Twine("invalid type for register \"" 3021 + StringRef(RegName) + "\".")); 3022 } 3023 3024 // If kill is not the last instruction, split the block so kill is always a 3025 // proper terminator. 3026 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3027 MachineBasicBlock *BB) const { 3028 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3029 3030 MachineBasicBlock::iterator SplitPoint(&MI); 3031 ++SplitPoint; 3032 3033 if (SplitPoint == BB->end()) { 3034 // Don't bother with a new block. 3035 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3036 return BB; 3037 } 3038 3039 MachineFunction *MF = BB->getParent(); 3040 MachineBasicBlock *SplitBB 3041 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3042 3043 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3044 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3045 3046 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3047 BB->addSuccessor(SplitBB); 3048 3049 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3050 return SplitBB; 3051 } 3052 3053 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3054 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3055 // be the first instruction in the remainder block. 3056 // 3057 /// \returns { LoopBody, Remainder } 3058 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3059 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3060 MachineFunction *MF = MBB.getParent(); 3061 MachineBasicBlock::iterator I(&MI); 3062 3063 // To insert the loop we need to split the block. Move everything after this 3064 // point to a new block, and insert a new empty block between the two. 3065 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3066 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3067 MachineFunction::iterator MBBI(MBB); 3068 ++MBBI; 3069 3070 MF->insert(MBBI, LoopBB); 3071 MF->insert(MBBI, RemainderBB); 3072 3073 LoopBB->addSuccessor(LoopBB); 3074 LoopBB->addSuccessor(RemainderBB); 3075 3076 // Move the rest of the block into a new block. 3077 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3078 3079 if (InstInLoop) { 3080 auto Next = std::next(I); 3081 3082 // Move instruction to loop body. 3083 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3084 3085 // Move the rest of the block. 3086 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3087 } else { 3088 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3089 } 3090 3091 MBB.addSuccessor(LoopBB); 3092 3093 return std::make_pair(LoopBB, RemainderBB); 3094 } 3095 3096 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3097 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3098 MachineBasicBlock *MBB = MI.getParent(); 3099 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3100 auto I = MI.getIterator(); 3101 auto E = std::next(I); 3102 3103 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3104 .addImm(0); 3105 3106 MIBundleBuilder Bundler(*MBB, I, E); 3107 finalizeBundle(*MBB, Bundler.begin()); 3108 } 3109 3110 MachineBasicBlock * 3111 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3112 MachineBasicBlock *BB) const { 3113 const DebugLoc &DL = MI.getDebugLoc(); 3114 3115 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3116 3117 MachineBasicBlock *LoopBB; 3118 MachineBasicBlock *RemainderBB; 3119 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3120 3121 // Apparently kill flags are only valid if the def is in the same block? 3122 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3123 Src->setIsKill(false); 3124 3125 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3126 3127 MachineBasicBlock::iterator I = LoopBB->end(); 3128 3129 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3130 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3131 3132 // Clear TRAP_STS.MEM_VIOL 3133 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3134 .addImm(0) 3135 .addImm(EncodedReg); 3136 3137 bundleInstWithWaitcnt(MI); 3138 3139 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3140 3141 // Load and check TRAP_STS.MEM_VIOL 3142 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3143 .addImm(EncodedReg); 3144 3145 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3146 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3147 .addReg(Reg, RegState::Kill) 3148 .addImm(0); 3149 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3150 .addMBB(LoopBB); 3151 3152 return RemainderBB; 3153 } 3154 3155 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3156 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3157 // will only do one iteration. In the worst case, this will loop 64 times. 3158 // 3159 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3160 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3161 const SIInstrInfo *TII, 3162 MachineRegisterInfo &MRI, 3163 MachineBasicBlock &OrigBB, 3164 MachineBasicBlock &LoopBB, 3165 const DebugLoc &DL, 3166 const MachineOperand &IdxReg, 3167 unsigned InitReg, 3168 unsigned ResultReg, 3169 unsigned PhiReg, 3170 unsigned InitSaveExecReg, 3171 int Offset, 3172 bool UseGPRIdxMode, 3173 bool IsIndirectSrc) { 3174 MachineFunction *MF = OrigBB.getParent(); 3175 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3176 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3177 MachineBasicBlock::iterator I = LoopBB.begin(); 3178 3179 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3180 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3181 Register NewExec = MRI.createVirtualRegister(BoolRC); 3182 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3183 Register CondReg = MRI.createVirtualRegister(BoolRC); 3184 3185 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3186 .addReg(InitReg) 3187 .addMBB(&OrigBB) 3188 .addReg(ResultReg) 3189 .addMBB(&LoopBB); 3190 3191 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3192 .addReg(InitSaveExecReg) 3193 .addMBB(&OrigBB) 3194 .addReg(NewExec) 3195 .addMBB(&LoopBB); 3196 3197 // Read the next variant <- also loop target. 3198 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3199 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3200 3201 // Compare the just read M0 value to all possible Idx values. 3202 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3203 .addReg(CurrentIdxReg) 3204 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3205 3206 // Update EXEC, save the original EXEC value to VCC. 3207 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3208 : AMDGPU::S_AND_SAVEEXEC_B64), 3209 NewExec) 3210 .addReg(CondReg, RegState::Kill); 3211 3212 MRI.setSimpleHint(NewExec, CondReg); 3213 3214 if (UseGPRIdxMode) { 3215 unsigned IdxReg; 3216 if (Offset == 0) { 3217 IdxReg = CurrentIdxReg; 3218 } else { 3219 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3220 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3221 .addReg(CurrentIdxReg, RegState::Kill) 3222 .addImm(Offset); 3223 } 3224 unsigned IdxMode = IsIndirectSrc ? 3225 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3226 MachineInstr *SetOn = 3227 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3228 .addReg(IdxReg, RegState::Kill) 3229 .addImm(IdxMode); 3230 SetOn->getOperand(3).setIsUndef(); 3231 } else { 3232 // Move index from VCC into M0 3233 if (Offset == 0) { 3234 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3235 .addReg(CurrentIdxReg, RegState::Kill); 3236 } else { 3237 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3238 .addReg(CurrentIdxReg, RegState::Kill) 3239 .addImm(Offset); 3240 } 3241 } 3242 3243 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3244 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3245 MachineInstr *InsertPt = 3246 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3247 : AMDGPU::S_XOR_B64_term), Exec) 3248 .addReg(Exec) 3249 .addReg(NewExec); 3250 3251 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3252 // s_cbranch_scc0? 3253 3254 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3255 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3256 .addMBB(&LoopBB); 3257 3258 return InsertPt->getIterator(); 3259 } 3260 3261 // This has slightly sub-optimal regalloc when the source vector is killed by 3262 // the read. The register allocator does not understand that the kill is 3263 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3264 // subregister from it, using 1 more VGPR than necessary. This was saved when 3265 // this was expanded after register allocation. 3266 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3267 MachineBasicBlock &MBB, 3268 MachineInstr &MI, 3269 unsigned InitResultReg, 3270 unsigned PhiReg, 3271 int Offset, 3272 bool UseGPRIdxMode, 3273 bool IsIndirectSrc) { 3274 MachineFunction *MF = MBB.getParent(); 3275 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3276 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3277 MachineRegisterInfo &MRI = MF->getRegInfo(); 3278 const DebugLoc &DL = MI.getDebugLoc(); 3279 MachineBasicBlock::iterator I(&MI); 3280 3281 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3282 Register DstReg = MI.getOperand(0).getReg(); 3283 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3284 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3285 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3286 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3287 3288 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3289 3290 // Save the EXEC mask 3291 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3292 .addReg(Exec); 3293 3294 MachineBasicBlock *LoopBB; 3295 MachineBasicBlock *RemainderBB; 3296 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3297 3298 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3299 3300 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3301 InitResultReg, DstReg, PhiReg, TmpExec, 3302 Offset, UseGPRIdxMode, IsIndirectSrc); 3303 3304 MachineBasicBlock::iterator First = RemainderBB->begin(); 3305 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3306 .addReg(SaveExec); 3307 3308 return InsPt; 3309 } 3310 3311 // Returns subreg index, offset 3312 static std::pair<unsigned, int> 3313 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3314 const TargetRegisterClass *SuperRC, 3315 unsigned VecReg, 3316 int Offset) { 3317 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3318 3319 // Skip out of bounds offsets, or else we would end up using an undefined 3320 // register. 3321 if (Offset >= NumElts || Offset < 0) 3322 return std::make_pair(AMDGPU::sub0, Offset); 3323 3324 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3325 } 3326 3327 // Return true if the index is an SGPR and was set. 3328 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3329 MachineRegisterInfo &MRI, 3330 MachineInstr &MI, 3331 int Offset, 3332 bool UseGPRIdxMode, 3333 bool IsIndirectSrc) { 3334 MachineBasicBlock *MBB = MI.getParent(); 3335 const DebugLoc &DL = MI.getDebugLoc(); 3336 MachineBasicBlock::iterator I(&MI); 3337 3338 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3339 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3340 3341 assert(Idx->getReg() != AMDGPU::NoRegister); 3342 3343 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3344 return false; 3345 3346 if (UseGPRIdxMode) { 3347 unsigned IdxMode = IsIndirectSrc ? 3348 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3349 if (Offset == 0) { 3350 MachineInstr *SetOn = 3351 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3352 .add(*Idx) 3353 .addImm(IdxMode); 3354 3355 SetOn->getOperand(3).setIsUndef(); 3356 } else { 3357 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3358 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3359 .add(*Idx) 3360 .addImm(Offset); 3361 MachineInstr *SetOn = 3362 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3363 .addReg(Tmp, RegState::Kill) 3364 .addImm(IdxMode); 3365 3366 SetOn->getOperand(3).setIsUndef(); 3367 } 3368 3369 return true; 3370 } 3371 3372 if (Offset == 0) { 3373 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3374 .add(*Idx); 3375 } else { 3376 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3377 .add(*Idx) 3378 .addImm(Offset); 3379 } 3380 3381 return true; 3382 } 3383 3384 // Control flow needs to be inserted if indexing with a VGPR. 3385 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3386 MachineBasicBlock &MBB, 3387 const GCNSubtarget &ST) { 3388 const SIInstrInfo *TII = ST.getInstrInfo(); 3389 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3390 MachineFunction *MF = MBB.getParent(); 3391 MachineRegisterInfo &MRI = MF->getRegInfo(); 3392 3393 Register Dst = MI.getOperand(0).getReg(); 3394 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3395 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3396 3397 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3398 3399 unsigned SubReg; 3400 std::tie(SubReg, Offset) 3401 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3402 3403 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3404 3405 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3406 MachineBasicBlock::iterator I(&MI); 3407 const DebugLoc &DL = MI.getDebugLoc(); 3408 3409 if (UseGPRIdxMode) { 3410 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3411 // to avoid interfering with other uses, so probably requires a new 3412 // optimization pass. 3413 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3414 .addReg(SrcReg, RegState::Undef, SubReg) 3415 .addReg(SrcReg, RegState::Implicit) 3416 .addReg(AMDGPU::M0, RegState::Implicit); 3417 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3418 } else { 3419 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3420 .addReg(SrcReg, RegState::Undef, SubReg) 3421 .addReg(SrcReg, RegState::Implicit); 3422 } 3423 3424 MI.eraseFromParent(); 3425 3426 return &MBB; 3427 } 3428 3429 const DebugLoc &DL = MI.getDebugLoc(); 3430 MachineBasicBlock::iterator I(&MI); 3431 3432 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3433 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3434 3435 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3436 3437 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3438 Offset, UseGPRIdxMode, true); 3439 MachineBasicBlock *LoopBB = InsPt->getParent(); 3440 3441 if (UseGPRIdxMode) { 3442 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3443 .addReg(SrcReg, RegState::Undef, SubReg) 3444 .addReg(SrcReg, RegState::Implicit) 3445 .addReg(AMDGPU::M0, RegState::Implicit); 3446 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3447 } else { 3448 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3449 .addReg(SrcReg, RegState::Undef, SubReg) 3450 .addReg(SrcReg, RegState::Implicit); 3451 } 3452 3453 MI.eraseFromParent(); 3454 3455 return LoopBB; 3456 } 3457 3458 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3459 const TargetRegisterClass *VecRC) { 3460 switch (TRI.getRegSizeInBits(*VecRC)) { 3461 case 32: // 4 bytes 3462 return AMDGPU::V_MOVRELD_B32_V1; 3463 case 64: // 8 bytes 3464 return AMDGPU::V_MOVRELD_B32_V2; 3465 case 128: // 16 bytes 3466 return AMDGPU::V_MOVRELD_B32_V4; 3467 case 256: // 32 bytes 3468 return AMDGPU::V_MOVRELD_B32_V8; 3469 case 512: // 64 bytes 3470 return AMDGPU::V_MOVRELD_B32_V16; 3471 default: 3472 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3473 } 3474 } 3475 3476 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3477 MachineBasicBlock &MBB, 3478 const GCNSubtarget &ST) { 3479 const SIInstrInfo *TII = ST.getInstrInfo(); 3480 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3481 MachineFunction *MF = MBB.getParent(); 3482 MachineRegisterInfo &MRI = MF->getRegInfo(); 3483 3484 Register Dst = MI.getOperand(0).getReg(); 3485 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3486 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3487 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3488 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3489 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3490 3491 // This can be an immediate, but will be folded later. 3492 assert(Val->getReg()); 3493 3494 unsigned SubReg; 3495 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3496 SrcVec->getReg(), 3497 Offset); 3498 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3499 3500 if (Idx->getReg() == AMDGPU::NoRegister) { 3501 MachineBasicBlock::iterator I(&MI); 3502 const DebugLoc &DL = MI.getDebugLoc(); 3503 3504 assert(Offset == 0); 3505 3506 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3507 .add(*SrcVec) 3508 .add(*Val) 3509 .addImm(SubReg); 3510 3511 MI.eraseFromParent(); 3512 return &MBB; 3513 } 3514 3515 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3516 MachineBasicBlock::iterator I(&MI); 3517 const DebugLoc &DL = MI.getDebugLoc(); 3518 3519 if (UseGPRIdxMode) { 3520 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3521 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3522 .add(*Val) 3523 .addReg(Dst, RegState::ImplicitDefine) 3524 .addReg(SrcVec->getReg(), RegState::Implicit) 3525 .addReg(AMDGPU::M0, RegState::Implicit); 3526 3527 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3528 } else { 3529 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3530 3531 BuildMI(MBB, I, DL, MovRelDesc) 3532 .addReg(Dst, RegState::Define) 3533 .addReg(SrcVec->getReg()) 3534 .add(*Val) 3535 .addImm(SubReg - AMDGPU::sub0); 3536 } 3537 3538 MI.eraseFromParent(); 3539 return &MBB; 3540 } 3541 3542 if (Val->isReg()) 3543 MRI.clearKillFlags(Val->getReg()); 3544 3545 const DebugLoc &DL = MI.getDebugLoc(); 3546 3547 Register PhiReg = MRI.createVirtualRegister(VecRC); 3548 3549 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3550 Offset, UseGPRIdxMode, false); 3551 MachineBasicBlock *LoopBB = InsPt->getParent(); 3552 3553 if (UseGPRIdxMode) { 3554 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3555 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3556 .add(*Val) // src0 3557 .addReg(Dst, RegState::ImplicitDefine) 3558 .addReg(PhiReg, RegState::Implicit) 3559 .addReg(AMDGPU::M0, RegState::Implicit); 3560 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3561 } else { 3562 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3563 3564 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3565 .addReg(Dst, RegState::Define) 3566 .addReg(PhiReg) 3567 .add(*Val) 3568 .addImm(SubReg - AMDGPU::sub0); 3569 } 3570 3571 MI.eraseFromParent(); 3572 3573 return LoopBB; 3574 } 3575 3576 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3577 MachineInstr &MI, MachineBasicBlock *BB) const { 3578 3579 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3580 MachineFunction *MF = BB->getParent(); 3581 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3582 3583 if (TII->isMIMG(MI)) { 3584 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3585 report_fatal_error("missing mem operand from MIMG instruction"); 3586 } 3587 // Add a memoperand for mimg instructions so that they aren't assumed to 3588 // be ordered memory instuctions. 3589 3590 return BB; 3591 } 3592 3593 switch (MI.getOpcode()) { 3594 case AMDGPU::S_ADD_U64_PSEUDO: 3595 case AMDGPU::S_SUB_U64_PSEUDO: { 3596 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3597 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3598 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3599 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3600 const DebugLoc &DL = MI.getDebugLoc(); 3601 3602 MachineOperand &Dest = MI.getOperand(0); 3603 MachineOperand &Src0 = MI.getOperand(1); 3604 MachineOperand &Src1 = MI.getOperand(2); 3605 3606 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3607 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3608 3609 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3610 Src0, BoolRC, AMDGPU::sub0, 3611 &AMDGPU::SReg_32_XM0RegClass); 3612 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3613 Src0, BoolRC, AMDGPU::sub1, 3614 &AMDGPU::SReg_32_XM0RegClass); 3615 3616 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3617 Src1, BoolRC, AMDGPU::sub0, 3618 &AMDGPU::SReg_32_XM0RegClass); 3619 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3620 Src1, BoolRC, AMDGPU::sub1, 3621 &AMDGPU::SReg_32_XM0RegClass); 3622 3623 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3624 3625 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3626 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3627 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3628 .add(Src0Sub0) 3629 .add(Src1Sub0); 3630 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3631 .add(Src0Sub1) 3632 .add(Src1Sub1); 3633 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3634 .addReg(DestSub0) 3635 .addImm(AMDGPU::sub0) 3636 .addReg(DestSub1) 3637 .addImm(AMDGPU::sub1); 3638 MI.eraseFromParent(); 3639 return BB; 3640 } 3641 case AMDGPU::SI_INIT_M0: { 3642 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3643 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3644 .add(MI.getOperand(0)); 3645 MI.eraseFromParent(); 3646 return BB; 3647 } 3648 case AMDGPU::SI_INIT_EXEC: 3649 // This should be before all vector instructions. 3650 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3651 AMDGPU::EXEC) 3652 .addImm(MI.getOperand(0).getImm()); 3653 MI.eraseFromParent(); 3654 return BB; 3655 3656 case AMDGPU::SI_INIT_EXEC_LO: 3657 // This should be before all vector instructions. 3658 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3659 AMDGPU::EXEC_LO) 3660 .addImm(MI.getOperand(0).getImm()); 3661 MI.eraseFromParent(); 3662 return BB; 3663 3664 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3665 // Extract the thread count from an SGPR input and set EXEC accordingly. 3666 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3667 // 3668 // S_BFE_U32 count, input, {shift, 7} 3669 // S_BFM_B64 exec, count, 0 3670 // S_CMP_EQ_U32 count, 64 3671 // S_CMOV_B64 exec, -1 3672 MachineInstr *FirstMI = &*BB->begin(); 3673 MachineRegisterInfo &MRI = MF->getRegInfo(); 3674 Register InputReg = MI.getOperand(0).getReg(); 3675 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3676 bool Found = false; 3677 3678 // Move the COPY of the input reg to the beginning, so that we can use it. 3679 for (auto I = BB->begin(); I != &MI; I++) { 3680 if (I->getOpcode() != TargetOpcode::COPY || 3681 I->getOperand(0).getReg() != InputReg) 3682 continue; 3683 3684 if (I == FirstMI) { 3685 FirstMI = &*++BB->begin(); 3686 } else { 3687 I->removeFromParent(); 3688 BB->insert(FirstMI, &*I); 3689 } 3690 Found = true; 3691 break; 3692 } 3693 assert(Found); 3694 (void)Found; 3695 3696 // This should be before all vector instructions. 3697 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3698 bool isWave32 = getSubtarget()->isWave32(); 3699 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3700 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3701 .addReg(InputReg) 3702 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3703 BuildMI(*BB, FirstMI, DebugLoc(), 3704 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3705 Exec) 3706 .addReg(CountReg) 3707 .addImm(0); 3708 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3709 .addReg(CountReg, RegState::Kill) 3710 .addImm(getSubtarget()->getWavefrontSize()); 3711 BuildMI(*BB, FirstMI, DebugLoc(), 3712 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3713 Exec) 3714 .addImm(-1); 3715 MI.eraseFromParent(); 3716 return BB; 3717 } 3718 3719 case AMDGPU::GET_GROUPSTATICSIZE: { 3720 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3721 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3722 DebugLoc DL = MI.getDebugLoc(); 3723 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3724 .add(MI.getOperand(0)) 3725 .addImm(MFI->getLDSSize()); 3726 MI.eraseFromParent(); 3727 return BB; 3728 } 3729 case AMDGPU::SI_INDIRECT_SRC_V1: 3730 case AMDGPU::SI_INDIRECT_SRC_V2: 3731 case AMDGPU::SI_INDIRECT_SRC_V4: 3732 case AMDGPU::SI_INDIRECT_SRC_V8: 3733 case AMDGPU::SI_INDIRECT_SRC_V16: 3734 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3735 case AMDGPU::SI_INDIRECT_DST_V1: 3736 case AMDGPU::SI_INDIRECT_DST_V2: 3737 case AMDGPU::SI_INDIRECT_DST_V4: 3738 case AMDGPU::SI_INDIRECT_DST_V8: 3739 case AMDGPU::SI_INDIRECT_DST_V16: 3740 return emitIndirectDst(MI, *BB, *getSubtarget()); 3741 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3742 case AMDGPU::SI_KILL_I1_PSEUDO: 3743 return splitKillBlock(MI, BB); 3744 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3745 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3746 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3747 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3748 3749 Register Dst = MI.getOperand(0).getReg(); 3750 Register Src0 = MI.getOperand(1).getReg(); 3751 Register Src1 = MI.getOperand(2).getReg(); 3752 const DebugLoc &DL = MI.getDebugLoc(); 3753 Register SrcCond = MI.getOperand(3).getReg(); 3754 3755 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3756 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3757 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3758 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3759 3760 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3761 .addReg(SrcCond); 3762 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3763 .addImm(0) 3764 .addReg(Src0, 0, AMDGPU::sub0) 3765 .addImm(0) 3766 .addReg(Src1, 0, AMDGPU::sub0) 3767 .addReg(SrcCondCopy); 3768 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3769 .addImm(0) 3770 .addReg(Src0, 0, AMDGPU::sub1) 3771 .addImm(0) 3772 .addReg(Src1, 0, AMDGPU::sub1) 3773 .addReg(SrcCondCopy); 3774 3775 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3776 .addReg(DstLo) 3777 .addImm(AMDGPU::sub0) 3778 .addReg(DstHi) 3779 .addImm(AMDGPU::sub1); 3780 MI.eraseFromParent(); 3781 return BB; 3782 } 3783 case AMDGPU::SI_BR_UNDEF: { 3784 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3785 const DebugLoc &DL = MI.getDebugLoc(); 3786 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3787 .add(MI.getOperand(0)); 3788 Br->getOperand(1).setIsUndef(true); // read undef SCC 3789 MI.eraseFromParent(); 3790 return BB; 3791 } 3792 case AMDGPU::ADJCALLSTACKUP: 3793 case AMDGPU::ADJCALLSTACKDOWN: { 3794 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3795 MachineInstrBuilder MIB(*MF, &MI); 3796 3797 // Add an implicit use of the frame offset reg to prevent the restore copy 3798 // inserted after the call from being reorderd after stack operations in the 3799 // the caller's frame. 3800 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3801 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3802 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3803 return BB; 3804 } 3805 case AMDGPU::SI_CALL_ISEL: { 3806 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3807 const DebugLoc &DL = MI.getDebugLoc(); 3808 3809 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3810 3811 MachineInstrBuilder MIB; 3812 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3813 3814 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3815 MIB.add(MI.getOperand(I)); 3816 3817 MIB.cloneMemRefs(MI); 3818 MI.eraseFromParent(); 3819 return BB; 3820 } 3821 case AMDGPU::V_ADD_I32_e32: 3822 case AMDGPU::V_SUB_I32_e32: 3823 case AMDGPU::V_SUBREV_I32_e32: { 3824 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3825 const DebugLoc &DL = MI.getDebugLoc(); 3826 unsigned Opc = MI.getOpcode(); 3827 3828 bool NeedClampOperand = false; 3829 if (TII->pseudoToMCOpcode(Opc) == -1) { 3830 Opc = AMDGPU::getVOPe64(Opc); 3831 NeedClampOperand = true; 3832 } 3833 3834 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3835 if (TII->isVOP3(*I)) { 3836 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3837 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3838 I.addReg(TRI->getVCC(), RegState::Define); 3839 } 3840 I.add(MI.getOperand(1)) 3841 .add(MI.getOperand(2)); 3842 if (NeedClampOperand) 3843 I.addImm(0); // clamp bit for e64 encoding 3844 3845 TII->legalizeOperands(*I); 3846 3847 MI.eraseFromParent(); 3848 return BB; 3849 } 3850 case AMDGPU::DS_GWS_INIT: 3851 case AMDGPU::DS_GWS_SEMA_V: 3852 case AMDGPU::DS_GWS_SEMA_BR: 3853 case AMDGPU::DS_GWS_SEMA_P: 3854 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3855 case AMDGPU::DS_GWS_BARRIER: 3856 // A s_waitcnt 0 is required to be the instruction immediately following. 3857 if (getSubtarget()->hasGWSAutoReplay()) { 3858 bundleInstWithWaitcnt(MI); 3859 return BB; 3860 } 3861 3862 return emitGWSMemViolTestLoop(MI, BB); 3863 default: 3864 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3865 } 3866 } 3867 3868 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3869 return isTypeLegal(VT.getScalarType()); 3870 } 3871 3872 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3873 // This currently forces unfolding various combinations of fsub into fma with 3874 // free fneg'd operands. As long as we have fast FMA (controlled by 3875 // isFMAFasterThanFMulAndFAdd), we should perform these. 3876 3877 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3878 // most of these combines appear to be cycle neutral but save on instruction 3879 // count / code size. 3880 return true; 3881 } 3882 3883 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3884 EVT VT) const { 3885 if (!VT.isVector()) { 3886 return MVT::i1; 3887 } 3888 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3889 } 3890 3891 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3892 // TODO: Should i16 be used always if legal? For now it would force VALU 3893 // shifts. 3894 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3895 } 3896 3897 // Answering this is somewhat tricky and depends on the specific device which 3898 // have different rates for fma or all f64 operations. 3899 // 3900 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3901 // regardless of which device (although the number of cycles differs between 3902 // devices), so it is always profitable for f64. 3903 // 3904 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3905 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3906 // which we can always do even without fused FP ops since it returns the same 3907 // result as the separate operations and since it is always full 3908 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3909 // however does not support denormals, so we do report fma as faster if we have 3910 // a fast fma device and require denormals. 3911 // 3912 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3913 VT = VT.getScalarType(); 3914 3915 switch (VT.getSimpleVT().SimpleTy) { 3916 case MVT::f32: { 3917 // This is as fast on some subtargets. However, we always have full rate f32 3918 // mad available which returns the same result as the separate operations 3919 // which we should prefer over fma. We can't use this if we want to support 3920 // denormals, so only report this in these cases. 3921 if (Subtarget->hasFP32Denormals()) 3922 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3923 3924 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3925 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3926 } 3927 case MVT::f64: 3928 return true; 3929 case MVT::f16: 3930 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3931 default: 3932 break; 3933 } 3934 3935 return false; 3936 } 3937 3938 //===----------------------------------------------------------------------===// 3939 // Custom DAG Lowering Operations 3940 //===----------------------------------------------------------------------===// 3941 3942 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3943 // wider vector type is legal. 3944 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3945 SelectionDAG &DAG) const { 3946 unsigned Opc = Op.getOpcode(); 3947 EVT VT = Op.getValueType(); 3948 assert(VT == MVT::v4f16); 3949 3950 SDValue Lo, Hi; 3951 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3952 3953 SDLoc SL(Op); 3954 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3955 Op->getFlags()); 3956 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3957 Op->getFlags()); 3958 3959 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3960 } 3961 3962 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3963 // wider vector type is legal. 3964 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3965 SelectionDAG &DAG) const { 3966 unsigned Opc = Op.getOpcode(); 3967 EVT VT = Op.getValueType(); 3968 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3969 3970 SDValue Lo0, Hi0; 3971 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3972 SDValue Lo1, Hi1; 3973 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3974 3975 SDLoc SL(Op); 3976 3977 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3978 Op->getFlags()); 3979 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3980 Op->getFlags()); 3981 3982 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3983 } 3984 3985 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 3986 SelectionDAG &DAG) const { 3987 unsigned Opc = Op.getOpcode(); 3988 EVT VT = Op.getValueType(); 3989 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3990 3991 SDValue Lo0, Hi0; 3992 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3993 SDValue Lo1, Hi1; 3994 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3995 SDValue Lo2, Hi2; 3996 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 3997 3998 SDLoc SL(Op); 3999 4000 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4001 Op->getFlags()); 4002 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4003 Op->getFlags()); 4004 4005 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4006 } 4007 4008 4009 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4010 switch (Op.getOpcode()) { 4011 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4012 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4013 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4014 case ISD::LOAD: { 4015 SDValue Result = LowerLOAD(Op, DAG); 4016 assert((!Result.getNode() || 4017 Result.getNode()->getNumValues() == 2) && 4018 "Load should return a value and a chain"); 4019 return Result; 4020 } 4021 4022 case ISD::FSIN: 4023 case ISD::FCOS: 4024 return LowerTrig(Op, DAG); 4025 case ISD::SELECT: return LowerSELECT(Op, DAG); 4026 case ISD::FDIV: return LowerFDIV(Op, DAG); 4027 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4028 case ISD::STORE: return LowerSTORE(Op, DAG); 4029 case ISD::GlobalAddress: { 4030 MachineFunction &MF = DAG.getMachineFunction(); 4031 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4032 return LowerGlobalAddress(MFI, Op, DAG); 4033 } 4034 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4035 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4036 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4037 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4038 case ISD::INSERT_SUBVECTOR: 4039 return lowerINSERT_SUBVECTOR(Op, DAG); 4040 case ISD::INSERT_VECTOR_ELT: 4041 return lowerINSERT_VECTOR_ELT(Op, DAG); 4042 case ISD::EXTRACT_VECTOR_ELT: 4043 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4044 case ISD::VECTOR_SHUFFLE: 4045 return lowerVECTOR_SHUFFLE(Op, DAG); 4046 case ISD::BUILD_VECTOR: 4047 return lowerBUILD_VECTOR(Op, DAG); 4048 case ISD::FP_ROUND: 4049 return lowerFP_ROUND(Op, DAG); 4050 case ISD::TRAP: 4051 return lowerTRAP(Op, DAG); 4052 case ISD::DEBUGTRAP: 4053 return lowerDEBUGTRAP(Op, DAG); 4054 case ISD::FABS: 4055 case ISD::FNEG: 4056 case ISD::FCANONICALIZE: 4057 return splitUnaryVectorOp(Op, DAG); 4058 case ISD::FMINNUM: 4059 case ISD::FMAXNUM: 4060 return lowerFMINNUM_FMAXNUM(Op, DAG); 4061 case ISD::FMA: 4062 return splitTernaryVectorOp(Op, DAG); 4063 case ISD::SHL: 4064 case ISD::SRA: 4065 case ISD::SRL: 4066 case ISD::ADD: 4067 case ISD::SUB: 4068 case ISD::MUL: 4069 case ISD::SMIN: 4070 case ISD::SMAX: 4071 case ISD::UMIN: 4072 case ISD::UMAX: 4073 case ISD::FADD: 4074 case ISD::FMUL: 4075 case ISD::FMINNUM_IEEE: 4076 case ISD::FMAXNUM_IEEE: 4077 return splitBinaryVectorOp(Op, DAG); 4078 } 4079 return SDValue(); 4080 } 4081 4082 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4083 const SDLoc &DL, 4084 SelectionDAG &DAG, bool Unpacked) { 4085 if (!LoadVT.isVector()) 4086 return Result; 4087 4088 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4089 // Truncate to v2i16/v4i16. 4090 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4091 4092 // Workaround legalizer not scalarizing truncate after vector op 4093 // legalization byt not creating intermediate vector trunc. 4094 SmallVector<SDValue, 4> Elts; 4095 DAG.ExtractVectorElements(Result, Elts); 4096 for (SDValue &Elt : Elts) 4097 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4098 4099 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4100 4101 // Bitcast to original type (v2f16/v4f16). 4102 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4103 } 4104 4105 // Cast back to the original packed type. 4106 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4107 } 4108 4109 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4110 MemSDNode *M, 4111 SelectionDAG &DAG, 4112 ArrayRef<SDValue> Ops, 4113 bool IsIntrinsic) const { 4114 SDLoc DL(M); 4115 4116 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4117 EVT LoadVT = M->getValueType(0); 4118 4119 EVT EquivLoadVT = LoadVT; 4120 if (Unpacked && LoadVT.isVector()) { 4121 EquivLoadVT = LoadVT.isVector() ? 4122 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4123 LoadVT.getVectorNumElements()) : LoadVT; 4124 } 4125 4126 // Change from v4f16/v2f16 to EquivLoadVT. 4127 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4128 4129 SDValue Load 4130 = DAG.getMemIntrinsicNode( 4131 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4132 VTList, Ops, M->getMemoryVT(), 4133 M->getMemOperand()); 4134 if (!Unpacked) // Just adjusted the opcode. 4135 return Load; 4136 4137 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4138 4139 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4140 } 4141 4142 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4143 SelectionDAG &DAG, 4144 ArrayRef<SDValue> Ops) const { 4145 SDLoc DL(M); 4146 EVT LoadVT = M->getValueType(0); 4147 EVT EltType = LoadVT.getScalarType(); 4148 EVT IntVT = LoadVT.changeTypeToInteger(); 4149 4150 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4151 4152 unsigned Opc = 4153 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4154 4155 if (IsD16) { 4156 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4157 } 4158 4159 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4160 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4161 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4162 4163 if (isTypeLegal(LoadVT)) { 4164 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4165 M->getMemOperand(), DAG); 4166 } 4167 4168 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4169 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4170 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4171 M->getMemOperand(), DAG); 4172 return DAG.getMergeValues( 4173 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4174 DL); 4175 } 4176 4177 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4178 SDNode *N, SelectionDAG &DAG) { 4179 EVT VT = N->getValueType(0); 4180 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4181 int CondCode = CD->getSExtValue(); 4182 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4183 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4184 return DAG.getUNDEF(VT); 4185 4186 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4187 4188 SDValue LHS = N->getOperand(1); 4189 SDValue RHS = N->getOperand(2); 4190 4191 SDLoc DL(N); 4192 4193 EVT CmpVT = LHS.getValueType(); 4194 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4195 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4196 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4197 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4198 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4199 } 4200 4201 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4202 4203 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4204 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4205 4206 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4207 DAG.getCondCode(CCOpcode)); 4208 if (VT.bitsEq(CCVT)) 4209 return SetCC; 4210 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4211 } 4212 4213 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4214 SDNode *N, SelectionDAG &DAG) { 4215 EVT VT = N->getValueType(0); 4216 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4217 4218 int CondCode = CD->getSExtValue(); 4219 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4220 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4221 return DAG.getUNDEF(VT); 4222 } 4223 4224 SDValue Src0 = N->getOperand(1); 4225 SDValue Src1 = N->getOperand(2); 4226 EVT CmpVT = Src0.getValueType(); 4227 SDLoc SL(N); 4228 4229 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4230 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4231 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4232 } 4233 4234 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4235 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4236 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4237 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4238 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4239 Src1, DAG.getCondCode(CCOpcode)); 4240 if (VT.bitsEq(CCVT)) 4241 return SetCC; 4242 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4243 } 4244 4245 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4246 SmallVectorImpl<SDValue> &Results, 4247 SelectionDAG &DAG) const { 4248 switch (N->getOpcode()) { 4249 case ISD::INSERT_VECTOR_ELT: { 4250 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4251 Results.push_back(Res); 4252 return; 4253 } 4254 case ISD::EXTRACT_VECTOR_ELT: { 4255 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4256 Results.push_back(Res); 4257 return; 4258 } 4259 case ISD::INTRINSIC_WO_CHAIN: { 4260 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4261 switch (IID) { 4262 case Intrinsic::amdgcn_cvt_pkrtz: { 4263 SDValue Src0 = N->getOperand(1); 4264 SDValue Src1 = N->getOperand(2); 4265 SDLoc SL(N); 4266 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4267 Src0, Src1); 4268 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4269 return; 4270 } 4271 case Intrinsic::amdgcn_cvt_pknorm_i16: 4272 case Intrinsic::amdgcn_cvt_pknorm_u16: 4273 case Intrinsic::amdgcn_cvt_pk_i16: 4274 case Intrinsic::amdgcn_cvt_pk_u16: { 4275 SDValue Src0 = N->getOperand(1); 4276 SDValue Src1 = N->getOperand(2); 4277 SDLoc SL(N); 4278 unsigned Opcode; 4279 4280 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4281 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4282 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4283 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4284 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4285 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4286 else 4287 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4288 4289 EVT VT = N->getValueType(0); 4290 if (isTypeLegal(VT)) 4291 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4292 else { 4293 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4294 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4295 } 4296 return; 4297 } 4298 } 4299 break; 4300 } 4301 case ISD::INTRINSIC_W_CHAIN: { 4302 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4303 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4304 // FIXME: Hacky 4305 Results.push_back(Res.getOperand(0)); 4306 Results.push_back(Res.getOperand(1)); 4307 } else { 4308 Results.push_back(Res); 4309 Results.push_back(Res.getValue(1)); 4310 } 4311 return; 4312 } 4313 4314 break; 4315 } 4316 case ISD::SELECT: { 4317 SDLoc SL(N); 4318 EVT VT = N->getValueType(0); 4319 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4320 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4321 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4322 4323 EVT SelectVT = NewVT; 4324 if (NewVT.bitsLT(MVT::i32)) { 4325 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4326 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4327 SelectVT = MVT::i32; 4328 } 4329 4330 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4331 N->getOperand(0), LHS, RHS); 4332 4333 if (NewVT != SelectVT) 4334 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4335 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4336 return; 4337 } 4338 case ISD::FNEG: { 4339 if (N->getValueType(0) != MVT::v2f16) 4340 break; 4341 4342 SDLoc SL(N); 4343 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4344 4345 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4346 BC, 4347 DAG.getConstant(0x80008000, SL, MVT::i32)); 4348 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4349 return; 4350 } 4351 case ISD::FABS: { 4352 if (N->getValueType(0) != MVT::v2f16) 4353 break; 4354 4355 SDLoc SL(N); 4356 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4357 4358 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4359 BC, 4360 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4361 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4362 return; 4363 } 4364 default: 4365 break; 4366 } 4367 } 4368 4369 /// Helper function for LowerBRCOND 4370 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4371 4372 SDNode *Parent = Value.getNode(); 4373 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4374 I != E; ++I) { 4375 4376 if (I.getUse().get() != Value) 4377 continue; 4378 4379 if (I->getOpcode() == Opcode) 4380 return *I; 4381 } 4382 return nullptr; 4383 } 4384 4385 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4386 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4387 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4388 case Intrinsic::amdgcn_if: 4389 return AMDGPUISD::IF; 4390 case Intrinsic::amdgcn_else: 4391 return AMDGPUISD::ELSE; 4392 case Intrinsic::amdgcn_loop: 4393 return AMDGPUISD::LOOP; 4394 case Intrinsic::amdgcn_end_cf: 4395 llvm_unreachable("should not occur"); 4396 default: 4397 return 0; 4398 } 4399 } 4400 4401 // break, if_break, else_break are all only used as inputs to loop, not 4402 // directly as branch conditions. 4403 return 0; 4404 } 4405 4406 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4407 const Triple &TT = getTargetMachine().getTargetTriple(); 4408 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4409 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4410 AMDGPU::shouldEmitConstantsToTextSection(TT); 4411 } 4412 4413 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4414 // FIXME: Either avoid relying on address space here or change the default 4415 // address space for functions to avoid the explicit check. 4416 return (GV->getValueType()->isFunctionTy() || 4417 GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4418 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4419 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4420 !shouldEmitFixup(GV) && 4421 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4422 } 4423 4424 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4425 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4426 } 4427 4428 /// This transforms the control flow intrinsics to get the branch destination as 4429 /// last parameter, also switches branch target with BR if the need arise 4430 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4431 SelectionDAG &DAG) const { 4432 SDLoc DL(BRCOND); 4433 4434 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4435 SDValue Target = BRCOND.getOperand(2); 4436 SDNode *BR = nullptr; 4437 SDNode *SetCC = nullptr; 4438 4439 if (Intr->getOpcode() == ISD::SETCC) { 4440 // As long as we negate the condition everything is fine 4441 SetCC = Intr; 4442 Intr = SetCC->getOperand(0).getNode(); 4443 4444 } else { 4445 // Get the target from BR if we don't negate the condition 4446 BR = findUser(BRCOND, ISD::BR); 4447 Target = BR->getOperand(1); 4448 } 4449 4450 // FIXME: This changes the types of the intrinsics instead of introducing new 4451 // nodes with the correct types. 4452 // e.g. llvm.amdgcn.loop 4453 4454 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4455 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4456 4457 unsigned CFNode = isCFIntrinsic(Intr); 4458 if (CFNode == 0) { 4459 // This is a uniform branch so we don't need to legalize. 4460 return BRCOND; 4461 } 4462 4463 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4464 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4465 4466 assert(!SetCC || 4467 (SetCC->getConstantOperandVal(1) == 1 && 4468 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4469 ISD::SETNE)); 4470 4471 // operands of the new intrinsic call 4472 SmallVector<SDValue, 4> Ops; 4473 if (HaveChain) 4474 Ops.push_back(BRCOND.getOperand(0)); 4475 4476 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4477 Ops.push_back(Target); 4478 4479 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4480 4481 // build the new intrinsic call 4482 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4483 4484 if (!HaveChain) { 4485 SDValue Ops[] = { 4486 SDValue(Result, 0), 4487 BRCOND.getOperand(0) 4488 }; 4489 4490 Result = DAG.getMergeValues(Ops, DL).getNode(); 4491 } 4492 4493 if (BR) { 4494 // Give the branch instruction our target 4495 SDValue Ops[] = { 4496 BR->getOperand(0), 4497 BRCOND.getOperand(2) 4498 }; 4499 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4500 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4501 BR = NewBR.getNode(); 4502 } 4503 4504 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4505 4506 // Copy the intrinsic results to registers 4507 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4508 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4509 if (!CopyToReg) 4510 continue; 4511 4512 Chain = DAG.getCopyToReg( 4513 Chain, DL, 4514 CopyToReg->getOperand(1), 4515 SDValue(Result, i - 1), 4516 SDValue()); 4517 4518 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4519 } 4520 4521 // Remove the old intrinsic from the chain 4522 DAG.ReplaceAllUsesOfValueWith( 4523 SDValue(Intr, Intr->getNumValues() - 1), 4524 Intr->getOperand(0)); 4525 4526 return Chain; 4527 } 4528 4529 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4530 SelectionDAG &DAG) const { 4531 MVT VT = Op.getSimpleValueType(); 4532 SDLoc DL(Op); 4533 // Checking the depth 4534 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4535 return DAG.getConstant(0, DL, VT); 4536 4537 MachineFunction &MF = DAG.getMachineFunction(); 4538 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4539 // Check for kernel and shader functions 4540 if (Info->isEntryFunction()) 4541 return DAG.getConstant(0, DL, VT); 4542 4543 MachineFrameInfo &MFI = MF.getFrameInfo(); 4544 // There is a call to @llvm.returnaddress in this function 4545 MFI.setReturnAddressIsTaken(true); 4546 4547 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4548 // Get the return address reg and mark it as an implicit live-in 4549 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4550 4551 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4552 } 4553 4554 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4555 SDValue Op, 4556 const SDLoc &DL, 4557 EVT VT) const { 4558 return Op.getValueType().bitsLE(VT) ? 4559 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4560 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4561 } 4562 4563 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4564 assert(Op.getValueType() == MVT::f16 && 4565 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4566 4567 SDValue Src = Op.getOperand(0); 4568 EVT SrcVT = Src.getValueType(); 4569 if (SrcVT != MVT::f64) 4570 return Op; 4571 4572 SDLoc DL(Op); 4573 4574 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4575 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4576 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4577 } 4578 4579 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4580 SelectionDAG &DAG) const { 4581 EVT VT = Op.getValueType(); 4582 const MachineFunction &MF = DAG.getMachineFunction(); 4583 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4584 bool IsIEEEMode = Info->getMode().IEEE; 4585 4586 // FIXME: Assert during eslection that this is only selected for 4587 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4588 // mode functions, but this happens to be OK since it's only done in cases 4589 // where there is known no sNaN. 4590 if (IsIEEEMode) 4591 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4592 4593 if (VT == MVT::v4f16) 4594 return splitBinaryVectorOp(Op, DAG); 4595 return Op; 4596 } 4597 4598 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4599 SDLoc SL(Op); 4600 SDValue Chain = Op.getOperand(0); 4601 4602 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4603 !Subtarget->isTrapHandlerEnabled()) 4604 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4605 4606 MachineFunction &MF = DAG.getMachineFunction(); 4607 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4608 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4609 assert(UserSGPR != AMDGPU::NoRegister); 4610 SDValue QueuePtr = CreateLiveInRegister( 4611 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4612 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4613 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4614 QueuePtr, SDValue()); 4615 SDValue Ops[] = { 4616 ToReg, 4617 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4618 SGPR01, 4619 ToReg.getValue(1) 4620 }; 4621 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4622 } 4623 4624 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4625 SDLoc SL(Op); 4626 SDValue Chain = Op.getOperand(0); 4627 MachineFunction &MF = DAG.getMachineFunction(); 4628 4629 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4630 !Subtarget->isTrapHandlerEnabled()) { 4631 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4632 "debugtrap handler not supported", 4633 Op.getDebugLoc(), 4634 DS_Warning); 4635 LLVMContext &Ctx = MF.getFunction().getContext(); 4636 Ctx.diagnose(NoTrap); 4637 return Chain; 4638 } 4639 4640 SDValue Ops[] = { 4641 Chain, 4642 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4643 }; 4644 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4645 } 4646 4647 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4648 SelectionDAG &DAG) const { 4649 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4650 if (Subtarget->hasApertureRegs()) { 4651 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4652 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4653 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4654 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4655 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4656 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4657 unsigned Encoding = 4658 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4659 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4660 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4661 4662 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4663 SDValue ApertureReg = SDValue( 4664 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4665 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4666 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4667 } 4668 4669 MachineFunction &MF = DAG.getMachineFunction(); 4670 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4671 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4672 assert(UserSGPR != AMDGPU::NoRegister); 4673 4674 SDValue QueuePtr = CreateLiveInRegister( 4675 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4676 4677 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4678 // private_segment_aperture_base_hi. 4679 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4680 4681 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4682 4683 // TODO: Use custom target PseudoSourceValue. 4684 // TODO: We should use the value from the IR intrinsic call, but it might not 4685 // be available and how do we get it? 4686 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4687 AMDGPUAS::CONSTANT_ADDRESS)); 4688 4689 MachinePointerInfo PtrInfo(V, StructOffset); 4690 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4691 MinAlign(64, StructOffset), 4692 MachineMemOperand::MODereferenceable | 4693 MachineMemOperand::MOInvariant); 4694 } 4695 4696 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4697 SelectionDAG &DAG) const { 4698 SDLoc SL(Op); 4699 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4700 4701 SDValue Src = ASC->getOperand(0); 4702 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4703 4704 const AMDGPUTargetMachine &TM = 4705 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4706 4707 // flat -> local/private 4708 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4709 unsigned DestAS = ASC->getDestAddressSpace(); 4710 4711 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4712 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4713 unsigned NullVal = TM.getNullPointerValue(DestAS); 4714 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4715 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4716 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4717 4718 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4719 NonNull, Ptr, SegmentNullPtr); 4720 } 4721 } 4722 4723 // local/private -> flat 4724 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4725 unsigned SrcAS = ASC->getSrcAddressSpace(); 4726 4727 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4728 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4729 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4730 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4731 4732 SDValue NonNull 4733 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4734 4735 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4736 SDValue CvtPtr 4737 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4738 4739 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4740 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4741 FlatNullPtr); 4742 } 4743 } 4744 4745 // global <-> flat are no-ops and never emitted. 4746 4747 const MachineFunction &MF = DAG.getMachineFunction(); 4748 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4749 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4750 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4751 4752 return DAG.getUNDEF(ASC->getValueType(0)); 4753 } 4754 4755 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4756 // the small vector and inserting them into the big vector. That is better than 4757 // the default expansion of doing it via a stack slot. Even though the use of 4758 // the stack slot would be optimized away afterwards, the stack slot itself 4759 // remains. 4760 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4761 SelectionDAG &DAG) const { 4762 SDValue Vec = Op.getOperand(0); 4763 SDValue Ins = Op.getOperand(1); 4764 SDValue Idx = Op.getOperand(2); 4765 EVT VecVT = Vec.getValueType(); 4766 EVT InsVT = Ins.getValueType(); 4767 EVT EltVT = VecVT.getVectorElementType(); 4768 unsigned InsNumElts = InsVT.getVectorNumElements(); 4769 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4770 SDLoc SL(Op); 4771 4772 for (unsigned I = 0; I != InsNumElts; ++I) { 4773 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4774 DAG.getConstant(I, SL, MVT::i32)); 4775 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4776 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4777 } 4778 return Vec; 4779 } 4780 4781 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4782 SelectionDAG &DAG) const { 4783 SDValue Vec = Op.getOperand(0); 4784 SDValue InsVal = Op.getOperand(1); 4785 SDValue Idx = Op.getOperand(2); 4786 EVT VecVT = Vec.getValueType(); 4787 EVT EltVT = VecVT.getVectorElementType(); 4788 unsigned VecSize = VecVT.getSizeInBits(); 4789 unsigned EltSize = EltVT.getSizeInBits(); 4790 4791 4792 assert(VecSize <= 64); 4793 4794 unsigned NumElts = VecVT.getVectorNumElements(); 4795 SDLoc SL(Op); 4796 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4797 4798 if (NumElts == 4 && EltSize == 16 && KIdx) { 4799 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4800 4801 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4802 DAG.getConstant(0, SL, MVT::i32)); 4803 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4804 DAG.getConstant(1, SL, MVT::i32)); 4805 4806 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4807 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4808 4809 unsigned Idx = KIdx->getZExtValue(); 4810 bool InsertLo = Idx < 2; 4811 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4812 InsertLo ? LoVec : HiVec, 4813 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4814 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4815 4816 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4817 4818 SDValue Concat = InsertLo ? 4819 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4820 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4821 4822 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4823 } 4824 4825 if (isa<ConstantSDNode>(Idx)) 4826 return SDValue(); 4827 4828 MVT IntVT = MVT::getIntegerVT(VecSize); 4829 4830 // Avoid stack access for dynamic indexing. 4831 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4832 4833 // Create a congruent vector with the target value in each element so that 4834 // the required element can be masked and ORed into the target vector. 4835 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4836 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4837 4838 assert(isPowerOf2_32(EltSize)); 4839 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4840 4841 // Convert vector index to bit-index. 4842 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4843 4844 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4845 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4846 DAG.getConstant(0xffff, SL, IntVT), 4847 ScaledIdx); 4848 4849 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4850 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4851 DAG.getNOT(SL, BFM, IntVT), BCVec); 4852 4853 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4854 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4855 } 4856 4857 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4858 SelectionDAG &DAG) const { 4859 SDLoc SL(Op); 4860 4861 EVT ResultVT = Op.getValueType(); 4862 SDValue Vec = Op.getOperand(0); 4863 SDValue Idx = Op.getOperand(1); 4864 EVT VecVT = Vec.getValueType(); 4865 unsigned VecSize = VecVT.getSizeInBits(); 4866 EVT EltVT = VecVT.getVectorElementType(); 4867 assert(VecSize <= 64); 4868 4869 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4870 4871 // Make sure we do any optimizations that will make it easier to fold 4872 // source modifiers before obscuring it with bit operations. 4873 4874 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4875 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4876 return Combined; 4877 4878 unsigned EltSize = EltVT.getSizeInBits(); 4879 assert(isPowerOf2_32(EltSize)); 4880 4881 MVT IntVT = MVT::getIntegerVT(VecSize); 4882 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4883 4884 // Convert vector index to bit-index (* EltSize) 4885 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4886 4887 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4888 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4889 4890 if (ResultVT == MVT::f16) { 4891 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4892 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4893 } 4894 4895 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4896 } 4897 4898 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4899 assert(Elt % 2 == 0); 4900 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4901 } 4902 4903 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4904 SelectionDAG &DAG) const { 4905 SDLoc SL(Op); 4906 EVT ResultVT = Op.getValueType(); 4907 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4908 4909 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4910 EVT EltVT = PackVT.getVectorElementType(); 4911 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4912 4913 // vector_shuffle <0,1,6,7> lhs, rhs 4914 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4915 // 4916 // vector_shuffle <6,7,2,3> lhs, rhs 4917 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4918 // 4919 // vector_shuffle <6,7,0,1> lhs, rhs 4920 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4921 4922 // Avoid scalarizing when both halves are reading from consecutive elements. 4923 SmallVector<SDValue, 4> Pieces; 4924 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4925 if (elementPairIsContiguous(SVN->getMask(), I)) { 4926 const int Idx = SVN->getMaskElt(I); 4927 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4928 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4929 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4930 PackVT, SVN->getOperand(VecIdx), 4931 DAG.getConstant(EltIdx, SL, MVT::i32)); 4932 Pieces.push_back(SubVec); 4933 } else { 4934 const int Idx0 = SVN->getMaskElt(I); 4935 const int Idx1 = SVN->getMaskElt(I + 1); 4936 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4937 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4938 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4939 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4940 4941 SDValue Vec0 = SVN->getOperand(VecIdx0); 4942 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4943 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4944 4945 SDValue Vec1 = SVN->getOperand(VecIdx1); 4946 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4947 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4948 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4949 } 4950 } 4951 4952 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4953 } 4954 4955 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4956 SelectionDAG &DAG) const { 4957 SDLoc SL(Op); 4958 EVT VT = Op.getValueType(); 4959 4960 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4961 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4962 4963 // Turn into pair of packed build_vectors. 4964 // TODO: Special case for constants that can be materialized with s_mov_b64. 4965 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4966 { Op.getOperand(0), Op.getOperand(1) }); 4967 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4968 { Op.getOperand(2), Op.getOperand(3) }); 4969 4970 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4971 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4972 4973 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4974 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4975 } 4976 4977 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4978 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4979 4980 SDValue Lo = Op.getOperand(0); 4981 SDValue Hi = Op.getOperand(1); 4982 4983 // Avoid adding defined bits with the zero_extend. 4984 if (Hi.isUndef()) { 4985 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4986 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4987 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4988 } 4989 4990 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4991 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4992 4993 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4994 DAG.getConstant(16, SL, MVT::i32)); 4995 if (Lo.isUndef()) 4996 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4997 4998 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4999 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5000 5001 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5002 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5003 } 5004 5005 bool 5006 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5007 // We can fold offsets for anything that doesn't require a GOT relocation. 5008 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5009 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5010 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5011 !shouldEmitGOTReloc(GA->getGlobal()); 5012 } 5013 5014 static SDValue 5015 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5016 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5017 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5018 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5019 // lowered to the following code sequence: 5020 // 5021 // For constant address space: 5022 // s_getpc_b64 s[0:1] 5023 // s_add_u32 s0, s0, $symbol 5024 // s_addc_u32 s1, s1, 0 5025 // 5026 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5027 // a fixup or relocation is emitted to replace $symbol with a literal 5028 // constant, which is a pc-relative offset from the encoding of the $symbol 5029 // operand to the global variable. 5030 // 5031 // For global address space: 5032 // s_getpc_b64 s[0:1] 5033 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5034 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5035 // 5036 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5037 // fixups or relocations are emitted to replace $symbol@*@lo and 5038 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5039 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5040 // operand to the global variable. 5041 // 5042 // What we want here is an offset from the value returned by s_getpc 5043 // (which is the address of the s_add_u32 instruction) to the global 5044 // variable, but since the encoding of $symbol starts 4 bytes after the start 5045 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5046 // small. This requires us to add 4 to the global variable offset in order to 5047 // compute the correct address. 5048 SDValue PtrLo = 5049 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5050 SDValue PtrHi; 5051 if (GAFlags == SIInstrInfo::MO_NONE) { 5052 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5053 } else { 5054 PtrHi = 5055 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5056 } 5057 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5058 } 5059 5060 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5061 SDValue Op, 5062 SelectionDAG &DAG) const { 5063 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5064 const GlobalValue *GV = GSD->getGlobal(); 5065 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5066 (!GV->hasExternalLinkage() || 5067 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 5068 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 5069 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5070 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5071 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5072 5073 SDLoc DL(GSD); 5074 EVT PtrVT = Op.getValueType(); 5075 5076 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5077 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5078 SIInstrInfo::MO_ABS32_LO); 5079 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5080 } 5081 5082 if (shouldEmitFixup(GV)) 5083 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5084 else if (shouldEmitPCReloc(GV)) 5085 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5086 SIInstrInfo::MO_REL32); 5087 5088 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5089 SIInstrInfo::MO_GOTPCREL32); 5090 5091 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5092 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5093 const DataLayout &DataLayout = DAG.getDataLayout(); 5094 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5095 MachinePointerInfo PtrInfo 5096 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5097 5098 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5099 MachineMemOperand::MODereferenceable | 5100 MachineMemOperand::MOInvariant); 5101 } 5102 5103 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5104 const SDLoc &DL, SDValue V) const { 5105 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5106 // the destination register. 5107 // 5108 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5109 // so we will end up with redundant moves to m0. 5110 // 5111 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5112 5113 // A Null SDValue creates a glue result. 5114 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5115 V, Chain); 5116 return SDValue(M0, 0); 5117 } 5118 5119 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5120 SDValue Op, 5121 MVT VT, 5122 unsigned Offset) const { 5123 SDLoc SL(Op); 5124 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5125 DAG.getEntryNode(), Offset, 4, false); 5126 // The local size values will have the hi 16-bits as zero. 5127 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5128 DAG.getValueType(VT)); 5129 } 5130 5131 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5132 EVT VT) { 5133 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5134 "non-hsa intrinsic with hsa target", 5135 DL.getDebugLoc()); 5136 DAG.getContext()->diagnose(BadIntrin); 5137 return DAG.getUNDEF(VT); 5138 } 5139 5140 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5141 EVT VT) { 5142 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5143 "intrinsic not supported on subtarget", 5144 DL.getDebugLoc()); 5145 DAG.getContext()->diagnose(BadIntrin); 5146 return DAG.getUNDEF(VT); 5147 } 5148 5149 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5150 ArrayRef<SDValue> Elts) { 5151 assert(!Elts.empty()); 5152 MVT Type; 5153 unsigned NumElts; 5154 5155 if (Elts.size() == 1) { 5156 Type = MVT::f32; 5157 NumElts = 1; 5158 } else if (Elts.size() == 2) { 5159 Type = MVT::v2f32; 5160 NumElts = 2; 5161 } else if (Elts.size() <= 4) { 5162 Type = MVT::v4f32; 5163 NumElts = 4; 5164 } else if (Elts.size() <= 8) { 5165 Type = MVT::v8f32; 5166 NumElts = 8; 5167 } else { 5168 assert(Elts.size() <= 16); 5169 Type = MVT::v16f32; 5170 NumElts = 16; 5171 } 5172 5173 SmallVector<SDValue, 16> VecElts(NumElts); 5174 for (unsigned i = 0; i < Elts.size(); ++i) { 5175 SDValue Elt = Elts[i]; 5176 if (Elt.getValueType() != MVT::f32) 5177 Elt = DAG.getBitcast(MVT::f32, Elt); 5178 VecElts[i] = Elt; 5179 } 5180 for (unsigned i = Elts.size(); i < NumElts; ++i) 5181 VecElts[i] = DAG.getUNDEF(MVT::f32); 5182 5183 if (NumElts == 1) 5184 return VecElts[0]; 5185 return DAG.getBuildVector(Type, DL, VecElts); 5186 } 5187 5188 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5189 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5190 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5191 5192 uint64_t Value = CachePolicyConst->getZExtValue(); 5193 SDLoc DL(CachePolicy); 5194 if (GLC) { 5195 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5196 Value &= ~(uint64_t)0x1; 5197 } 5198 if (SLC) { 5199 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5200 Value &= ~(uint64_t)0x2; 5201 } 5202 if (DLC) { 5203 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5204 Value &= ~(uint64_t)0x4; 5205 } 5206 5207 return Value == 0; 5208 } 5209 5210 // Re-construct the required return value for a image load intrinsic. 5211 // This is more complicated due to the optional use TexFailCtrl which means the required 5212 // return type is an aggregate 5213 static SDValue constructRetValue(SelectionDAG &DAG, 5214 MachineSDNode *Result, 5215 ArrayRef<EVT> ResultTypes, 5216 bool IsTexFail, bool Unpacked, bool IsD16, 5217 int DMaskPop, int NumVDataDwords, 5218 const SDLoc &DL, LLVMContext &Context) { 5219 // Determine the required return type. This is the same regardless of IsTexFail flag 5220 EVT ReqRetVT = ResultTypes[0]; 5221 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5222 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5223 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5224 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5225 : AdjEltVT 5226 : ReqRetVT; 5227 5228 // Extract data part of the result 5229 // Bitcast the result to the same type as the required return type 5230 int NumElts; 5231 if (IsD16 && !Unpacked) 5232 NumElts = NumVDataDwords << 1; 5233 else 5234 NumElts = NumVDataDwords; 5235 5236 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5237 : AdjEltVT; 5238 5239 // Special case for v6f16. Rather than add support for this, use v3i32 to 5240 // extract the data elements 5241 bool V6F16Special = false; 5242 if (NumElts == 6) { 5243 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5244 DMaskPop >>= 1; 5245 ReqRetNumElts >>= 1; 5246 V6F16Special = true; 5247 AdjVT = MVT::v2i32; 5248 } 5249 5250 SDValue N = SDValue(Result, 0); 5251 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5252 5253 // Iterate over the result 5254 SmallVector<SDValue, 4> BVElts; 5255 5256 if (CastVT.isVector()) { 5257 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5258 } else { 5259 BVElts.push_back(CastRes); 5260 } 5261 int ExtraElts = ReqRetNumElts - DMaskPop; 5262 while(ExtraElts--) 5263 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5264 5265 SDValue PreTFCRes; 5266 if (ReqRetNumElts > 1) { 5267 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5268 if (IsD16 && Unpacked) 5269 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5270 else 5271 PreTFCRes = NewVec; 5272 } else { 5273 PreTFCRes = BVElts[0]; 5274 } 5275 5276 if (V6F16Special) 5277 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5278 5279 if (!IsTexFail) { 5280 if (Result->getNumValues() > 1) 5281 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5282 else 5283 return PreTFCRes; 5284 } 5285 5286 // Extract the TexFail result and insert into aggregate return 5287 SmallVector<SDValue, 1> TFCElt; 5288 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5289 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5290 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5291 } 5292 5293 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5294 SDValue *LWE, bool &IsTexFail) { 5295 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5296 5297 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5298 if (Value) { 5299 IsTexFail = true; 5300 } 5301 5302 SDLoc DL(TexFailCtrlConst); 5303 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5304 Value &= ~(uint64_t)0x1; 5305 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5306 Value &= ~(uint64_t)0x2; 5307 5308 return Value == 0; 5309 } 5310 5311 SDValue SITargetLowering::lowerImage(SDValue Op, 5312 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5313 SelectionDAG &DAG) const { 5314 SDLoc DL(Op); 5315 MachineFunction &MF = DAG.getMachineFunction(); 5316 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5317 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5318 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5319 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5320 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5321 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5322 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5323 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5324 unsigned IntrOpcode = Intr->BaseOpcode; 5325 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5326 5327 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5328 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5329 bool IsD16 = false; 5330 bool IsA16 = false; 5331 SDValue VData; 5332 int NumVDataDwords; 5333 bool AdjustRetType = false; 5334 5335 unsigned AddrIdx; // Index of first address argument 5336 unsigned DMask; 5337 unsigned DMaskLanes = 0; 5338 5339 if (BaseOpcode->Atomic) { 5340 VData = Op.getOperand(2); 5341 5342 bool Is64Bit = VData.getValueType() == MVT::i64; 5343 if (BaseOpcode->AtomicX2) { 5344 SDValue VData2 = Op.getOperand(3); 5345 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5346 {VData, VData2}); 5347 if (Is64Bit) 5348 VData = DAG.getBitcast(MVT::v4i32, VData); 5349 5350 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5351 DMask = Is64Bit ? 0xf : 0x3; 5352 NumVDataDwords = Is64Bit ? 4 : 2; 5353 AddrIdx = 4; 5354 } else { 5355 DMask = Is64Bit ? 0x3 : 0x1; 5356 NumVDataDwords = Is64Bit ? 2 : 1; 5357 AddrIdx = 3; 5358 } 5359 } else { 5360 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5361 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5362 DMask = DMaskConst->getZExtValue(); 5363 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5364 5365 if (BaseOpcode->Store) { 5366 VData = Op.getOperand(2); 5367 5368 MVT StoreVT = VData.getSimpleValueType(); 5369 if (StoreVT.getScalarType() == MVT::f16) { 5370 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5371 return Op; // D16 is unsupported for this instruction 5372 5373 IsD16 = true; 5374 VData = handleD16VData(VData, DAG); 5375 } 5376 5377 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5378 } else { 5379 // Work out the num dwords based on the dmask popcount and underlying type 5380 // and whether packing is supported. 5381 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5382 if (LoadVT.getScalarType() == MVT::f16) { 5383 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5384 return Op; // D16 is unsupported for this instruction 5385 5386 IsD16 = true; 5387 } 5388 5389 // Confirm that the return type is large enough for the dmask specified 5390 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5391 (!LoadVT.isVector() && DMaskLanes > 1)) 5392 return Op; 5393 5394 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5395 NumVDataDwords = (DMaskLanes + 1) / 2; 5396 else 5397 NumVDataDwords = DMaskLanes; 5398 5399 AdjustRetType = true; 5400 } 5401 5402 AddrIdx = DMaskIdx + 1; 5403 } 5404 5405 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5406 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5407 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5408 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5409 NumCoords + NumLCM; 5410 unsigned NumMIVAddrs = NumVAddrs; 5411 5412 SmallVector<SDValue, 4> VAddrs; 5413 5414 // Optimize _L to _LZ when _L is zero 5415 if (LZMappingInfo) { 5416 if (auto ConstantLod = 5417 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5418 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5419 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5420 NumMIVAddrs--; // remove 'lod' 5421 } 5422 } 5423 } 5424 5425 // Optimize _mip away, when 'lod' is zero 5426 if (MIPMappingInfo) { 5427 if (auto ConstantLod = 5428 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5429 if (ConstantLod->isNullValue()) { 5430 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5431 NumMIVAddrs--; // remove 'lod' 5432 } 5433 } 5434 } 5435 5436 // Check for 16 bit addresses and pack if true. 5437 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5438 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5439 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5440 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5441 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5442 IsA16 = true; 5443 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5444 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5445 SDValue AddrLo, AddrHi; 5446 // Push back extra arguments. 5447 if (i < DimIdx) { 5448 AddrLo = Op.getOperand(i); 5449 } else { 5450 AddrLo = Op.getOperand(i); 5451 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5452 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5453 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5454 ((NumGradients / 2) % 2 == 1 && 5455 (i == DimIdx + (NumGradients / 2) - 1 || 5456 i == DimIdx + NumGradients - 1))) { 5457 AddrHi = DAG.getUNDEF(MVT::f16); 5458 } else { 5459 AddrHi = Op.getOperand(i + 1); 5460 i++; 5461 } 5462 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5463 {AddrLo, AddrHi}); 5464 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5465 } 5466 VAddrs.push_back(AddrLo); 5467 } 5468 } else { 5469 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5470 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5471 } 5472 5473 // If the register allocator cannot place the address registers contiguously 5474 // without introducing moves, then using the non-sequential address encoding 5475 // is always preferable, since it saves VALU instructions and is usually a 5476 // wash in terms of code size or even better. 5477 // 5478 // However, we currently have no way of hinting to the register allocator that 5479 // MIMG addresses should be placed contiguously when it is possible to do so, 5480 // so force non-NSA for the common 2-address case as a heuristic. 5481 // 5482 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5483 // allocation when possible. 5484 bool UseNSA = 5485 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5486 SDValue VAddr; 5487 if (!UseNSA) 5488 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5489 5490 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5491 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5492 unsigned CtrlIdx; // Index of texfailctrl argument 5493 SDValue Unorm; 5494 if (!BaseOpcode->Sampler) { 5495 Unorm = True; 5496 CtrlIdx = AddrIdx + NumVAddrs + 1; 5497 } else { 5498 auto UnormConst = 5499 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5500 5501 Unorm = UnormConst->getZExtValue() ? True : False; 5502 CtrlIdx = AddrIdx + NumVAddrs + 3; 5503 } 5504 5505 SDValue TFE; 5506 SDValue LWE; 5507 SDValue TexFail = Op.getOperand(CtrlIdx); 5508 bool IsTexFail = false; 5509 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5510 return Op; 5511 5512 if (IsTexFail) { 5513 if (!DMaskLanes) { 5514 // Expecting to get an error flag since TFC is on - and dmask is 0 5515 // Force dmask to be at least 1 otherwise the instruction will fail 5516 DMask = 0x1; 5517 DMaskLanes = 1; 5518 NumVDataDwords = 1; 5519 } 5520 NumVDataDwords += 1; 5521 AdjustRetType = true; 5522 } 5523 5524 // Has something earlier tagged that the return type needs adjusting 5525 // This happens if the instruction is a load or has set TexFailCtrl flags 5526 if (AdjustRetType) { 5527 // NumVDataDwords reflects the true number of dwords required in the return type 5528 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5529 // This is a no-op load. This can be eliminated 5530 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5531 if (isa<MemSDNode>(Op)) 5532 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5533 return Undef; 5534 } 5535 5536 EVT NewVT = NumVDataDwords > 1 ? 5537 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5538 : MVT::f32; 5539 5540 ResultTypes[0] = NewVT; 5541 if (ResultTypes.size() == 3) { 5542 // Original result was aggregate type used for TexFailCtrl results 5543 // The actual instruction returns as a vector type which has now been 5544 // created. Remove the aggregate result. 5545 ResultTypes.erase(&ResultTypes[1]); 5546 } 5547 } 5548 5549 SDValue GLC; 5550 SDValue SLC; 5551 SDValue DLC; 5552 if (BaseOpcode->Atomic) { 5553 GLC = True; // TODO no-return optimization 5554 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5555 IsGFX10 ? &DLC : nullptr)) 5556 return Op; 5557 } else { 5558 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5559 IsGFX10 ? &DLC : nullptr)) 5560 return Op; 5561 } 5562 5563 SmallVector<SDValue, 26> Ops; 5564 if (BaseOpcode->Store || BaseOpcode->Atomic) 5565 Ops.push_back(VData); // vdata 5566 if (UseNSA) { 5567 for (const SDValue &Addr : VAddrs) 5568 Ops.push_back(Addr); 5569 } else { 5570 Ops.push_back(VAddr); 5571 } 5572 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5573 if (BaseOpcode->Sampler) 5574 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5575 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5576 if (IsGFX10) 5577 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5578 Ops.push_back(Unorm); 5579 if (IsGFX10) 5580 Ops.push_back(DLC); 5581 Ops.push_back(GLC); 5582 Ops.push_back(SLC); 5583 Ops.push_back(IsA16 && // a16 or r128 5584 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5585 Ops.push_back(TFE); // tfe 5586 Ops.push_back(LWE); // lwe 5587 if (!IsGFX10) 5588 Ops.push_back(DimInfo->DA ? True : False); 5589 if (BaseOpcode->HasD16) 5590 Ops.push_back(IsD16 ? True : False); 5591 if (isa<MemSDNode>(Op)) 5592 Ops.push_back(Op.getOperand(0)); // chain 5593 5594 int NumVAddrDwords = 5595 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5596 int Opcode = -1; 5597 5598 if (IsGFX10) { 5599 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5600 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5601 : AMDGPU::MIMGEncGfx10Default, 5602 NumVDataDwords, NumVAddrDwords); 5603 } else { 5604 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5605 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5606 NumVDataDwords, NumVAddrDwords); 5607 if (Opcode == -1) 5608 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5609 NumVDataDwords, NumVAddrDwords); 5610 } 5611 assert(Opcode != -1); 5612 5613 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5614 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5615 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5616 DAG.setNodeMemRefs(NewNode, {MemRef}); 5617 } 5618 5619 if (BaseOpcode->AtomicX2) { 5620 SmallVector<SDValue, 1> Elt; 5621 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5622 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5623 } else if (!BaseOpcode->Store) { 5624 return constructRetValue(DAG, NewNode, 5625 OrigResultTypes, IsTexFail, 5626 Subtarget->hasUnpackedD16VMem(), IsD16, 5627 DMaskLanes, NumVDataDwords, DL, 5628 *DAG.getContext()); 5629 } 5630 5631 return SDValue(NewNode, 0); 5632 } 5633 5634 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5635 SDValue Offset, SDValue GLC, SDValue DLC, 5636 SelectionDAG &DAG) const { 5637 MachineFunction &MF = DAG.getMachineFunction(); 5638 MachineMemOperand *MMO = MF.getMachineMemOperand( 5639 MachinePointerInfo(), 5640 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5641 MachineMemOperand::MOInvariant, 5642 VT.getStoreSize(), VT.getStoreSize()); 5643 5644 if (!Offset->isDivergent()) { 5645 SDValue Ops[] = { 5646 Rsrc, 5647 Offset, // Offset 5648 GLC, 5649 DLC, 5650 }; 5651 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5652 DAG.getVTList(VT), Ops, VT, MMO); 5653 } 5654 5655 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5656 // assume that the buffer is unswizzled. 5657 SmallVector<SDValue, 4> Loads; 5658 unsigned NumLoads = 1; 5659 MVT LoadVT = VT.getSimpleVT(); 5660 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5661 assert((LoadVT.getScalarType() == MVT::i32 || 5662 LoadVT.getScalarType() == MVT::f32) && 5663 isPowerOf2_32(NumElts)); 5664 5665 if (NumElts == 8 || NumElts == 16) { 5666 NumLoads = NumElts == 16 ? 4 : 2; 5667 LoadVT = MVT::v4i32; 5668 } 5669 5670 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5671 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5672 SDValue Ops[] = { 5673 DAG.getEntryNode(), // Chain 5674 Rsrc, // rsrc 5675 DAG.getConstant(0, DL, MVT::i32), // vindex 5676 {}, // voffset 5677 {}, // soffset 5678 {}, // offset 5679 DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5680 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5681 }; 5682 5683 // Use the alignment to ensure that the required offsets will fit into the 5684 // immediate offsets. 5685 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5686 5687 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5688 for (unsigned i = 0; i < NumLoads; ++i) { 5689 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5690 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, 5691 Ops, LoadVT, MMO)); 5692 } 5693 5694 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5695 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5696 5697 return Loads[0]; 5698 } 5699 5700 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5701 SelectionDAG &DAG) const { 5702 MachineFunction &MF = DAG.getMachineFunction(); 5703 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5704 5705 EVT VT = Op.getValueType(); 5706 SDLoc DL(Op); 5707 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5708 5709 // TODO: Should this propagate fast-math-flags? 5710 5711 switch (IntrinsicID) { 5712 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5713 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5714 return emitNonHSAIntrinsicError(DAG, DL, VT); 5715 return getPreloadedValue(DAG, *MFI, VT, 5716 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5717 } 5718 case Intrinsic::amdgcn_dispatch_ptr: 5719 case Intrinsic::amdgcn_queue_ptr: { 5720 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5721 DiagnosticInfoUnsupported BadIntrin( 5722 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5723 DL.getDebugLoc()); 5724 DAG.getContext()->diagnose(BadIntrin); 5725 return DAG.getUNDEF(VT); 5726 } 5727 5728 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5729 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5730 return getPreloadedValue(DAG, *MFI, VT, RegID); 5731 } 5732 case Intrinsic::amdgcn_implicitarg_ptr: { 5733 if (MFI->isEntryFunction()) 5734 return getImplicitArgPtr(DAG, DL); 5735 return getPreloadedValue(DAG, *MFI, VT, 5736 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5737 } 5738 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5739 return getPreloadedValue(DAG, *MFI, VT, 5740 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5741 } 5742 case Intrinsic::amdgcn_dispatch_id: { 5743 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5744 } 5745 case Intrinsic::amdgcn_rcp: 5746 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5747 case Intrinsic::amdgcn_rsq: 5748 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5749 case Intrinsic::amdgcn_rsq_legacy: 5750 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5751 return emitRemovedIntrinsicError(DAG, DL, VT); 5752 5753 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5754 case Intrinsic::amdgcn_rcp_legacy: 5755 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5756 return emitRemovedIntrinsicError(DAG, DL, VT); 5757 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5758 case Intrinsic::amdgcn_rsq_clamp: { 5759 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5760 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5761 5762 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5763 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5764 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5765 5766 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5767 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5768 DAG.getConstantFP(Max, DL, VT)); 5769 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5770 DAG.getConstantFP(Min, DL, VT)); 5771 } 5772 case Intrinsic::r600_read_ngroups_x: 5773 if (Subtarget->isAmdHsaOS()) 5774 return emitNonHSAIntrinsicError(DAG, DL, VT); 5775 5776 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5777 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5778 case Intrinsic::r600_read_ngroups_y: 5779 if (Subtarget->isAmdHsaOS()) 5780 return emitNonHSAIntrinsicError(DAG, DL, VT); 5781 5782 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5783 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5784 case Intrinsic::r600_read_ngroups_z: 5785 if (Subtarget->isAmdHsaOS()) 5786 return emitNonHSAIntrinsicError(DAG, DL, VT); 5787 5788 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5789 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5790 case Intrinsic::r600_read_global_size_x: 5791 if (Subtarget->isAmdHsaOS()) 5792 return emitNonHSAIntrinsicError(DAG, DL, VT); 5793 5794 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5795 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5796 case Intrinsic::r600_read_global_size_y: 5797 if (Subtarget->isAmdHsaOS()) 5798 return emitNonHSAIntrinsicError(DAG, DL, VT); 5799 5800 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5801 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5802 case Intrinsic::r600_read_global_size_z: 5803 if (Subtarget->isAmdHsaOS()) 5804 return emitNonHSAIntrinsicError(DAG, DL, VT); 5805 5806 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5807 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5808 case Intrinsic::r600_read_local_size_x: 5809 if (Subtarget->isAmdHsaOS()) 5810 return emitNonHSAIntrinsicError(DAG, DL, VT); 5811 5812 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5813 SI::KernelInputOffsets::LOCAL_SIZE_X); 5814 case Intrinsic::r600_read_local_size_y: 5815 if (Subtarget->isAmdHsaOS()) 5816 return emitNonHSAIntrinsicError(DAG, DL, VT); 5817 5818 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5819 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5820 case Intrinsic::r600_read_local_size_z: 5821 if (Subtarget->isAmdHsaOS()) 5822 return emitNonHSAIntrinsicError(DAG, DL, VT); 5823 5824 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5825 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5826 case Intrinsic::amdgcn_workgroup_id_x: 5827 case Intrinsic::r600_read_tgid_x: 5828 return getPreloadedValue(DAG, *MFI, VT, 5829 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5830 case Intrinsic::amdgcn_workgroup_id_y: 5831 case Intrinsic::r600_read_tgid_y: 5832 return getPreloadedValue(DAG, *MFI, VT, 5833 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5834 case Intrinsic::amdgcn_workgroup_id_z: 5835 case Intrinsic::r600_read_tgid_z: 5836 return getPreloadedValue(DAG, *MFI, VT, 5837 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5838 case Intrinsic::amdgcn_workitem_id_x: 5839 case Intrinsic::r600_read_tidig_x: 5840 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5841 SDLoc(DAG.getEntryNode()), 5842 MFI->getArgInfo().WorkItemIDX); 5843 case Intrinsic::amdgcn_workitem_id_y: 5844 case Intrinsic::r600_read_tidig_y: 5845 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5846 SDLoc(DAG.getEntryNode()), 5847 MFI->getArgInfo().WorkItemIDY); 5848 case Intrinsic::amdgcn_workitem_id_z: 5849 case Intrinsic::r600_read_tidig_z: 5850 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5851 SDLoc(DAG.getEntryNode()), 5852 MFI->getArgInfo().WorkItemIDZ); 5853 case Intrinsic::amdgcn_wavefrontsize: 5854 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5855 SDLoc(Op), MVT::i32); 5856 case Intrinsic::amdgcn_s_buffer_load: { 5857 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5858 SDValue GLC; 5859 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5860 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5861 IsGFX10 ? &DLC : nullptr)) 5862 return Op; 5863 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5864 DAG); 5865 } 5866 case Intrinsic::amdgcn_fdiv_fast: 5867 return lowerFDIV_FAST(Op, DAG); 5868 case Intrinsic::amdgcn_interp_mov: { 5869 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5870 SDValue Glue = M0.getValue(1); 5871 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 5872 Op.getOperand(2), Op.getOperand(3), Glue); 5873 } 5874 case Intrinsic::amdgcn_interp_p1: { 5875 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5876 SDValue Glue = M0.getValue(1); 5877 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 5878 Op.getOperand(2), Op.getOperand(3), Glue); 5879 } 5880 case Intrinsic::amdgcn_interp_p2: { 5881 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5882 SDValue Glue = SDValue(M0.getNode(), 1); 5883 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 5884 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 5885 Glue); 5886 } 5887 case Intrinsic::amdgcn_interp_p1_f16: { 5888 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5889 SDValue Glue = M0.getValue(1); 5890 if (getSubtarget()->getLDSBankCount() == 16) { 5891 // 16 bank LDS 5892 SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 5893 DAG.getConstant(2, DL, MVT::i32), // P0 5894 Op.getOperand(2), // Attrchan 5895 Op.getOperand(3), // Attr 5896 Glue); 5897 SDValue Ops[] = { 5898 Op.getOperand(1), // Src0 5899 Op.getOperand(2), // Attrchan 5900 Op.getOperand(3), // Attr 5901 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5902 S, // Src2 - holds two f16 values selected by high 5903 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5904 Op.getOperand(4), // high 5905 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5906 DAG.getTargetConstant(0, DL, MVT::i32) // $omod 5907 }; 5908 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5909 } else { 5910 // 32 bank LDS 5911 SDValue Ops[] = { 5912 Op.getOperand(1), // Src0 5913 Op.getOperand(2), // Attrchan 5914 Op.getOperand(3), // Attr 5915 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5916 Op.getOperand(4), // high 5917 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5918 DAG.getTargetConstant(0, DL, MVT::i32), // $omod 5919 Glue 5920 }; 5921 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5922 } 5923 } 5924 case Intrinsic::amdgcn_interp_p2_f16: { 5925 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6)); 5926 SDValue Glue = SDValue(M0.getNode(), 1); 5927 SDValue Ops[] = { 5928 Op.getOperand(2), // Src0 5929 Op.getOperand(3), // Attrchan 5930 Op.getOperand(4), // Attr 5931 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5932 Op.getOperand(1), // Src2 5933 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5934 Op.getOperand(5), // high 5935 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5936 Glue 5937 }; 5938 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5939 } 5940 case Intrinsic::amdgcn_sin: 5941 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5942 5943 case Intrinsic::amdgcn_cos: 5944 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5945 5946 case Intrinsic::amdgcn_mul_u24: 5947 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5948 case Intrinsic::amdgcn_mul_i24: 5949 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5950 5951 case Intrinsic::amdgcn_log_clamp: { 5952 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5953 return SDValue(); 5954 5955 DiagnosticInfoUnsupported BadIntrin( 5956 MF.getFunction(), "intrinsic not supported on subtarget", 5957 DL.getDebugLoc()); 5958 DAG.getContext()->diagnose(BadIntrin); 5959 return DAG.getUNDEF(VT); 5960 } 5961 case Intrinsic::amdgcn_ldexp: 5962 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5963 Op.getOperand(1), Op.getOperand(2)); 5964 5965 case Intrinsic::amdgcn_fract: 5966 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5967 5968 case Intrinsic::amdgcn_class: 5969 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5970 Op.getOperand(1), Op.getOperand(2)); 5971 case Intrinsic::amdgcn_div_fmas: 5972 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5973 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5974 Op.getOperand(4)); 5975 5976 case Intrinsic::amdgcn_div_fixup: 5977 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5978 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5979 5980 case Intrinsic::amdgcn_trig_preop: 5981 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5982 Op.getOperand(1), Op.getOperand(2)); 5983 case Intrinsic::amdgcn_div_scale: { 5984 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5985 5986 // Translate to the operands expected by the machine instruction. The 5987 // first parameter must be the same as the first instruction. 5988 SDValue Numerator = Op.getOperand(1); 5989 SDValue Denominator = Op.getOperand(2); 5990 5991 // Note this order is opposite of the machine instruction's operations, 5992 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5993 // intrinsic has the numerator as the first operand to match a normal 5994 // division operation. 5995 5996 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5997 5998 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5999 Denominator, Numerator); 6000 } 6001 case Intrinsic::amdgcn_icmp: { 6002 // There is a Pat that handles this variant, so return it as-is. 6003 if (Op.getOperand(1).getValueType() == MVT::i1 && 6004 Op.getConstantOperandVal(2) == 0 && 6005 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6006 return Op; 6007 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6008 } 6009 case Intrinsic::amdgcn_fcmp: { 6010 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6011 } 6012 case Intrinsic::amdgcn_fmed3: 6013 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6014 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6015 case Intrinsic::amdgcn_fdot2: 6016 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6017 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6018 Op.getOperand(4)); 6019 case Intrinsic::amdgcn_fmul_legacy: 6020 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6021 Op.getOperand(1), Op.getOperand(2)); 6022 case Intrinsic::amdgcn_sffbh: 6023 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6024 case Intrinsic::amdgcn_sbfe: 6025 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6026 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6027 case Intrinsic::amdgcn_ubfe: 6028 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6029 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6030 case Intrinsic::amdgcn_cvt_pkrtz: 6031 case Intrinsic::amdgcn_cvt_pknorm_i16: 6032 case Intrinsic::amdgcn_cvt_pknorm_u16: 6033 case Intrinsic::amdgcn_cvt_pk_i16: 6034 case Intrinsic::amdgcn_cvt_pk_u16: { 6035 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6036 EVT VT = Op.getValueType(); 6037 unsigned Opcode; 6038 6039 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6040 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6041 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6042 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6043 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6044 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6045 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6046 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6047 else 6048 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6049 6050 if (isTypeLegal(VT)) 6051 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6052 6053 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6054 Op.getOperand(1), Op.getOperand(2)); 6055 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6056 } 6057 case Intrinsic::amdgcn_fmad_ftz: 6058 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6059 Op.getOperand(2), Op.getOperand(3)); 6060 6061 case Intrinsic::amdgcn_if_break: 6062 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6063 Op->getOperand(1), Op->getOperand(2)), 0); 6064 6065 case Intrinsic::amdgcn_groupstaticsize: { 6066 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6067 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6068 return Op; 6069 6070 const Module *M = MF.getFunction().getParent(); 6071 const GlobalValue *GV = 6072 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6073 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6074 SIInstrInfo::MO_ABS32_LO); 6075 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6076 } 6077 case Intrinsic::amdgcn_is_shared: 6078 case Intrinsic::amdgcn_is_private: { 6079 SDLoc SL(Op); 6080 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6081 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6082 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6083 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6084 Op.getOperand(1)); 6085 6086 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6087 DAG.getConstant(1, SL, MVT::i32)); 6088 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6089 } 6090 default: 6091 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6092 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6093 return lowerImage(Op, ImageDimIntr, DAG); 6094 6095 return Op; 6096 } 6097 } 6098 6099 // This function computes an appropriate offset to pass to 6100 // MachineMemOperand::setOffset() based on the offset inputs to 6101 // an intrinsic. If any of the offsets are non-contstant or 6102 // if VIndex is non-zero then this function returns 0. Otherwise, 6103 // it returns the sum of VOffset, SOffset, and Offset. 6104 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6105 SDValue SOffset, 6106 SDValue Offset, 6107 SDValue VIndex = SDValue()) { 6108 6109 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6110 !isa<ConstantSDNode>(Offset)) 6111 return 0; 6112 6113 if (VIndex) { 6114 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6115 return 0; 6116 } 6117 6118 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6119 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6120 cast<ConstantSDNode>(Offset)->getSExtValue(); 6121 } 6122 6123 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6124 SelectionDAG &DAG) const { 6125 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6126 SDLoc DL(Op); 6127 6128 switch (IntrID) { 6129 case Intrinsic::amdgcn_ds_ordered_add: 6130 case Intrinsic::amdgcn_ds_ordered_swap: { 6131 MemSDNode *M = cast<MemSDNode>(Op); 6132 SDValue Chain = M->getOperand(0); 6133 SDValue M0 = M->getOperand(2); 6134 SDValue Value = M->getOperand(3); 6135 unsigned IndexOperand = M->getConstantOperandVal(7); 6136 unsigned WaveRelease = M->getConstantOperandVal(8); 6137 unsigned WaveDone = M->getConstantOperandVal(9); 6138 unsigned ShaderType; 6139 unsigned Instruction; 6140 6141 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6142 IndexOperand &= ~0x3f; 6143 unsigned CountDw = 0; 6144 6145 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6146 CountDw = (IndexOperand >> 24) & 0xf; 6147 IndexOperand &= ~(0xf << 24); 6148 6149 if (CountDw < 1 || CountDw > 4) { 6150 report_fatal_error( 6151 "ds_ordered_count: dword count must be between 1 and 4"); 6152 } 6153 } 6154 6155 if (IndexOperand) 6156 report_fatal_error("ds_ordered_count: bad index operand"); 6157 6158 switch (IntrID) { 6159 case Intrinsic::amdgcn_ds_ordered_add: 6160 Instruction = 0; 6161 break; 6162 case Intrinsic::amdgcn_ds_ordered_swap: 6163 Instruction = 1; 6164 break; 6165 } 6166 6167 if (WaveDone && !WaveRelease) 6168 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6169 6170 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6171 case CallingConv::AMDGPU_CS: 6172 case CallingConv::AMDGPU_KERNEL: 6173 ShaderType = 0; 6174 break; 6175 case CallingConv::AMDGPU_PS: 6176 ShaderType = 1; 6177 break; 6178 case CallingConv::AMDGPU_VS: 6179 ShaderType = 2; 6180 break; 6181 case CallingConv::AMDGPU_GS: 6182 ShaderType = 3; 6183 break; 6184 default: 6185 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6186 } 6187 6188 unsigned Offset0 = OrderedCountIndex << 2; 6189 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6190 (Instruction << 4); 6191 6192 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6193 Offset1 |= (CountDw - 1) << 6; 6194 6195 unsigned Offset = Offset0 | (Offset1 << 8); 6196 6197 SDValue Ops[] = { 6198 Chain, 6199 Value, 6200 DAG.getTargetConstant(Offset, DL, MVT::i16), 6201 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6202 }; 6203 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6204 M->getVTList(), Ops, M->getMemoryVT(), 6205 M->getMemOperand()); 6206 } 6207 case Intrinsic::amdgcn_ds_fadd: { 6208 MemSDNode *M = cast<MemSDNode>(Op); 6209 unsigned Opc; 6210 switch (IntrID) { 6211 case Intrinsic::amdgcn_ds_fadd: 6212 Opc = ISD::ATOMIC_LOAD_FADD; 6213 break; 6214 } 6215 6216 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6217 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6218 M->getMemOperand()); 6219 } 6220 case Intrinsic::amdgcn_atomic_inc: 6221 case Intrinsic::amdgcn_atomic_dec: 6222 case Intrinsic::amdgcn_ds_fmin: 6223 case Intrinsic::amdgcn_ds_fmax: { 6224 MemSDNode *M = cast<MemSDNode>(Op); 6225 unsigned Opc; 6226 switch (IntrID) { 6227 case Intrinsic::amdgcn_atomic_inc: 6228 Opc = AMDGPUISD::ATOMIC_INC; 6229 break; 6230 case Intrinsic::amdgcn_atomic_dec: 6231 Opc = AMDGPUISD::ATOMIC_DEC; 6232 break; 6233 case Intrinsic::amdgcn_ds_fmin: 6234 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6235 break; 6236 case Intrinsic::amdgcn_ds_fmax: 6237 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6238 break; 6239 default: 6240 llvm_unreachable("Unknown intrinsic!"); 6241 } 6242 SDValue Ops[] = { 6243 M->getOperand(0), // Chain 6244 M->getOperand(2), // Ptr 6245 M->getOperand(3) // Value 6246 }; 6247 6248 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6249 M->getMemoryVT(), M->getMemOperand()); 6250 } 6251 case Intrinsic::amdgcn_buffer_load: 6252 case Intrinsic::amdgcn_buffer_load_format: { 6253 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6254 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6255 unsigned IdxEn = 1; 6256 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6257 IdxEn = Idx->getZExtValue() != 0; 6258 SDValue Ops[] = { 6259 Op.getOperand(0), // Chain 6260 Op.getOperand(2), // rsrc 6261 Op.getOperand(3), // vindex 6262 SDValue(), // voffset -- will be set by setBufferOffsets 6263 SDValue(), // soffset -- will be set by setBufferOffsets 6264 SDValue(), // offset -- will be set by setBufferOffsets 6265 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6266 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6267 }; 6268 6269 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6270 // We don't know the offset if vindex is non-zero, so clear it. 6271 if (IdxEn) 6272 Offset = 0; 6273 6274 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6275 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6276 6277 EVT VT = Op.getValueType(); 6278 EVT IntVT = VT.changeTypeToInteger(); 6279 auto *M = cast<MemSDNode>(Op); 6280 M->getMemOperand()->setOffset(Offset); 6281 EVT LoadVT = Op.getValueType(); 6282 6283 if (LoadVT.getScalarType() == MVT::f16) 6284 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6285 M, DAG, Ops); 6286 6287 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6288 if (LoadVT.getScalarType() == MVT::i8 || 6289 LoadVT.getScalarType() == MVT::i16) 6290 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6291 6292 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6293 M->getMemOperand(), DAG); 6294 } 6295 case Intrinsic::amdgcn_raw_buffer_load: 6296 case Intrinsic::amdgcn_raw_buffer_load_format: { 6297 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6298 6299 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6300 SDValue Ops[] = { 6301 Op.getOperand(0), // Chain 6302 Op.getOperand(2), // rsrc 6303 DAG.getConstant(0, DL, MVT::i32), // vindex 6304 Offsets.first, // voffset 6305 Op.getOperand(4), // soffset 6306 Offsets.second, // offset 6307 Op.getOperand(5), // cachepolicy, swizzled buffer 6308 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6309 }; 6310 6311 auto *M = cast<MemSDNode>(Op); 6312 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6313 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6314 } 6315 case Intrinsic::amdgcn_struct_buffer_load: 6316 case Intrinsic::amdgcn_struct_buffer_load_format: { 6317 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6318 6319 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6320 SDValue Ops[] = { 6321 Op.getOperand(0), // Chain 6322 Op.getOperand(2), // rsrc 6323 Op.getOperand(3), // vindex 6324 Offsets.first, // voffset 6325 Op.getOperand(5), // soffset 6326 Offsets.second, // offset 6327 Op.getOperand(6), // cachepolicy, swizzled buffer 6328 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6329 }; 6330 6331 auto *M = cast<MemSDNode>(Op); 6332 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6333 Ops[2])); 6334 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6335 } 6336 case Intrinsic::amdgcn_tbuffer_load: { 6337 MemSDNode *M = cast<MemSDNode>(Op); 6338 EVT LoadVT = Op.getValueType(); 6339 6340 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6341 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6342 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6343 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6344 unsigned IdxEn = 1; 6345 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6346 IdxEn = Idx->getZExtValue() != 0; 6347 SDValue Ops[] = { 6348 Op.getOperand(0), // Chain 6349 Op.getOperand(2), // rsrc 6350 Op.getOperand(3), // vindex 6351 Op.getOperand(4), // voffset 6352 Op.getOperand(5), // soffset 6353 Op.getOperand(6), // offset 6354 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6355 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6356 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6357 }; 6358 6359 if (LoadVT.getScalarType() == MVT::f16) 6360 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6361 M, DAG, Ops); 6362 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6363 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6364 DAG); 6365 } 6366 case Intrinsic::amdgcn_raw_tbuffer_load: { 6367 MemSDNode *M = cast<MemSDNode>(Op); 6368 EVT LoadVT = Op.getValueType(); 6369 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6370 6371 SDValue Ops[] = { 6372 Op.getOperand(0), // Chain 6373 Op.getOperand(2), // rsrc 6374 DAG.getConstant(0, DL, MVT::i32), // vindex 6375 Offsets.first, // voffset 6376 Op.getOperand(4), // soffset 6377 Offsets.second, // offset 6378 Op.getOperand(5), // format 6379 Op.getOperand(6), // cachepolicy, swizzled buffer 6380 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6381 }; 6382 6383 if (LoadVT.getScalarType() == MVT::f16) 6384 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6385 M, DAG, Ops); 6386 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6387 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6388 DAG); 6389 } 6390 case Intrinsic::amdgcn_struct_tbuffer_load: { 6391 MemSDNode *M = cast<MemSDNode>(Op); 6392 EVT LoadVT = Op.getValueType(); 6393 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6394 6395 SDValue Ops[] = { 6396 Op.getOperand(0), // Chain 6397 Op.getOperand(2), // rsrc 6398 Op.getOperand(3), // vindex 6399 Offsets.first, // voffset 6400 Op.getOperand(5), // soffset 6401 Offsets.second, // offset 6402 Op.getOperand(6), // format 6403 Op.getOperand(7), // cachepolicy, swizzled buffer 6404 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6405 }; 6406 6407 if (LoadVT.getScalarType() == MVT::f16) 6408 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6409 M, DAG, Ops); 6410 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6411 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6412 DAG); 6413 } 6414 case Intrinsic::amdgcn_buffer_atomic_swap: 6415 case Intrinsic::amdgcn_buffer_atomic_add: 6416 case Intrinsic::amdgcn_buffer_atomic_sub: 6417 case Intrinsic::amdgcn_buffer_atomic_smin: 6418 case Intrinsic::amdgcn_buffer_atomic_umin: 6419 case Intrinsic::amdgcn_buffer_atomic_smax: 6420 case Intrinsic::amdgcn_buffer_atomic_umax: 6421 case Intrinsic::amdgcn_buffer_atomic_and: 6422 case Intrinsic::amdgcn_buffer_atomic_or: 6423 case Intrinsic::amdgcn_buffer_atomic_xor: { 6424 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6425 unsigned IdxEn = 1; 6426 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6427 IdxEn = Idx->getZExtValue() != 0; 6428 SDValue Ops[] = { 6429 Op.getOperand(0), // Chain 6430 Op.getOperand(2), // vdata 6431 Op.getOperand(3), // rsrc 6432 Op.getOperand(4), // vindex 6433 SDValue(), // voffset -- will be set by setBufferOffsets 6434 SDValue(), // soffset -- will be set by setBufferOffsets 6435 SDValue(), // offset -- will be set by setBufferOffsets 6436 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6437 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6438 }; 6439 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6440 // We don't know the offset if vindex is non-zero, so clear it. 6441 if (IdxEn) 6442 Offset = 0; 6443 EVT VT = Op.getValueType(); 6444 6445 auto *M = cast<MemSDNode>(Op); 6446 M->getMemOperand()->setOffset(Offset); 6447 unsigned Opcode = 0; 6448 6449 switch (IntrID) { 6450 case Intrinsic::amdgcn_buffer_atomic_swap: 6451 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6452 break; 6453 case Intrinsic::amdgcn_buffer_atomic_add: 6454 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6455 break; 6456 case Intrinsic::amdgcn_buffer_atomic_sub: 6457 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6458 break; 6459 case Intrinsic::amdgcn_buffer_atomic_smin: 6460 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6461 break; 6462 case Intrinsic::amdgcn_buffer_atomic_umin: 6463 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6464 break; 6465 case Intrinsic::amdgcn_buffer_atomic_smax: 6466 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6467 break; 6468 case Intrinsic::amdgcn_buffer_atomic_umax: 6469 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6470 break; 6471 case Intrinsic::amdgcn_buffer_atomic_and: 6472 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6473 break; 6474 case Intrinsic::amdgcn_buffer_atomic_or: 6475 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6476 break; 6477 case Intrinsic::amdgcn_buffer_atomic_xor: 6478 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6479 break; 6480 default: 6481 llvm_unreachable("unhandled atomic opcode"); 6482 } 6483 6484 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6485 M->getMemOperand()); 6486 } 6487 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6488 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6489 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6490 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6491 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6492 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6493 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6494 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6495 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6496 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6497 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6498 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6499 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6500 SDValue Ops[] = { 6501 Op.getOperand(0), // Chain 6502 Op.getOperand(2), // vdata 6503 Op.getOperand(3), // rsrc 6504 DAG.getConstant(0, DL, MVT::i32), // vindex 6505 Offsets.first, // voffset 6506 Op.getOperand(5), // soffset 6507 Offsets.second, // offset 6508 Op.getOperand(6), // cachepolicy 6509 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6510 }; 6511 EVT VT = Op.getValueType(); 6512 6513 auto *M = cast<MemSDNode>(Op); 6514 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6515 unsigned Opcode = 0; 6516 6517 switch (IntrID) { 6518 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6519 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6520 break; 6521 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6522 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6523 break; 6524 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6525 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6526 break; 6527 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6528 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6529 break; 6530 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6531 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6532 break; 6533 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6534 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6535 break; 6536 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6537 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6538 break; 6539 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6540 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6541 break; 6542 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6543 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6544 break; 6545 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6546 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6547 break; 6548 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6549 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6550 break; 6551 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6552 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6553 break; 6554 default: 6555 llvm_unreachable("unhandled atomic opcode"); 6556 } 6557 6558 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6559 M->getMemOperand()); 6560 } 6561 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6562 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6563 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6564 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6565 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6566 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6567 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6568 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6569 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6570 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6571 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6572 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6573 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6574 SDValue Ops[] = { 6575 Op.getOperand(0), // Chain 6576 Op.getOperand(2), // vdata 6577 Op.getOperand(3), // rsrc 6578 Op.getOperand(4), // vindex 6579 Offsets.first, // voffset 6580 Op.getOperand(6), // soffset 6581 Offsets.second, // offset 6582 Op.getOperand(7), // cachepolicy 6583 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6584 }; 6585 EVT VT = Op.getValueType(); 6586 6587 auto *M = cast<MemSDNode>(Op); 6588 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6589 Ops[3])); 6590 unsigned Opcode = 0; 6591 6592 switch (IntrID) { 6593 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6594 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6595 break; 6596 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6597 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6598 break; 6599 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6600 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6601 break; 6602 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6603 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6604 break; 6605 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6606 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6607 break; 6608 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6609 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6610 break; 6611 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6612 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6613 break; 6614 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6615 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6616 break; 6617 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6618 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6619 break; 6620 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6621 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6622 break; 6623 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6624 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6625 break; 6626 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6627 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6628 break; 6629 default: 6630 llvm_unreachable("unhandled atomic opcode"); 6631 } 6632 6633 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6634 M->getMemOperand()); 6635 } 6636 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6637 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6638 unsigned IdxEn = 1; 6639 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6640 IdxEn = Idx->getZExtValue() != 0; 6641 SDValue Ops[] = { 6642 Op.getOperand(0), // Chain 6643 Op.getOperand(2), // src 6644 Op.getOperand(3), // cmp 6645 Op.getOperand(4), // rsrc 6646 Op.getOperand(5), // vindex 6647 SDValue(), // voffset -- will be set by setBufferOffsets 6648 SDValue(), // soffset -- will be set by setBufferOffsets 6649 SDValue(), // offset -- will be set by setBufferOffsets 6650 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6651 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6652 }; 6653 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6654 // We don't know the offset if vindex is non-zero, so clear it. 6655 if (IdxEn) 6656 Offset = 0; 6657 EVT VT = Op.getValueType(); 6658 auto *M = cast<MemSDNode>(Op); 6659 M->getMemOperand()->setOffset(Offset); 6660 6661 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6662 Op->getVTList(), Ops, VT, M->getMemOperand()); 6663 } 6664 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6665 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6666 SDValue Ops[] = { 6667 Op.getOperand(0), // Chain 6668 Op.getOperand(2), // src 6669 Op.getOperand(3), // cmp 6670 Op.getOperand(4), // rsrc 6671 DAG.getConstant(0, DL, MVT::i32), // vindex 6672 Offsets.first, // voffset 6673 Op.getOperand(6), // soffset 6674 Offsets.second, // offset 6675 Op.getOperand(7), // cachepolicy 6676 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6677 }; 6678 EVT VT = Op.getValueType(); 6679 auto *M = cast<MemSDNode>(Op); 6680 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6681 6682 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6683 Op->getVTList(), Ops, VT, M->getMemOperand()); 6684 } 6685 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6686 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6687 SDValue Ops[] = { 6688 Op.getOperand(0), // Chain 6689 Op.getOperand(2), // src 6690 Op.getOperand(3), // cmp 6691 Op.getOperand(4), // rsrc 6692 Op.getOperand(5), // vindex 6693 Offsets.first, // voffset 6694 Op.getOperand(7), // soffset 6695 Offsets.second, // offset 6696 Op.getOperand(8), // cachepolicy 6697 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6698 }; 6699 EVT VT = Op.getValueType(); 6700 auto *M = cast<MemSDNode>(Op); 6701 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6702 Ops[4])); 6703 6704 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6705 Op->getVTList(), Ops, VT, M->getMemOperand()); 6706 } 6707 6708 default: 6709 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6710 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6711 return lowerImage(Op, ImageDimIntr, DAG); 6712 6713 return SDValue(); 6714 } 6715 } 6716 6717 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6718 // dwordx4 if on SI. 6719 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6720 SDVTList VTList, 6721 ArrayRef<SDValue> Ops, EVT MemVT, 6722 MachineMemOperand *MMO, 6723 SelectionDAG &DAG) const { 6724 EVT VT = VTList.VTs[0]; 6725 EVT WidenedVT = VT; 6726 EVT WidenedMemVT = MemVT; 6727 if (!Subtarget->hasDwordx3LoadStores() && 6728 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6729 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6730 WidenedVT.getVectorElementType(), 4); 6731 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6732 WidenedMemVT.getVectorElementType(), 4); 6733 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6734 } 6735 6736 assert(VTList.NumVTs == 2); 6737 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6738 6739 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6740 WidenedMemVT, MMO); 6741 if (WidenedVT != VT) { 6742 auto Extract = DAG.getNode( 6743 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6744 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6745 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6746 } 6747 return NewOp; 6748 } 6749 6750 SDValue SITargetLowering::handleD16VData(SDValue VData, 6751 SelectionDAG &DAG) const { 6752 EVT StoreVT = VData.getValueType(); 6753 6754 // No change for f16 and legal vector D16 types. 6755 if (!StoreVT.isVector()) 6756 return VData; 6757 6758 SDLoc DL(VData); 6759 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6760 6761 if (Subtarget->hasUnpackedD16VMem()) { 6762 // We need to unpack the packed data to store. 6763 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6764 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6765 6766 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6767 StoreVT.getVectorNumElements()); 6768 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6769 return DAG.UnrollVectorOp(ZExt.getNode()); 6770 } 6771 6772 assert(isTypeLegal(StoreVT)); 6773 return VData; 6774 } 6775 6776 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6777 SelectionDAG &DAG) const { 6778 SDLoc DL(Op); 6779 SDValue Chain = Op.getOperand(0); 6780 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6781 MachineFunction &MF = DAG.getMachineFunction(); 6782 6783 switch (IntrinsicID) { 6784 case Intrinsic::amdgcn_exp: { 6785 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6786 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6787 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6788 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6789 6790 const SDValue Ops[] = { 6791 Chain, 6792 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6793 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6794 Op.getOperand(4), // src0 6795 Op.getOperand(5), // src1 6796 Op.getOperand(6), // src2 6797 Op.getOperand(7), // src3 6798 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6799 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6800 }; 6801 6802 unsigned Opc = Done->isNullValue() ? 6803 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6804 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6805 } 6806 case Intrinsic::amdgcn_exp_compr: { 6807 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6808 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6809 SDValue Src0 = Op.getOperand(4); 6810 SDValue Src1 = Op.getOperand(5); 6811 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6812 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6813 6814 SDValue Undef = DAG.getUNDEF(MVT::f32); 6815 const SDValue Ops[] = { 6816 Chain, 6817 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6818 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6819 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6820 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6821 Undef, // src2 6822 Undef, // src3 6823 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6824 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6825 }; 6826 6827 unsigned Opc = Done->isNullValue() ? 6828 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6829 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6830 } 6831 case Intrinsic::amdgcn_s_barrier: { 6832 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6833 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6834 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6835 if (WGSize <= ST.getWavefrontSize()) 6836 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6837 Op.getOperand(0)), 0); 6838 } 6839 return SDValue(); 6840 }; 6841 case Intrinsic::amdgcn_tbuffer_store: { 6842 SDValue VData = Op.getOperand(2); 6843 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6844 if (IsD16) 6845 VData = handleD16VData(VData, DAG); 6846 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6847 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6848 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6849 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6850 unsigned IdxEn = 1; 6851 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6852 IdxEn = Idx->getZExtValue() != 0; 6853 SDValue Ops[] = { 6854 Chain, 6855 VData, // vdata 6856 Op.getOperand(3), // rsrc 6857 Op.getOperand(4), // vindex 6858 Op.getOperand(5), // voffset 6859 Op.getOperand(6), // soffset 6860 Op.getOperand(7), // offset 6861 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6862 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6863 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6864 }; 6865 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6866 AMDGPUISD::TBUFFER_STORE_FORMAT; 6867 MemSDNode *M = cast<MemSDNode>(Op); 6868 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6869 M->getMemoryVT(), M->getMemOperand()); 6870 } 6871 6872 case Intrinsic::amdgcn_struct_tbuffer_store: { 6873 SDValue VData = Op.getOperand(2); 6874 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6875 if (IsD16) 6876 VData = handleD16VData(VData, DAG); 6877 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6878 SDValue Ops[] = { 6879 Chain, 6880 VData, // vdata 6881 Op.getOperand(3), // rsrc 6882 Op.getOperand(4), // vindex 6883 Offsets.first, // voffset 6884 Op.getOperand(6), // soffset 6885 Offsets.second, // offset 6886 Op.getOperand(7), // format 6887 Op.getOperand(8), // cachepolicy, swizzled buffer 6888 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6889 }; 6890 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6891 AMDGPUISD::TBUFFER_STORE_FORMAT; 6892 MemSDNode *M = cast<MemSDNode>(Op); 6893 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6894 M->getMemoryVT(), M->getMemOperand()); 6895 } 6896 6897 case Intrinsic::amdgcn_raw_tbuffer_store: { 6898 SDValue VData = Op.getOperand(2); 6899 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6900 if (IsD16) 6901 VData = handleD16VData(VData, DAG); 6902 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6903 SDValue Ops[] = { 6904 Chain, 6905 VData, // vdata 6906 Op.getOperand(3), // rsrc 6907 DAG.getConstant(0, DL, MVT::i32), // vindex 6908 Offsets.first, // voffset 6909 Op.getOperand(5), // soffset 6910 Offsets.second, // offset 6911 Op.getOperand(6), // format 6912 Op.getOperand(7), // cachepolicy, swizzled buffer 6913 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6914 }; 6915 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6916 AMDGPUISD::TBUFFER_STORE_FORMAT; 6917 MemSDNode *M = cast<MemSDNode>(Op); 6918 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6919 M->getMemoryVT(), M->getMemOperand()); 6920 } 6921 6922 case Intrinsic::amdgcn_buffer_store: 6923 case Intrinsic::amdgcn_buffer_store_format: { 6924 SDValue VData = Op.getOperand(2); 6925 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6926 if (IsD16) 6927 VData = handleD16VData(VData, DAG); 6928 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6929 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6930 unsigned IdxEn = 1; 6931 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6932 IdxEn = Idx->getZExtValue() != 0; 6933 SDValue Ops[] = { 6934 Chain, 6935 VData, 6936 Op.getOperand(3), // rsrc 6937 Op.getOperand(4), // vindex 6938 SDValue(), // voffset -- will be set by setBufferOffsets 6939 SDValue(), // soffset -- will be set by setBufferOffsets 6940 SDValue(), // offset -- will be set by setBufferOffsets 6941 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6942 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6943 }; 6944 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6945 // We don't know the offset if vindex is non-zero, so clear it. 6946 if (IdxEn) 6947 Offset = 0; 6948 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6949 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6950 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6951 MemSDNode *M = cast<MemSDNode>(Op); 6952 M->getMemOperand()->setOffset(Offset); 6953 6954 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6955 EVT VDataType = VData.getValueType().getScalarType(); 6956 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6957 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6958 6959 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6960 M->getMemoryVT(), M->getMemOperand()); 6961 } 6962 6963 case Intrinsic::amdgcn_raw_buffer_store: 6964 case Intrinsic::amdgcn_raw_buffer_store_format: { 6965 const bool IsFormat = 6966 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6967 6968 SDValue VData = Op.getOperand(2); 6969 EVT VDataVT = VData.getValueType(); 6970 EVT EltType = VDataVT.getScalarType(); 6971 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6972 if (IsD16) 6973 VData = handleD16VData(VData, DAG); 6974 6975 if (!isTypeLegal(VDataVT)) { 6976 VData = 6977 DAG.getNode(ISD::BITCAST, DL, 6978 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6979 } 6980 6981 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6982 SDValue Ops[] = { 6983 Chain, 6984 VData, 6985 Op.getOperand(3), // rsrc 6986 DAG.getConstant(0, DL, MVT::i32), // vindex 6987 Offsets.first, // voffset 6988 Op.getOperand(5), // soffset 6989 Offsets.second, // offset 6990 Op.getOperand(6), // cachepolicy, swizzled buffer 6991 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6992 }; 6993 unsigned Opc = 6994 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6995 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6996 MemSDNode *M = cast<MemSDNode>(Op); 6997 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6998 6999 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7000 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7001 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7002 7003 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7004 M->getMemoryVT(), M->getMemOperand()); 7005 } 7006 7007 case Intrinsic::amdgcn_struct_buffer_store: 7008 case Intrinsic::amdgcn_struct_buffer_store_format: { 7009 const bool IsFormat = 7010 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7011 7012 SDValue VData = Op.getOperand(2); 7013 EVT VDataVT = VData.getValueType(); 7014 EVT EltType = VDataVT.getScalarType(); 7015 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7016 7017 if (IsD16) 7018 VData = handleD16VData(VData, DAG); 7019 7020 if (!isTypeLegal(VDataVT)) { 7021 VData = 7022 DAG.getNode(ISD::BITCAST, DL, 7023 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7024 } 7025 7026 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7027 SDValue Ops[] = { 7028 Chain, 7029 VData, 7030 Op.getOperand(3), // rsrc 7031 Op.getOperand(4), // vindex 7032 Offsets.first, // voffset 7033 Op.getOperand(6), // soffset 7034 Offsets.second, // offset 7035 Op.getOperand(7), // cachepolicy, swizzled buffer 7036 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7037 }; 7038 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7039 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7040 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7041 MemSDNode *M = cast<MemSDNode>(Op); 7042 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7043 Ops[3])); 7044 7045 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7046 EVT VDataType = VData.getValueType().getScalarType(); 7047 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7048 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7049 7050 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7051 M->getMemoryVT(), M->getMemOperand()); 7052 } 7053 7054 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7055 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7056 unsigned IdxEn = 1; 7057 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7058 IdxEn = Idx->getZExtValue() != 0; 7059 SDValue Ops[] = { 7060 Chain, 7061 Op.getOperand(2), // vdata 7062 Op.getOperand(3), // rsrc 7063 Op.getOperand(4), // vindex 7064 SDValue(), // voffset -- will be set by setBufferOffsets 7065 SDValue(), // soffset -- will be set by setBufferOffsets 7066 SDValue(), // offset -- will be set by setBufferOffsets 7067 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7068 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7069 }; 7070 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7071 // We don't know the offset if vindex is non-zero, so clear it. 7072 if (IdxEn) 7073 Offset = 0; 7074 EVT VT = Op.getOperand(2).getValueType(); 7075 7076 auto *M = cast<MemSDNode>(Op); 7077 M->getMemOperand()->setOffset(Offset); 7078 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7079 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7080 7081 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7082 M->getMemOperand()); 7083 } 7084 7085 case Intrinsic::amdgcn_global_atomic_fadd: { 7086 SDValue Ops[] = { 7087 Chain, 7088 Op.getOperand(2), // ptr 7089 Op.getOperand(3) // vdata 7090 }; 7091 EVT VT = Op.getOperand(3).getValueType(); 7092 7093 auto *M = cast<MemSDNode>(Op); 7094 unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD 7095 : AMDGPUISD::ATOMIC_FADD; 7096 7097 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7098 M->getMemOperand()); 7099 } 7100 7101 case Intrinsic::amdgcn_end_cf: 7102 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7103 Op->getOperand(2), Chain), 0); 7104 7105 default: { 7106 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7107 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7108 return lowerImage(Op, ImageDimIntr, DAG); 7109 7110 return Op; 7111 } 7112 } 7113 } 7114 7115 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7116 // offset (the offset that is included in bounds checking and swizzling, to be 7117 // split between the instruction's voffset and immoffset fields) and soffset 7118 // (the offset that is excluded from bounds checking and swizzling, to go in 7119 // the instruction's soffset field). This function takes the first kind of 7120 // offset and figures out how to split it between voffset and immoffset. 7121 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7122 SDValue Offset, SelectionDAG &DAG) const { 7123 SDLoc DL(Offset); 7124 const unsigned MaxImm = 4095; 7125 SDValue N0 = Offset; 7126 ConstantSDNode *C1 = nullptr; 7127 7128 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7129 N0 = SDValue(); 7130 else if (DAG.isBaseWithConstantOffset(N0)) { 7131 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7132 N0 = N0.getOperand(0); 7133 } 7134 7135 if (C1) { 7136 unsigned ImmOffset = C1->getZExtValue(); 7137 // If the immediate value is too big for the immoffset field, put the value 7138 // and -4096 into the immoffset field so that the value that is copied/added 7139 // for the voffset field is a multiple of 4096, and it stands more chance 7140 // of being CSEd with the copy/add for another similar load/store. 7141 // However, do not do that rounding down to a multiple of 4096 if that is a 7142 // negative number, as it appears to be illegal to have a negative offset 7143 // in the vgpr, even if adding the immediate offset makes it positive. 7144 unsigned Overflow = ImmOffset & ~MaxImm; 7145 ImmOffset -= Overflow; 7146 if ((int32_t)Overflow < 0) { 7147 Overflow += ImmOffset; 7148 ImmOffset = 0; 7149 } 7150 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7151 if (Overflow) { 7152 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7153 if (!N0) 7154 N0 = OverflowVal; 7155 else { 7156 SDValue Ops[] = { N0, OverflowVal }; 7157 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7158 } 7159 } 7160 } 7161 if (!N0) 7162 N0 = DAG.getConstant(0, DL, MVT::i32); 7163 if (!C1) 7164 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7165 return {N0, SDValue(C1, 0)}; 7166 } 7167 7168 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7169 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7170 // pointed to by Offsets. 7171 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7172 SelectionDAG &DAG, SDValue *Offsets, 7173 unsigned Align) const { 7174 SDLoc DL(CombinedOffset); 7175 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7176 uint32_t Imm = C->getZExtValue(); 7177 uint32_t SOffset, ImmOffset; 7178 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7179 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7180 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7181 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7182 return SOffset + ImmOffset; 7183 } 7184 } 7185 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7186 SDValue N0 = CombinedOffset.getOperand(0); 7187 SDValue N1 = CombinedOffset.getOperand(1); 7188 uint32_t SOffset, ImmOffset; 7189 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7190 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7191 Subtarget, Align)) { 7192 Offsets[0] = N0; 7193 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7194 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7195 return 0; 7196 } 7197 } 7198 Offsets[0] = CombinedOffset; 7199 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7200 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7201 return 0; 7202 } 7203 7204 // Handle 8 bit and 16 bit buffer loads 7205 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7206 EVT LoadVT, SDLoc DL, 7207 ArrayRef<SDValue> Ops, 7208 MemSDNode *M) const { 7209 EVT IntVT = LoadVT.changeTypeToInteger(); 7210 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7211 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7212 7213 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7214 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7215 Ops, IntVT, 7216 M->getMemOperand()); 7217 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7218 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7219 7220 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7221 } 7222 7223 // Handle 8 bit and 16 bit buffer stores 7224 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7225 EVT VDataType, SDLoc DL, 7226 SDValue Ops[], 7227 MemSDNode *M) const { 7228 if (VDataType == MVT::f16) 7229 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7230 7231 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7232 Ops[1] = BufferStoreExt; 7233 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7234 AMDGPUISD::BUFFER_STORE_SHORT; 7235 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7236 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7237 M->getMemOperand()); 7238 } 7239 7240 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7241 ISD::LoadExtType ExtType, SDValue Op, 7242 const SDLoc &SL, EVT VT) { 7243 if (VT.bitsLT(Op.getValueType())) 7244 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7245 7246 switch (ExtType) { 7247 case ISD::SEXTLOAD: 7248 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7249 case ISD::ZEXTLOAD: 7250 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7251 case ISD::EXTLOAD: 7252 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7253 case ISD::NON_EXTLOAD: 7254 return Op; 7255 } 7256 7257 llvm_unreachable("invalid ext type"); 7258 } 7259 7260 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7261 SelectionDAG &DAG = DCI.DAG; 7262 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7263 return SDValue(); 7264 7265 // FIXME: Constant loads should all be marked invariant. 7266 unsigned AS = Ld->getAddressSpace(); 7267 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7268 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7269 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7270 return SDValue(); 7271 7272 // Don't do this early, since it may interfere with adjacent load merging for 7273 // illegal types. We can avoid losing alignment information for exotic types 7274 // pre-legalize. 7275 EVT MemVT = Ld->getMemoryVT(); 7276 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7277 MemVT.getSizeInBits() >= 32) 7278 return SDValue(); 7279 7280 SDLoc SL(Ld); 7281 7282 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7283 "unexpected vector extload"); 7284 7285 // TODO: Drop only high part of range. 7286 SDValue Ptr = Ld->getBasePtr(); 7287 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7288 MVT::i32, SL, Ld->getChain(), Ptr, 7289 Ld->getOffset(), 7290 Ld->getPointerInfo(), MVT::i32, 7291 Ld->getAlignment(), 7292 Ld->getMemOperand()->getFlags(), 7293 Ld->getAAInfo(), 7294 nullptr); // Drop ranges 7295 7296 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7297 if (MemVT.isFloatingPoint()) { 7298 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7299 "unexpected fp extload"); 7300 TruncVT = MemVT.changeTypeToInteger(); 7301 } 7302 7303 SDValue Cvt = NewLoad; 7304 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7305 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7306 DAG.getValueType(TruncVT)); 7307 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7308 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7309 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7310 } else { 7311 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7312 } 7313 7314 EVT VT = Ld->getValueType(0); 7315 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7316 7317 DCI.AddToWorklist(Cvt.getNode()); 7318 7319 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7320 // the appropriate extension from the 32-bit load. 7321 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7322 DCI.AddToWorklist(Cvt.getNode()); 7323 7324 // Handle conversion back to floating point if necessary. 7325 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7326 7327 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7328 } 7329 7330 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7331 SDLoc DL(Op); 7332 LoadSDNode *Load = cast<LoadSDNode>(Op); 7333 ISD::LoadExtType ExtType = Load->getExtensionType(); 7334 EVT MemVT = Load->getMemoryVT(); 7335 7336 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7337 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7338 return SDValue(); 7339 7340 // FIXME: Copied from PPC 7341 // First, load into 32 bits, then truncate to 1 bit. 7342 7343 SDValue Chain = Load->getChain(); 7344 SDValue BasePtr = Load->getBasePtr(); 7345 MachineMemOperand *MMO = Load->getMemOperand(); 7346 7347 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7348 7349 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7350 BasePtr, RealMemVT, MMO); 7351 7352 if (!MemVT.isVector()) { 7353 SDValue Ops[] = { 7354 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7355 NewLD.getValue(1) 7356 }; 7357 7358 return DAG.getMergeValues(Ops, DL); 7359 } 7360 7361 SmallVector<SDValue, 3> Elts; 7362 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7363 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7364 DAG.getConstant(I, DL, MVT::i32)); 7365 7366 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7367 } 7368 7369 SDValue Ops[] = { 7370 DAG.getBuildVector(MemVT, DL, Elts), 7371 NewLD.getValue(1) 7372 }; 7373 7374 return DAG.getMergeValues(Ops, DL); 7375 } 7376 7377 if (!MemVT.isVector()) 7378 return SDValue(); 7379 7380 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7381 "Custom lowering for non-i32 vectors hasn't been implemented."); 7382 7383 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7384 MemVT, *Load->getMemOperand())) { 7385 SDValue Ops[2]; 7386 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7387 return DAG.getMergeValues(Ops, DL); 7388 } 7389 7390 unsigned Alignment = Load->getAlignment(); 7391 unsigned AS = Load->getAddressSpace(); 7392 if (Subtarget->hasLDSMisalignedBug() && 7393 AS == AMDGPUAS::FLAT_ADDRESS && 7394 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7395 return SplitVectorLoad(Op, DAG); 7396 } 7397 7398 MachineFunction &MF = DAG.getMachineFunction(); 7399 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7400 // If there is a possibilty that flat instruction access scratch memory 7401 // then we need to use the same legalization rules we use for private. 7402 if (AS == AMDGPUAS::FLAT_ADDRESS) 7403 AS = MFI->hasFlatScratchInit() ? 7404 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7405 7406 unsigned NumElements = MemVT.getVectorNumElements(); 7407 7408 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7409 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7410 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7411 if (MemVT.isPow2VectorType()) 7412 return SDValue(); 7413 if (NumElements == 3) 7414 return WidenVectorLoad(Op, DAG); 7415 return SplitVectorLoad(Op, DAG); 7416 } 7417 // Non-uniform loads will be selected to MUBUF instructions, so they 7418 // have the same legalization requirements as global and private 7419 // loads. 7420 // 7421 } 7422 7423 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7424 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7425 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7426 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7427 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7428 Alignment >= 4 && NumElements < 32) { 7429 if (MemVT.isPow2VectorType()) 7430 return SDValue(); 7431 if (NumElements == 3) 7432 return WidenVectorLoad(Op, DAG); 7433 return SplitVectorLoad(Op, DAG); 7434 } 7435 // Non-uniform loads will be selected to MUBUF instructions, so they 7436 // have the same legalization requirements as global and private 7437 // loads. 7438 // 7439 } 7440 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7441 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7442 AS == AMDGPUAS::GLOBAL_ADDRESS || 7443 AS == AMDGPUAS::FLAT_ADDRESS) { 7444 if (NumElements > 4) 7445 return SplitVectorLoad(Op, DAG); 7446 // v3 loads not supported on SI. 7447 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7448 return WidenVectorLoad(Op, DAG); 7449 // v3 and v4 loads are supported for private and global memory. 7450 return SDValue(); 7451 } 7452 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7453 // Depending on the setting of the private_element_size field in the 7454 // resource descriptor, we can only make private accesses up to a certain 7455 // size. 7456 switch (Subtarget->getMaxPrivateElementSize()) { 7457 case 4: 7458 return scalarizeVectorLoad(Load, DAG); 7459 case 8: 7460 if (NumElements > 2) 7461 return SplitVectorLoad(Op, DAG); 7462 return SDValue(); 7463 case 16: 7464 // Same as global/flat 7465 if (NumElements > 4) 7466 return SplitVectorLoad(Op, DAG); 7467 // v3 loads not supported on SI. 7468 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7469 return WidenVectorLoad(Op, DAG); 7470 return SDValue(); 7471 default: 7472 llvm_unreachable("unsupported private_element_size"); 7473 } 7474 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7475 // Use ds_read_b128 if possible. 7476 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7477 MemVT.getStoreSize() == 16) 7478 return SDValue(); 7479 7480 if (NumElements > 2) 7481 return SplitVectorLoad(Op, DAG); 7482 7483 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7484 // address is negative, then the instruction is incorrectly treated as 7485 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7486 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7487 // load later in the SILoadStoreOptimizer. 7488 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7489 NumElements == 2 && MemVT.getStoreSize() == 8 && 7490 Load->getAlignment() < 8) { 7491 return SplitVectorLoad(Op, DAG); 7492 } 7493 } 7494 return SDValue(); 7495 } 7496 7497 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7498 EVT VT = Op.getValueType(); 7499 assert(VT.getSizeInBits() == 64); 7500 7501 SDLoc DL(Op); 7502 SDValue Cond = Op.getOperand(0); 7503 7504 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7505 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7506 7507 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7508 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7509 7510 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7511 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7512 7513 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7514 7515 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7516 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7517 7518 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7519 7520 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7521 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7522 } 7523 7524 // Catch division cases where we can use shortcuts with rcp and rsq 7525 // instructions. 7526 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7527 SelectionDAG &DAG) const { 7528 SDLoc SL(Op); 7529 SDValue LHS = Op.getOperand(0); 7530 SDValue RHS = Op.getOperand(1); 7531 EVT VT = Op.getValueType(); 7532 const SDNodeFlags Flags = Op->getFlags(); 7533 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7534 7535 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 7536 return SDValue(); 7537 7538 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7539 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7540 if (CLHS->isExactlyValue(1.0)) { 7541 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7542 // the CI documentation has a worst case error of 1 ulp. 7543 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7544 // use it as long as we aren't trying to use denormals. 7545 // 7546 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7547 7548 // 1.0 / sqrt(x) -> rsq(x) 7549 7550 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7551 // error seems really high at 2^29 ULP. 7552 if (RHS.getOpcode() == ISD::FSQRT) 7553 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7554 7555 // 1.0 / x -> rcp(x) 7556 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7557 } 7558 7559 // Same as for 1.0, but expand the sign out of the constant. 7560 if (CLHS->isExactlyValue(-1.0)) { 7561 // -1.0 / x -> rcp (fneg x) 7562 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7563 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7564 } 7565 } 7566 } 7567 7568 if (Unsafe) { 7569 // Turn into multiply by the reciprocal. 7570 // x / y -> x * (1.0 / y) 7571 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7572 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7573 } 7574 7575 return SDValue(); 7576 } 7577 7578 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7579 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7580 if (GlueChain->getNumValues() <= 1) { 7581 return DAG.getNode(Opcode, SL, VT, A, B); 7582 } 7583 7584 assert(GlueChain->getNumValues() == 3); 7585 7586 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7587 switch (Opcode) { 7588 default: llvm_unreachable("no chain equivalent for opcode"); 7589 case ISD::FMUL: 7590 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7591 break; 7592 } 7593 7594 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7595 GlueChain.getValue(2)); 7596 } 7597 7598 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7599 EVT VT, SDValue A, SDValue B, SDValue C, 7600 SDValue GlueChain) { 7601 if (GlueChain->getNumValues() <= 1) { 7602 return DAG.getNode(Opcode, SL, VT, A, B, C); 7603 } 7604 7605 assert(GlueChain->getNumValues() == 3); 7606 7607 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7608 switch (Opcode) { 7609 default: llvm_unreachable("no chain equivalent for opcode"); 7610 case ISD::FMA: 7611 Opcode = AMDGPUISD::FMA_W_CHAIN; 7612 break; 7613 } 7614 7615 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7616 GlueChain.getValue(2)); 7617 } 7618 7619 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7620 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7621 return FastLowered; 7622 7623 SDLoc SL(Op); 7624 SDValue Src0 = Op.getOperand(0); 7625 SDValue Src1 = Op.getOperand(1); 7626 7627 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7628 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7629 7630 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7631 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7632 7633 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7634 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7635 7636 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7637 } 7638 7639 // Faster 2.5 ULP division that does not support denormals. 7640 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7641 SDLoc SL(Op); 7642 SDValue LHS = Op.getOperand(1); 7643 SDValue RHS = Op.getOperand(2); 7644 7645 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7646 7647 const APFloat K0Val(BitsToFloat(0x6f800000)); 7648 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7649 7650 const APFloat K1Val(BitsToFloat(0x2f800000)); 7651 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7652 7653 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7654 7655 EVT SetCCVT = 7656 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7657 7658 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7659 7660 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7661 7662 // TODO: Should this propagate fast-math-flags? 7663 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7664 7665 // rcp does not support denormals. 7666 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7667 7668 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7669 7670 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7671 } 7672 7673 // Returns immediate value for setting the F32 denorm mode when using the 7674 // S_DENORM_MODE instruction. 7675 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7676 const SDLoc &SL, const GCNSubtarget *ST) { 7677 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7678 int DPDenormModeDefault = ST->hasFP64Denormals() 7679 ? FP_DENORM_FLUSH_NONE 7680 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7681 7682 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7683 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7684 } 7685 7686 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7687 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7688 return FastLowered; 7689 7690 SDLoc SL(Op); 7691 SDValue LHS = Op.getOperand(0); 7692 SDValue RHS = Op.getOperand(1); 7693 7694 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7695 7696 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7697 7698 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7699 RHS, RHS, LHS); 7700 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7701 LHS, RHS, LHS); 7702 7703 // Denominator is scaled to not be denormal, so using rcp is ok. 7704 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7705 DenominatorScaled); 7706 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7707 DenominatorScaled); 7708 7709 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7710 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7711 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7712 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7713 7714 if (!Subtarget->hasFP32Denormals()) { 7715 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7716 7717 SDValue EnableDenorm; 7718 if (Subtarget->hasDenormModeInst()) { 7719 const SDValue EnableDenormValue = 7720 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7721 7722 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7723 DAG.getEntryNode(), EnableDenormValue); 7724 } else { 7725 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7726 SL, MVT::i32); 7727 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7728 DAG.getEntryNode(), EnableDenormValue, 7729 BitField); 7730 } 7731 7732 SDValue Ops[3] = { 7733 NegDivScale0, 7734 EnableDenorm.getValue(0), 7735 EnableDenorm.getValue(1) 7736 }; 7737 7738 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7739 } 7740 7741 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7742 ApproxRcp, One, NegDivScale0); 7743 7744 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7745 ApproxRcp, Fma0); 7746 7747 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7748 Fma1, Fma1); 7749 7750 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7751 NumeratorScaled, Mul); 7752 7753 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7754 7755 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7756 NumeratorScaled, Fma3); 7757 7758 if (!Subtarget->hasFP32Denormals()) { 7759 7760 SDValue DisableDenorm; 7761 if (Subtarget->hasDenormModeInst()) { 7762 const SDValue DisableDenormValue = 7763 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7764 7765 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7766 Fma4.getValue(1), DisableDenormValue, 7767 Fma4.getValue(2)); 7768 } else { 7769 const SDValue DisableDenormValue = 7770 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7771 7772 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7773 Fma4.getValue(1), DisableDenormValue, 7774 BitField, Fma4.getValue(2)); 7775 } 7776 7777 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7778 DisableDenorm, DAG.getRoot()); 7779 DAG.setRoot(OutputChain); 7780 } 7781 7782 SDValue Scale = NumeratorScaled.getValue(1); 7783 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7784 Fma4, Fma1, Fma3, Scale); 7785 7786 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7787 } 7788 7789 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7790 if (DAG.getTarget().Options.UnsafeFPMath) 7791 return lowerFastUnsafeFDIV(Op, DAG); 7792 7793 SDLoc SL(Op); 7794 SDValue X = Op.getOperand(0); 7795 SDValue Y = Op.getOperand(1); 7796 7797 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7798 7799 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7800 7801 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7802 7803 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7804 7805 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7806 7807 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7808 7809 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7810 7811 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7812 7813 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7814 7815 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7816 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7817 7818 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7819 NegDivScale0, Mul, DivScale1); 7820 7821 SDValue Scale; 7822 7823 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7824 // Workaround a hardware bug on SI where the condition output from div_scale 7825 // is not usable. 7826 7827 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7828 7829 // Figure out if the scale to use for div_fmas. 7830 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7831 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7832 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7833 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7834 7835 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7836 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7837 7838 SDValue Scale0Hi 7839 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7840 SDValue Scale1Hi 7841 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7842 7843 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7844 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7845 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7846 } else { 7847 Scale = DivScale1.getValue(1); 7848 } 7849 7850 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7851 Fma4, Fma3, Mul, Scale); 7852 7853 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7854 } 7855 7856 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7857 EVT VT = Op.getValueType(); 7858 7859 if (VT == MVT::f32) 7860 return LowerFDIV32(Op, DAG); 7861 7862 if (VT == MVT::f64) 7863 return LowerFDIV64(Op, DAG); 7864 7865 if (VT == MVT::f16) 7866 return LowerFDIV16(Op, DAG); 7867 7868 llvm_unreachable("Unexpected type for fdiv"); 7869 } 7870 7871 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7872 SDLoc DL(Op); 7873 StoreSDNode *Store = cast<StoreSDNode>(Op); 7874 EVT VT = Store->getMemoryVT(); 7875 7876 if (VT == MVT::i1) { 7877 return DAG.getTruncStore(Store->getChain(), DL, 7878 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7879 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7880 } 7881 7882 assert(VT.isVector() && 7883 Store->getValue().getValueType().getScalarType() == MVT::i32); 7884 7885 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7886 VT, *Store->getMemOperand())) { 7887 return expandUnalignedStore(Store, DAG); 7888 } 7889 7890 unsigned AS = Store->getAddressSpace(); 7891 if (Subtarget->hasLDSMisalignedBug() && 7892 AS == AMDGPUAS::FLAT_ADDRESS && 7893 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7894 return SplitVectorStore(Op, DAG); 7895 } 7896 7897 MachineFunction &MF = DAG.getMachineFunction(); 7898 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7899 // If there is a possibilty that flat instruction access scratch memory 7900 // then we need to use the same legalization rules we use for private. 7901 if (AS == AMDGPUAS::FLAT_ADDRESS) 7902 AS = MFI->hasFlatScratchInit() ? 7903 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7904 7905 unsigned NumElements = VT.getVectorNumElements(); 7906 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7907 AS == AMDGPUAS::FLAT_ADDRESS) { 7908 if (NumElements > 4) 7909 return SplitVectorStore(Op, DAG); 7910 // v3 stores not supported on SI. 7911 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7912 return SplitVectorStore(Op, DAG); 7913 return SDValue(); 7914 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7915 switch (Subtarget->getMaxPrivateElementSize()) { 7916 case 4: 7917 return scalarizeVectorStore(Store, DAG); 7918 case 8: 7919 if (NumElements > 2) 7920 return SplitVectorStore(Op, DAG); 7921 return SDValue(); 7922 case 16: 7923 if (NumElements > 4 || NumElements == 3) 7924 return SplitVectorStore(Op, DAG); 7925 return SDValue(); 7926 default: 7927 llvm_unreachable("unsupported private_element_size"); 7928 } 7929 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7930 // Use ds_write_b128 if possible. 7931 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7932 VT.getStoreSize() == 16 && NumElements != 3) 7933 return SDValue(); 7934 7935 if (NumElements > 2) 7936 return SplitVectorStore(Op, DAG); 7937 7938 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7939 // address is negative, then the instruction is incorrectly treated as 7940 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7941 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7942 // store later in the SILoadStoreOptimizer. 7943 if (!Subtarget->hasUsableDSOffset() && 7944 NumElements == 2 && VT.getStoreSize() == 8 && 7945 Store->getAlignment() < 8) { 7946 return SplitVectorStore(Op, DAG); 7947 } 7948 7949 return SDValue(); 7950 } else { 7951 llvm_unreachable("unhandled address space"); 7952 } 7953 } 7954 7955 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7956 SDLoc DL(Op); 7957 EVT VT = Op.getValueType(); 7958 SDValue Arg = Op.getOperand(0); 7959 SDValue TrigVal; 7960 7961 // TODO: Should this propagate fast-math-flags? 7962 7963 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7964 7965 if (Subtarget->hasTrigReducedRange()) { 7966 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7967 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7968 } else { 7969 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7970 } 7971 7972 switch (Op.getOpcode()) { 7973 case ISD::FCOS: 7974 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7975 case ISD::FSIN: 7976 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7977 default: 7978 llvm_unreachable("Wrong trig opcode"); 7979 } 7980 } 7981 7982 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7983 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7984 assert(AtomicNode->isCompareAndSwap()); 7985 unsigned AS = AtomicNode->getAddressSpace(); 7986 7987 // No custom lowering required for local address space 7988 if (!isFlatGlobalAddrSpace(AS)) 7989 return Op; 7990 7991 // Non-local address space requires custom lowering for atomic compare 7992 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7993 SDLoc DL(Op); 7994 SDValue ChainIn = Op.getOperand(0); 7995 SDValue Addr = Op.getOperand(1); 7996 SDValue Old = Op.getOperand(2); 7997 SDValue New = Op.getOperand(3); 7998 EVT VT = Op.getValueType(); 7999 MVT SimpleVT = VT.getSimpleVT(); 8000 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8001 8002 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8003 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8004 8005 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8006 Ops, VT, AtomicNode->getMemOperand()); 8007 } 8008 8009 //===----------------------------------------------------------------------===// 8010 // Custom DAG optimizations 8011 //===----------------------------------------------------------------------===// 8012 8013 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8014 DAGCombinerInfo &DCI) const { 8015 EVT VT = N->getValueType(0); 8016 EVT ScalarVT = VT.getScalarType(); 8017 if (ScalarVT != MVT::f32) 8018 return SDValue(); 8019 8020 SelectionDAG &DAG = DCI.DAG; 8021 SDLoc DL(N); 8022 8023 SDValue Src = N->getOperand(0); 8024 EVT SrcVT = Src.getValueType(); 8025 8026 // TODO: We could try to match extracting the higher bytes, which would be 8027 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8028 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8029 // about in practice. 8030 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8031 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8032 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 8033 DCI.AddToWorklist(Cvt.getNode()); 8034 return Cvt; 8035 } 8036 } 8037 8038 return SDValue(); 8039 } 8040 8041 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8042 8043 // This is a variant of 8044 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8045 // 8046 // The normal DAG combiner will do this, but only if the add has one use since 8047 // that would increase the number of instructions. 8048 // 8049 // This prevents us from seeing a constant offset that can be folded into a 8050 // memory instruction's addressing mode. If we know the resulting add offset of 8051 // a pointer can be folded into an addressing offset, we can replace the pointer 8052 // operand with the add of new constant offset. This eliminates one of the uses, 8053 // and may allow the remaining use to also be simplified. 8054 // 8055 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8056 unsigned AddrSpace, 8057 EVT MemVT, 8058 DAGCombinerInfo &DCI) const { 8059 SDValue N0 = N->getOperand(0); 8060 SDValue N1 = N->getOperand(1); 8061 8062 // We only do this to handle cases where it's profitable when there are 8063 // multiple uses of the add, so defer to the standard combine. 8064 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8065 N0->hasOneUse()) 8066 return SDValue(); 8067 8068 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8069 if (!CN1) 8070 return SDValue(); 8071 8072 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8073 if (!CAdd) 8074 return SDValue(); 8075 8076 // If the resulting offset is too large, we can't fold it into the addressing 8077 // mode offset. 8078 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8079 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8080 8081 AddrMode AM; 8082 AM.HasBaseReg = true; 8083 AM.BaseOffs = Offset.getSExtValue(); 8084 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8085 return SDValue(); 8086 8087 SelectionDAG &DAG = DCI.DAG; 8088 SDLoc SL(N); 8089 EVT VT = N->getValueType(0); 8090 8091 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8092 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8093 8094 SDNodeFlags Flags; 8095 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8096 (N0.getOpcode() == ISD::OR || 8097 N0->getFlags().hasNoUnsignedWrap())); 8098 8099 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8100 } 8101 8102 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8103 DAGCombinerInfo &DCI) const { 8104 SDValue Ptr = N->getBasePtr(); 8105 SelectionDAG &DAG = DCI.DAG; 8106 SDLoc SL(N); 8107 8108 // TODO: We could also do this for multiplies. 8109 if (Ptr.getOpcode() == ISD::SHL) { 8110 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8111 N->getMemoryVT(), DCI); 8112 if (NewPtr) { 8113 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8114 8115 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8116 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8117 } 8118 } 8119 8120 return SDValue(); 8121 } 8122 8123 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8124 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8125 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8126 (Opc == ISD::XOR && Val == 0); 8127 } 8128 8129 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8130 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8131 // integer combine opportunities since most 64-bit operations are decomposed 8132 // this way. TODO: We won't want this for SALU especially if it is an inline 8133 // immediate. 8134 SDValue SITargetLowering::splitBinaryBitConstantOp( 8135 DAGCombinerInfo &DCI, 8136 const SDLoc &SL, 8137 unsigned Opc, SDValue LHS, 8138 const ConstantSDNode *CRHS) const { 8139 uint64_t Val = CRHS->getZExtValue(); 8140 uint32_t ValLo = Lo_32(Val); 8141 uint32_t ValHi = Hi_32(Val); 8142 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8143 8144 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8145 bitOpWithConstantIsReducible(Opc, ValHi)) || 8146 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8147 // If we need to materialize a 64-bit immediate, it will be split up later 8148 // anyway. Avoid creating the harder to understand 64-bit immediate 8149 // materialization. 8150 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8151 } 8152 8153 return SDValue(); 8154 } 8155 8156 // Returns true if argument is a boolean value which is not serialized into 8157 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8158 static bool isBoolSGPR(SDValue V) { 8159 if (V.getValueType() != MVT::i1) 8160 return false; 8161 switch (V.getOpcode()) { 8162 default: break; 8163 case ISD::SETCC: 8164 case ISD::AND: 8165 case ISD::OR: 8166 case ISD::XOR: 8167 case AMDGPUISD::FP_CLASS: 8168 return true; 8169 } 8170 return false; 8171 } 8172 8173 // If a constant has all zeroes or all ones within each byte return it. 8174 // Otherwise return 0. 8175 static uint32_t getConstantPermuteMask(uint32_t C) { 8176 // 0xff for any zero byte in the mask 8177 uint32_t ZeroByteMask = 0; 8178 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8179 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8180 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8181 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8182 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8183 if ((NonZeroByteMask & C) != NonZeroByteMask) 8184 return 0; // Partial bytes selected. 8185 return C; 8186 } 8187 8188 // Check if a node selects whole bytes from its operand 0 starting at a byte 8189 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8190 // or -1 if not succeeded. 8191 // Note byte select encoding: 8192 // value 0-3 selects corresponding source byte; 8193 // value 0xc selects zero; 8194 // value 0xff selects 0xff. 8195 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8196 assert(V.getValueSizeInBits() == 32); 8197 8198 if (V.getNumOperands() != 2) 8199 return ~0; 8200 8201 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8202 if (!N1) 8203 return ~0; 8204 8205 uint32_t C = N1->getZExtValue(); 8206 8207 switch (V.getOpcode()) { 8208 default: 8209 break; 8210 case ISD::AND: 8211 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8212 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8213 } 8214 break; 8215 8216 case ISD::OR: 8217 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8218 return (0x03020100 & ~ConstMask) | ConstMask; 8219 } 8220 break; 8221 8222 case ISD::SHL: 8223 if (C % 8) 8224 return ~0; 8225 8226 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8227 8228 case ISD::SRL: 8229 if (C % 8) 8230 return ~0; 8231 8232 return uint32_t(0x0c0c0c0c03020100ull >> C); 8233 } 8234 8235 return ~0; 8236 } 8237 8238 SDValue SITargetLowering::performAndCombine(SDNode *N, 8239 DAGCombinerInfo &DCI) const { 8240 if (DCI.isBeforeLegalize()) 8241 return SDValue(); 8242 8243 SelectionDAG &DAG = DCI.DAG; 8244 EVT VT = N->getValueType(0); 8245 SDValue LHS = N->getOperand(0); 8246 SDValue RHS = N->getOperand(1); 8247 8248 8249 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8250 if (VT == MVT::i64 && CRHS) { 8251 if (SDValue Split 8252 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8253 return Split; 8254 } 8255 8256 if (CRHS && VT == MVT::i32) { 8257 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8258 // nb = number of trailing zeroes in mask 8259 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8260 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8261 uint64_t Mask = CRHS->getZExtValue(); 8262 unsigned Bits = countPopulation(Mask); 8263 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8264 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8265 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8266 unsigned Shift = CShift->getZExtValue(); 8267 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8268 unsigned Offset = NB + Shift; 8269 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8270 SDLoc SL(N); 8271 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8272 LHS->getOperand(0), 8273 DAG.getConstant(Offset, SL, MVT::i32), 8274 DAG.getConstant(Bits, SL, MVT::i32)); 8275 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8276 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8277 DAG.getValueType(NarrowVT)); 8278 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8279 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8280 return Shl; 8281 } 8282 } 8283 } 8284 8285 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8286 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8287 isa<ConstantSDNode>(LHS.getOperand(2))) { 8288 uint32_t Sel = getConstantPermuteMask(Mask); 8289 if (!Sel) 8290 return SDValue(); 8291 8292 // Select 0xc for all zero bytes 8293 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8294 SDLoc DL(N); 8295 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8296 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8297 } 8298 } 8299 8300 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8301 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8302 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8303 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8304 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8305 8306 SDValue X = LHS.getOperand(0); 8307 SDValue Y = RHS.getOperand(0); 8308 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8309 return SDValue(); 8310 8311 if (LCC == ISD::SETO) { 8312 if (X != LHS.getOperand(1)) 8313 return SDValue(); 8314 8315 if (RCC == ISD::SETUNE) { 8316 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8317 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8318 return SDValue(); 8319 8320 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8321 SIInstrFlags::N_SUBNORMAL | 8322 SIInstrFlags::N_ZERO | 8323 SIInstrFlags::P_ZERO | 8324 SIInstrFlags::P_SUBNORMAL | 8325 SIInstrFlags::P_NORMAL; 8326 8327 static_assert(((~(SIInstrFlags::S_NAN | 8328 SIInstrFlags::Q_NAN | 8329 SIInstrFlags::N_INFINITY | 8330 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8331 "mask not equal"); 8332 8333 SDLoc DL(N); 8334 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8335 X, DAG.getConstant(Mask, DL, MVT::i32)); 8336 } 8337 } 8338 } 8339 8340 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8341 std::swap(LHS, RHS); 8342 8343 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8344 RHS.hasOneUse()) { 8345 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8346 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8347 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8348 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8349 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8350 (RHS.getOperand(0) == LHS.getOperand(0) && 8351 LHS.getOperand(0) == LHS.getOperand(1))) { 8352 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8353 unsigned NewMask = LCC == ISD::SETO ? 8354 Mask->getZExtValue() & ~OrdMask : 8355 Mask->getZExtValue() & OrdMask; 8356 8357 SDLoc DL(N); 8358 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8359 DAG.getConstant(NewMask, DL, MVT::i32)); 8360 } 8361 } 8362 8363 if (VT == MVT::i32 && 8364 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8365 // and x, (sext cc from i1) => select cc, x, 0 8366 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8367 std::swap(LHS, RHS); 8368 if (isBoolSGPR(RHS.getOperand(0))) 8369 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8370 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8371 } 8372 8373 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8374 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8375 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8376 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8377 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8378 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8379 if (LHSMask != ~0u && RHSMask != ~0u) { 8380 // Canonicalize the expression in an attempt to have fewer unique masks 8381 // and therefore fewer registers used to hold the masks. 8382 if (LHSMask > RHSMask) { 8383 std::swap(LHSMask, RHSMask); 8384 std::swap(LHS, RHS); 8385 } 8386 8387 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8388 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8389 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8390 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8391 8392 // Check of we need to combine values from two sources within a byte. 8393 if (!(LHSUsedLanes & RHSUsedLanes) && 8394 // If we select high and lower word keep it for SDWA. 8395 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8396 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8397 // Each byte in each mask is either selector mask 0-3, or has higher 8398 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8399 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8400 // mask which is not 0xff wins. By anding both masks we have a correct 8401 // result except that 0x0c shall be corrected to give 0x0c only. 8402 uint32_t Mask = LHSMask & RHSMask; 8403 for (unsigned I = 0; I < 32; I += 8) { 8404 uint32_t ByteSel = 0xff << I; 8405 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8406 Mask &= (0x0c << I) & 0xffffffff; 8407 } 8408 8409 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8410 // or 0x0c. 8411 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8412 SDLoc DL(N); 8413 8414 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8415 LHS.getOperand(0), RHS.getOperand(0), 8416 DAG.getConstant(Sel, DL, MVT::i32)); 8417 } 8418 } 8419 } 8420 8421 return SDValue(); 8422 } 8423 8424 SDValue SITargetLowering::performOrCombine(SDNode *N, 8425 DAGCombinerInfo &DCI) const { 8426 SelectionDAG &DAG = DCI.DAG; 8427 SDValue LHS = N->getOperand(0); 8428 SDValue RHS = N->getOperand(1); 8429 8430 EVT VT = N->getValueType(0); 8431 if (VT == MVT::i1) { 8432 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8433 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8434 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8435 SDValue Src = LHS.getOperand(0); 8436 if (Src != RHS.getOperand(0)) 8437 return SDValue(); 8438 8439 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8440 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8441 if (!CLHS || !CRHS) 8442 return SDValue(); 8443 8444 // Only 10 bits are used. 8445 static const uint32_t MaxMask = 0x3ff; 8446 8447 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8448 SDLoc DL(N); 8449 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8450 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8451 } 8452 8453 return SDValue(); 8454 } 8455 8456 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8457 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8458 LHS.getOpcode() == AMDGPUISD::PERM && 8459 isa<ConstantSDNode>(LHS.getOperand(2))) { 8460 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8461 if (!Sel) 8462 return SDValue(); 8463 8464 Sel |= LHS.getConstantOperandVal(2); 8465 SDLoc DL(N); 8466 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8467 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8468 } 8469 8470 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8471 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8472 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8473 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8474 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8475 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8476 if (LHSMask != ~0u && RHSMask != ~0u) { 8477 // Canonicalize the expression in an attempt to have fewer unique masks 8478 // and therefore fewer registers used to hold the masks. 8479 if (LHSMask > RHSMask) { 8480 std::swap(LHSMask, RHSMask); 8481 std::swap(LHS, RHS); 8482 } 8483 8484 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8485 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8486 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8487 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8488 8489 // Check of we need to combine values from two sources within a byte. 8490 if (!(LHSUsedLanes & RHSUsedLanes) && 8491 // If we select high and lower word keep it for SDWA. 8492 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8493 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8494 // Kill zero bytes selected by other mask. Zero value is 0xc. 8495 LHSMask &= ~RHSUsedLanes; 8496 RHSMask &= ~LHSUsedLanes; 8497 // Add 4 to each active LHS lane 8498 LHSMask |= LHSUsedLanes & 0x04040404; 8499 // Combine masks 8500 uint32_t Sel = LHSMask | RHSMask; 8501 SDLoc DL(N); 8502 8503 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8504 LHS.getOperand(0), RHS.getOperand(0), 8505 DAG.getConstant(Sel, DL, MVT::i32)); 8506 } 8507 } 8508 } 8509 8510 if (VT != MVT::i64) 8511 return SDValue(); 8512 8513 // TODO: This could be a generic combine with a predicate for extracting the 8514 // high half of an integer being free. 8515 8516 // (or i64:x, (zero_extend i32:y)) -> 8517 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8518 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8519 RHS.getOpcode() != ISD::ZERO_EXTEND) 8520 std::swap(LHS, RHS); 8521 8522 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8523 SDValue ExtSrc = RHS.getOperand(0); 8524 EVT SrcVT = ExtSrc.getValueType(); 8525 if (SrcVT == MVT::i32) { 8526 SDLoc SL(N); 8527 SDValue LowLHS, HiBits; 8528 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8529 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8530 8531 DCI.AddToWorklist(LowOr.getNode()); 8532 DCI.AddToWorklist(HiBits.getNode()); 8533 8534 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8535 LowOr, HiBits); 8536 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8537 } 8538 } 8539 8540 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8541 if (CRHS) { 8542 if (SDValue Split 8543 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8544 return Split; 8545 } 8546 8547 return SDValue(); 8548 } 8549 8550 SDValue SITargetLowering::performXorCombine(SDNode *N, 8551 DAGCombinerInfo &DCI) const { 8552 EVT VT = N->getValueType(0); 8553 if (VT != MVT::i64) 8554 return SDValue(); 8555 8556 SDValue LHS = N->getOperand(0); 8557 SDValue RHS = N->getOperand(1); 8558 8559 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8560 if (CRHS) { 8561 if (SDValue Split 8562 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8563 return Split; 8564 } 8565 8566 return SDValue(); 8567 } 8568 8569 // Instructions that will be lowered with a final instruction that zeros the 8570 // high result bits. 8571 // XXX - probably only need to list legal operations. 8572 static bool fp16SrcZerosHighBits(unsigned Opc) { 8573 switch (Opc) { 8574 case ISD::FADD: 8575 case ISD::FSUB: 8576 case ISD::FMUL: 8577 case ISD::FDIV: 8578 case ISD::FREM: 8579 case ISD::FMA: 8580 case ISD::FMAD: 8581 case ISD::FCANONICALIZE: 8582 case ISD::FP_ROUND: 8583 case ISD::UINT_TO_FP: 8584 case ISD::SINT_TO_FP: 8585 case ISD::FABS: 8586 // Fabs is lowered to a bit operation, but it's an and which will clear the 8587 // high bits anyway. 8588 case ISD::FSQRT: 8589 case ISD::FSIN: 8590 case ISD::FCOS: 8591 case ISD::FPOWI: 8592 case ISD::FPOW: 8593 case ISD::FLOG: 8594 case ISD::FLOG2: 8595 case ISD::FLOG10: 8596 case ISD::FEXP: 8597 case ISD::FEXP2: 8598 case ISD::FCEIL: 8599 case ISD::FTRUNC: 8600 case ISD::FRINT: 8601 case ISD::FNEARBYINT: 8602 case ISD::FROUND: 8603 case ISD::FFLOOR: 8604 case ISD::FMINNUM: 8605 case ISD::FMAXNUM: 8606 case AMDGPUISD::FRACT: 8607 case AMDGPUISD::CLAMP: 8608 case AMDGPUISD::COS_HW: 8609 case AMDGPUISD::SIN_HW: 8610 case AMDGPUISD::FMIN3: 8611 case AMDGPUISD::FMAX3: 8612 case AMDGPUISD::FMED3: 8613 case AMDGPUISD::FMAD_FTZ: 8614 case AMDGPUISD::RCP: 8615 case AMDGPUISD::RSQ: 8616 case AMDGPUISD::RCP_IFLAG: 8617 case AMDGPUISD::LDEXP: 8618 return true; 8619 default: 8620 // fcopysign, select and others may be lowered to 32-bit bit operations 8621 // which don't zero the high bits. 8622 return false; 8623 } 8624 } 8625 8626 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8627 DAGCombinerInfo &DCI) const { 8628 if (!Subtarget->has16BitInsts() || 8629 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8630 return SDValue(); 8631 8632 EVT VT = N->getValueType(0); 8633 if (VT != MVT::i32) 8634 return SDValue(); 8635 8636 SDValue Src = N->getOperand(0); 8637 if (Src.getValueType() != MVT::i16) 8638 return SDValue(); 8639 8640 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8641 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8642 if (Src.getOpcode() == ISD::BITCAST) { 8643 SDValue BCSrc = Src.getOperand(0); 8644 if (BCSrc.getValueType() == MVT::f16 && 8645 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8646 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8647 } 8648 8649 return SDValue(); 8650 } 8651 8652 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8653 DAGCombinerInfo &DCI) 8654 const { 8655 SDValue Src = N->getOperand(0); 8656 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8657 8658 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8659 VTSign->getVT() == MVT::i8) || 8660 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8661 VTSign->getVT() == MVT::i16)) && 8662 Src.hasOneUse()) { 8663 auto *M = cast<MemSDNode>(Src); 8664 SDValue Ops[] = { 8665 Src.getOperand(0), // Chain 8666 Src.getOperand(1), // rsrc 8667 Src.getOperand(2), // vindex 8668 Src.getOperand(3), // voffset 8669 Src.getOperand(4), // soffset 8670 Src.getOperand(5), // offset 8671 Src.getOperand(6), 8672 Src.getOperand(7) 8673 }; 8674 // replace with BUFFER_LOAD_BYTE/SHORT 8675 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8676 Src.getOperand(0).getValueType()); 8677 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8678 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8679 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8680 ResList, 8681 Ops, M->getMemoryVT(), 8682 M->getMemOperand()); 8683 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8684 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8685 } 8686 return SDValue(); 8687 } 8688 8689 SDValue SITargetLowering::performClassCombine(SDNode *N, 8690 DAGCombinerInfo &DCI) const { 8691 SelectionDAG &DAG = DCI.DAG; 8692 SDValue Mask = N->getOperand(1); 8693 8694 // fp_class x, 0 -> false 8695 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8696 if (CMask->isNullValue()) 8697 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8698 } 8699 8700 if (N->getOperand(0).isUndef()) 8701 return DAG.getUNDEF(MVT::i1); 8702 8703 return SDValue(); 8704 } 8705 8706 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8707 DAGCombinerInfo &DCI) const { 8708 EVT VT = N->getValueType(0); 8709 SDValue N0 = N->getOperand(0); 8710 8711 if (N0.isUndef()) 8712 return N0; 8713 8714 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8715 N0.getOpcode() == ISD::SINT_TO_FP)) { 8716 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8717 N->getFlags()); 8718 } 8719 8720 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8721 } 8722 8723 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8724 unsigned MaxDepth) const { 8725 unsigned Opcode = Op.getOpcode(); 8726 if (Opcode == ISD::FCANONICALIZE) 8727 return true; 8728 8729 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8730 auto F = CFP->getValueAPF(); 8731 if (F.isNaN() && F.isSignaling()) 8732 return false; 8733 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 8734 } 8735 8736 // If source is a result of another standard FP operation it is already in 8737 // canonical form. 8738 if (MaxDepth == 0) 8739 return false; 8740 8741 switch (Opcode) { 8742 // These will flush denorms if required. 8743 case ISD::FADD: 8744 case ISD::FSUB: 8745 case ISD::FMUL: 8746 case ISD::FCEIL: 8747 case ISD::FFLOOR: 8748 case ISD::FMA: 8749 case ISD::FMAD: 8750 case ISD::FSQRT: 8751 case ISD::FDIV: 8752 case ISD::FREM: 8753 case ISD::FP_ROUND: 8754 case ISD::FP_EXTEND: 8755 case AMDGPUISD::FMUL_LEGACY: 8756 case AMDGPUISD::FMAD_FTZ: 8757 case AMDGPUISD::RCP: 8758 case AMDGPUISD::RSQ: 8759 case AMDGPUISD::RSQ_CLAMP: 8760 case AMDGPUISD::RCP_LEGACY: 8761 case AMDGPUISD::RSQ_LEGACY: 8762 case AMDGPUISD::RCP_IFLAG: 8763 case AMDGPUISD::TRIG_PREOP: 8764 case AMDGPUISD::DIV_SCALE: 8765 case AMDGPUISD::DIV_FMAS: 8766 case AMDGPUISD::DIV_FIXUP: 8767 case AMDGPUISD::FRACT: 8768 case AMDGPUISD::LDEXP: 8769 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8770 case AMDGPUISD::CVT_F32_UBYTE0: 8771 case AMDGPUISD::CVT_F32_UBYTE1: 8772 case AMDGPUISD::CVT_F32_UBYTE2: 8773 case AMDGPUISD::CVT_F32_UBYTE3: 8774 return true; 8775 8776 // It can/will be lowered or combined as a bit operation. 8777 // Need to check their input recursively to handle. 8778 case ISD::FNEG: 8779 case ISD::FABS: 8780 case ISD::FCOPYSIGN: 8781 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8782 8783 case ISD::FSIN: 8784 case ISD::FCOS: 8785 case ISD::FSINCOS: 8786 return Op.getValueType().getScalarType() != MVT::f16; 8787 8788 case ISD::FMINNUM: 8789 case ISD::FMAXNUM: 8790 case ISD::FMINNUM_IEEE: 8791 case ISD::FMAXNUM_IEEE: 8792 case AMDGPUISD::CLAMP: 8793 case AMDGPUISD::FMED3: 8794 case AMDGPUISD::FMAX3: 8795 case AMDGPUISD::FMIN3: { 8796 // FIXME: Shouldn't treat the generic operations different based these. 8797 // However, we aren't really required to flush the result from 8798 // minnum/maxnum.. 8799 8800 // snans will be quieted, so we only need to worry about denormals. 8801 if (Subtarget->supportsMinMaxDenormModes() || 8802 denormalsEnabledForType(Op.getValueType())) 8803 return true; 8804 8805 // Flushing may be required. 8806 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8807 // targets need to check their input recursively. 8808 8809 // FIXME: Does this apply with clamp? It's implemented with max. 8810 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8811 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8812 return false; 8813 } 8814 8815 return true; 8816 } 8817 case ISD::SELECT: { 8818 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8819 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8820 } 8821 case ISD::BUILD_VECTOR: { 8822 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8823 SDValue SrcOp = Op.getOperand(i); 8824 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8825 return false; 8826 } 8827 8828 return true; 8829 } 8830 case ISD::EXTRACT_VECTOR_ELT: 8831 case ISD::EXTRACT_SUBVECTOR: { 8832 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8833 } 8834 case ISD::INSERT_VECTOR_ELT: { 8835 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8836 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8837 } 8838 case ISD::UNDEF: 8839 // Could be anything. 8840 return false; 8841 8842 case ISD::BITCAST: { 8843 // Hack round the mess we make when legalizing extract_vector_elt 8844 SDValue Src = Op.getOperand(0); 8845 if (Src.getValueType() == MVT::i16 && 8846 Src.getOpcode() == ISD::TRUNCATE) { 8847 SDValue TruncSrc = Src.getOperand(0); 8848 if (TruncSrc.getValueType() == MVT::i32 && 8849 TruncSrc.getOpcode() == ISD::BITCAST && 8850 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8851 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8852 } 8853 } 8854 8855 return false; 8856 } 8857 case ISD::INTRINSIC_WO_CHAIN: { 8858 unsigned IntrinsicID 8859 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8860 // TODO: Handle more intrinsics 8861 switch (IntrinsicID) { 8862 case Intrinsic::amdgcn_cvt_pkrtz: 8863 case Intrinsic::amdgcn_cubeid: 8864 case Intrinsic::amdgcn_frexp_mant: 8865 case Intrinsic::amdgcn_fdot2: 8866 return true; 8867 default: 8868 break; 8869 } 8870 8871 LLVM_FALLTHROUGH; 8872 } 8873 default: 8874 return denormalsEnabledForType(Op.getValueType()) && 8875 DAG.isKnownNeverSNaN(Op); 8876 } 8877 8878 llvm_unreachable("invalid operation"); 8879 } 8880 8881 // Constant fold canonicalize. 8882 SDValue SITargetLowering::getCanonicalConstantFP( 8883 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8884 // Flush denormals to 0 if not enabled. 8885 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8886 return DAG.getConstantFP(0.0, SL, VT); 8887 8888 if (C.isNaN()) { 8889 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8890 if (C.isSignaling()) { 8891 // Quiet a signaling NaN. 8892 // FIXME: Is this supposed to preserve payload bits? 8893 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8894 } 8895 8896 // Make sure it is the canonical NaN bitpattern. 8897 // 8898 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8899 // immediate? 8900 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8901 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8902 } 8903 8904 // Already canonical. 8905 return DAG.getConstantFP(C, SL, VT); 8906 } 8907 8908 static bool vectorEltWillFoldAway(SDValue Op) { 8909 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8910 } 8911 8912 SDValue SITargetLowering::performFCanonicalizeCombine( 8913 SDNode *N, 8914 DAGCombinerInfo &DCI) const { 8915 SelectionDAG &DAG = DCI.DAG; 8916 SDValue N0 = N->getOperand(0); 8917 EVT VT = N->getValueType(0); 8918 8919 // fcanonicalize undef -> qnan 8920 if (N0.isUndef()) { 8921 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8922 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8923 } 8924 8925 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8926 EVT VT = N->getValueType(0); 8927 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8928 } 8929 8930 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8931 // (fcanonicalize k) 8932 // 8933 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8934 8935 // TODO: This could be better with wider vectors that will be split to v2f16, 8936 // and to consider uses since there aren't that many packed operations. 8937 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8938 isTypeLegal(MVT::v2f16)) { 8939 SDLoc SL(N); 8940 SDValue NewElts[2]; 8941 SDValue Lo = N0.getOperand(0); 8942 SDValue Hi = N0.getOperand(1); 8943 EVT EltVT = Lo.getValueType(); 8944 8945 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8946 for (unsigned I = 0; I != 2; ++I) { 8947 SDValue Op = N0.getOperand(I); 8948 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8949 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8950 CFP->getValueAPF()); 8951 } else if (Op.isUndef()) { 8952 // Handled below based on what the other operand is. 8953 NewElts[I] = Op; 8954 } else { 8955 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8956 } 8957 } 8958 8959 // If one half is undef, and one is constant, perfer a splat vector rather 8960 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8961 // cheaper to use and may be free with a packed operation. 8962 if (NewElts[0].isUndef()) { 8963 if (isa<ConstantFPSDNode>(NewElts[1])) 8964 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8965 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8966 } 8967 8968 if (NewElts[1].isUndef()) { 8969 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8970 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8971 } 8972 8973 return DAG.getBuildVector(VT, SL, NewElts); 8974 } 8975 } 8976 8977 unsigned SrcOpc = N0.getOpcode(); 8978 8979 // If it's free to do so, push canonicalizes further up the source, which may 8980 // find a canonical source. 8981 // 8982 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8983 // sNaNs. 8984 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8985 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8986 if (CRHS && N0.hasOneUse()) { 8987 SDLoc SL(N); 8988 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8989 N0.getOperand(0)); 8990 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8991 DCI.AddToWorklist(Canon0.getNode()); 8992 8993 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8994 } 8995 } 8996 8997 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8998 } 8999 9000 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9001 switch (Opc) { 9002 case ISD::FMAXNUM: 9003 case ISD::FMAXNUM_IEEE: 9004 return AMDGPUISD::FMAX3; 9005 case ISD::SMAX: 9006 return AMDGPUISD::SMAX3; 9007 case ISD::UMAX: 9008 return AMDGPUISD::UMAX3; 9009 case ISD::FMINNUM: 9010 case ISD::FMINNUM_IEEE: 9011 return AMDGPUISD::FMIN3; 9012 case ISD::SMIN: 9013 return AMDGPUISD::SMIN3; 9014 case ISD::UMIN: 9015 return AMDGPUISD::UMIN3; 9016 default: 9017 llvm_unreachable("Not a min/max opcode"); 9018 } 9019 } 9020 9021 SDValue SITargetLowering::performIntMed3ImmCombine( 9022 SelectionDAG &DAG, const SDLoc &SL, 9023 SDValue Op0, SDValue Op1, bool Signed) const { 9024 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9025 if (!K1) 9026 return SDValue(); 9027 9028 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9029 if (!K0) 9030 return SDValue(); 9031 9032 if (Signed) { 9033 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9034 return SDValue(); 9035 } else { 9036 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9037 return SDValue(); 9038 } 9039 9040 EVT VT = K0->getValueType(0); 9041 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9042 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9043 return DAG.getNode(Med3Opc, SL, VT, 9044 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9045 } 9046 9047 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9048 MVT NVT = MVT::i32; 9049 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9050 9051 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9052 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9053 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9054 9055 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9056 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9057 } 9058 9059 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9060 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9061 return C; 9062 9063 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9064 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9065 return C; 9066 } 9067 9068 return nullptr; 9069 } 9070 9071 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9072 const SDLoc &SL, 9073 SDValue Op0, 9074 SDValue Op1) const { 9075 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9076 if (!K1) 9077 return SDValue(); 9078 9079 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9080 if (!K0) 9081 return SDValue(); 9082 9083 // Ordered >= (although NaN inputs should have folded away by now). 9084 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 9085 if (Cmp == APFloat::cmpGreaterThan) 9086 return SDValue(); 9087 9088 const MachineFunction &MF = DAG.getMachineFunction(); 9089 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9090 9091 // TODO: Check IEEE bit enabled? 9092 EVT VT = Op0.getValueType(); 9093 if (Info->getMode().DX10Clamp) { 9094 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9095 // hardware fmed3 behavior converting to a min. 9096 // FIXME: Should this be allowing -0.0? 9097 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9098 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9099 } 9100 9101 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9102 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9103 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9104 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9105 // then give the other result, which is different from med3 with a NaN 9106 // input. 9107 SDValue Var = Op0.getOperand(0); 9108 if (!DAG.isKnownNeverSNaN(Var)) 9109 return SDValue(); 9110 9111 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9112 9113 if ((!K0->hasOneUse() || 9114 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9115 (!K1->hasOneUse() || 9116 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9117 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9118 Var, SDValue(K0, 0), SDValue(K1, 0)); 9119 } 9120 } 9121 9122 return SDValue(); 9123 } 9124 9125 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9126 DAGCombinerInfo &DCI) const { 9127 SelectionDAG &DAG = DCI.DAG; 9128 9129 EVT VT = N->getValueType(0); 9130 unsigned Opc = N->getOpcode(); 9131 SDValue Op0 = N->getOperand(0); 9132 SDValue Op1 = N->getOperand(1); 9133 9134 // Only do this if the inner op has one use since this will just increases 9135 // register pressure for no benefit. 9136 9137 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9138 !VT.isVector() && 9139 (VT == MVT::i32 || VT == MVT::f32 || 9140 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9141 // max(max(a, b), c) -> max3(a, b, c) 9142 // min(min(a, b), c) -> min3(a, b, c) 9143 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9144 SDLoc DL(N); 9145 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9146 DL, 9147 N->getValueType(0), 9148 Op0.getOperand(0), 9149 Op0.getOperand(1), 9150 Op1); 9151 } 9152 9153 // Try commuted. 9154 // max(a, max(b, c)) -> max3(a, b, c) 9155 // min(a, min(b, c)) -> min3(a, b, c) 9156 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9157 SDLoc DL(N); 9158 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9159 DL, 9160 N->getValueType(0), 9161 Op0, 9162 Op1.getOperand(0), 9163 Op1.getOperand(1)); 9164 } 9165 } 9166 9167 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9168 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9169 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9170 return Med3; 9171 } 9172 9173 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9174 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9175 return Med3; 9176 } 9177 9178 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9179 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9180 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9181 (Opc == AMDGPUISD::FMIN_LEGACY && 9182 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9183 (VT == MVT::f32 || VT == MVT::f64 || 9184 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9185 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9186 Op0.hasOneUse()) { 9187 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9188 return Res; 9189 } 9190 9191 return SDValue(); 9192 } 9193 9194 static bool isClampZeroToOne(SDValue A, SDValue B) { 9195 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9196 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9197 // FIXME: Should this be allowing -0.0? 9198 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9199 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9200 } 9201 } 9202 9203 return false; 9204 } 9205 9206 // FIXME: Should only worry about snans for version with chain. 9207 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9208 DAGCombinerInfo &DCI) const { 9209 EVT VT = N->getValueType(0); 9210 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9211 // NaNs. With a NaN input, the order of the operands may change the result. 9212 9213 SelectionDAG &DAG = DCI.DAG; 9214 SDLoc SL(N); 9215 9216 SDValue Src0 = N->getOperand(0); 9217 SDValue Src1 = N->getOperand(1); 9218 SDValue Src2 = N->getOperand(2); 9219 9220 if (isClampZeroToOne(Src0, Src1)) { 9221 // const_a, const_b, x -> clamp is safe in all cases including signaling 9222 // nans. 9223 // FIXME: Should this be allowing -0.0? 9224 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9225 } 9226 9227 const MachineFunction &MF = DAG.getMachineFunction(); 9228 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9229 9230 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9231 // handling no dx10-clamp? 9232 if (Info->getMode().DX10Clamp) { 9233 // If NaNs is clamped to 0, we are free to reorder the inputs. 9234 9235 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9236 std::swap(Src0, Src1); 9237 9238 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9239 std::swap(Src1, Src2); 9240 9241 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9242 std::swap(Src0, Src1); 9243 9244 if (isClampZeroToOne(Src1, Src2)) 9245 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9246 } 9247 9248 return SDValue(); 9249 } 9250 9251 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9252 DAGCombinerInfo &DCI) const { 9253 SDValue Src0 = N->getOperand(0); 9254 SDValue Src1 = N->getOperand(1); 9255 if (Src0.isUndef() && Src1.isUndef()) 9256 return DCI.DAG.getUNDEF(N->getValueType(0)); 9257 return SDValue(); 9258 } 9259 9260 SDValue SITargetLowering::performExtractVectorEltCombine( 9261 SDNode *N, DAGCombinerInfo &DCI) const { 9262 SDValue Vec = N->getOperand(0); 9263 SelectionDAG &DAG = DCI.DAG; 9264 9265 EVT VecVT = Vec.getValueType(); 9266 EVT EltVT = VecVT.getVectorElementType(); 9267 9268 if ((Vec.getOpcode() == ISD::FNEG || 9269 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9270 SDLoc SL(N); 9271 EVT EltVT = N->getValueType(0); 9272 SDValue Idx = N->getOperand(1); 9273 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9274 Vec.getOperand(0), Idx); 9275 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9276 } 9277 9278 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9279 // => 9280 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9281 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9282 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9283 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9284 SDLoc SL(N); 9285 EVT EltVT = N->getValueType(0); 9286 SDValue Idx = N->getOperand(1); 9287 unsigned Opc = Vec.getOpcode(); 9288 9289 switch(Opc) { 9290 default: 9291 break; 9292 // TODO: Support other binary operations. 9293 case ISD::FADD: 9294 case ISD::FSUB: 9295 case ISD::FMUL: 9296 case ISD::ADD: 9297 case ISD::UMIN: 9298 case ISD::UMAX: 9299 case ISD::SMIN: 9300 case ISD::SMAX: 9301 case ISD::FMAXNUM: 9302 case ISD::FMINNUM: 9303 case ISD::FMAXNUM_IEEE: 9304 case ISD::FMINNUM_IEEE: { 9305 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9306 Vec.getOperand(0), Idx); 9307 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9308 Vec.getOperand(1), Idx); 9309 9310 DCI.AddToWorklist(Elt0.getNode()); 9311 DCI.AddToWorklist(Elt1.getNode()); 9312 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9313 } 9314 } 9315 } 9316 9317 unsigned VecSize = VecVT.getSizeInBits(); 9318 unsigned EltSize = EltVT.getSizeInBits(); 9319 9320 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9321 // This elminates non-constant index and subsequent movrel or scratch access. 9322 // Sub-dword vectors of size 2 dword or less have better implementation. 9323 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9324 // instructions. 9325 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9326 !isa<ConstantSDNode>(N->getOperand(1))) { 9327 SDLoc SL(N); 9328 SDValue Idx = N->getOperand(1); 9329 EVT IdxVT = Idx.getValueType(); 9330 SDValue V; 9331 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9332 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9333 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9334 if (I == 0) 9335 V = Elt; 9336 else 9337 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9338 } 9339 return V; 9340 } 9341 9342 if (!DCI.isBeforeLegalize()) 9343 return SDValue(); 9344 9345 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9346 // elements. This exposes more load reduction opportunities by replacing 9347 // multiple small extract_vector_elements with a single 32-bit extract. 9348 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9349 if (isa<MemSDNode>(Vec) && 9350 EltSize <= 16 && 9351 EltVT.isByteSized() && 9352 VecSize > 32 && 9353 VecSize % 32 == 0 && 9354 Idx) { 9355 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9356 9357 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9358 unsigned EltIdx = BitIndex / 32; 9359 unsigned LeftoverBitIdx = BitIndex % 32; 9360 SDLoc SL(N); 9361 9362 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9363 DCI.AddToWorklist(Cast.getNode()); 9364 9365 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9366 DAG.getConstant(EltIdx, SL, MVT::i32)); 9367 DCI.AddToWorklist(Elt.getNode()); 9368 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9369 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9370 DCI.AddToWorklist(Srl.getNode()); 9371 9372 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9373 DCI.AddToWorklist(Trunc.getNode()); 9374 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9375 } 9376 9377 return SDValue(); 9378 } 9379 9380 SDValue 9381 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9382 DAGCombinerInfo &DCI) const { 9383 SDValue Vec = N->getOperand(0); 9384 SDValue Idx = N->getOperand(2); 9385 EVT VecVT = Vec.getValueType(); 9386 EVT EltVT = VecVT.getVectorElementType(); 9387 unsigned VecSize = VecVT.getSizeInBits(); 9388 unsigned EltSize = EltVT.getSizeInBits(); 9389 9390 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9391 // => BUILD_VECTOR n x select (e, const-idx) 9392 // This elminates non-constant index and subsequent movrel or scratch access. 9393 // Sub-dword vectors of size 2 dword or less have better implementation. 9394 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9395 // instructions. 9396 if (isa<ConstantSDNode>(Idx) || 9397 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9398 return SDValue(); 9399 9400 SelectionDAG &DAG = DCI.DAG; 9401 SDLoc SL(N); 9402 SDValue Ins = N->getOperand(1); 9403 EVT IdxVT = Idx.getValueType(); 9404 9405 SmallVector<SDValue, 16> Ops; 9406 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9407 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9408 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9409 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9410 Ops.push_back(V); 9411 } 9412 9413 return DAG.getBuildVector(VecVT, SL, Ops); 9414 } 9415 9416 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9417 const SDNode *N0, 9418 const SDNode *N1) const { 9419 EVT VT = N0->getValueType(0); 9420 9421 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9422 // support denormals ever. 9423 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 9424 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() && 9425 getSubtarget()->hasMadF16())) && 9426 isOperationLegal(ISD::FMAD, VT)) 9427 return ISD::FMAD; 9428 9429 const TargetOptions &Options = DAG.getTarget().Options; 9430 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9431 (N0->getFlags().hasAllowContract() && 9432 N1->getFlags().hasAllowContract())) && 9433 isFMAFasterThanFMulAndFAdd(VT)) { 9434 return ISD::FMA; 9435 } 9436 9437 return 0; 9438 } 9439 9440 // For a reassociatable opcode perform: 9441 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9442 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9443 SelectionDAG &DAG) const { 9444 EVT VT = N->getValueType(0); 9445 if (VT != MVT::i32 && VT != MVT::i64) 9446 return SDValue(); 9447 9448 unsigned Opc = N->getOpcode(); 9449 SDValue Op0 = N->getOperand(0); 9450 SDValue Op1 = N->getOperand(1); 9451 9452 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9453 return SDValue(); 9454 9455 if (Op0->isDivergent()) 9456 std::swap(Op0, Op1); 9457 9458 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9459 return SDValue(); 9460 9461 SDValue Op2 = Op1.getOperand(1); 9462 Op1 = Op1.getOperand(0); 9463 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9464 return SDValue(); 9465 9466 if (Op1->isDivergent()) 9467 std::swap(Op1, Op2); 9468 9469 // If either operand is constant this will conflict with 9470 // DAGCombiner::ReassociateOps(). 9471 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9472 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9473 return SDValue(); 9474 9475 SDLoc SL(N); 9476 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9477 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9478 } 9479 9480 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9481 EVT VT, 9482 SDValue N0, SDValue N1, SDValue N2, 9483 bool Signed) { 9484 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9485 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9486 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9487 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9488 } 9489 9490 SDValue SITargetLowering::performAddCombine(SDNode *N, 9491 DAGCombinerInfo &DCI) const { 9492 SelectionDAG &DAG = DCI.DAG; 9493 EVT VT = N->getValueType(0); 9494 SDLoc SL(N); 9495 SDValue LHS = N->getOperand(0); 9496 SDValue RHS = N->getOperand(1); 9497 9498 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9499 && Subtarget->hasMad64_32() && 9500 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9501 VT.getScalarSizeInBits() <= 64) { 9502 if (LHS.getOpcode() != ISD::MUL) 9503 std::swap(LHS, RHS); 9504 9505 SDValue MulLHS = LHS.getOperand(0); 9506 SDValue MulRHS = LHS.getOperand(1); 9507 SDValue AddRHS = RHS; 9508 9509 // TODO: Maybe restrict if SGPR inputs. 9510 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9511 numBitsUnsigned(MulRHS, DAG) <= 32) { 9512 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9513 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9514 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9515 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9516 } 9517 9518 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9519 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9520 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9521 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9522 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9523 } 9524 9525 return SDValue(); 9526 } 9527 9528 if (SDValue V = reassociateScalarOps(N, DAG)) { 9529 return V; 9530 } 9531 9532 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9533 return SDValue(); 9534 9535 // add x, zext (setcc) => addcarry x, 0, setcc 9536 // add x, sext (setcc) => subcarry x, 0, setcc 9537 unsigned Opc = LHS.getOpcode(); 9538 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9539 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9540 std::swap(RHS, LHS); 9541 9542 Opc = RHS.getOpcode(); 9543 switch (Opc) { 9544 default: break; 9545 case ISD::ZERO_EXTEND: 9546 case ISD::SIGN_EXTEND: 9547 case ISD::ANY_EXTEND: { 9548 auto Cond = RHS.getOperand(0); 9549 if (!isBoolSGPR(Cond)) 9550 break; 9551 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9552 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9553 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9554 return DAG.getNode(Opc, SL, VTList, Args); 9555 } 9556 case ISD::ADDCARRY: { 9557 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9558 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9559 if (!C || C->getZExtValue() != 0) break; 9560 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9561 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9562 } 9563 } 9564 return SDValue(); 9565 } 9566 9567 SDValue SITargetLowering::performSubCombine(SDNode *N, 9568 DAGCombinerInfo &DCI) const { 9569 SelectionDAG &DAG = DCI.DAG; 9570 EVT VT = N->getValueType(0); 9571 9572 if (VT != MVT::i32) 9573 return SDValue(); 9574 9575 SDLoc SL(N); 9576 SDValue LHS = N->getOperand(0); 9577 SDValue RHS = N->getOperand(1); 9578 9579 if (LHS.getOpcode() == ISD::SUBCARRY) { 9580 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9581 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9582 if (!C || !C->isNullValue()) 9583 return SDValue(); 9584 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9585 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9586 } 9587 return SDValue(); 9588 } 9589 9590 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9591 DAGCombinerInfo &DCI) const { 9592 9593 if (N->getValueType(0) != MVT::i32) 9594 return SDValue(); 9595 9596 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9597 if (!C || C->getZExtValue() != 0) 9598 return SDValue(); 9599 9600 SelectionDAG &DAG = DCI.DAG; 9601 SDValue LHS = N->getOperand(0); 9602 9603 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9604 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9605 unsigned LHSOpc = LHS.getOpcode(); 9606 unsigned Opc = N->getOpcode(); 9607 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9608 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9609 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9610 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9611 } 9612 return SDValue(); 9613 } 9614 9615 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9616 DAGCombinerInfo &DCI) const { 9617 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9618 return SDValue(); 9619 9620 SelectionDAG &DAG = DCI.DAG; 9621 EVT VT = N->getValueType(0); 9622 9623 SDLoc SL(N); 9624 SDValue LHS = N->getOperand(0); 9625 SDValue RHS = N->getOperand(1); 9626 9627 // These should really be instruction patterns, but writing patterns with 9628 // source modiifiers is a pain. 9629 9630 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9631 if (LHS.getOpcode() == ISD::FADD) { 9632 SDValue A = LHS.getOperand(0); 9633 if (A == LHS.getOperand(1)) { 9634 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9635 if (FusedOp != 0) { 9636 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9637 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9638 } 9639 } 9640 } 9641 9642 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9643 if (RHS.getOpcode() == ISD::FADD) { 9644 SDValue A = RHS.getOperand(0); 9645 if (A == RHS.getOperand(1)) { 9646 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9647 if (FusedOp != 0) { 9648 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9649 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9650 } 9651 } 9652 } 9653 9654 return SDValue(); 9655 } 9656 9657 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9658 DAGCombinerInfo &DCI) const { 9659 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9660 return SDValue(); 9661 9662 SelectionDAG &DAG = DCI.DAG; 9663 SDLoc SL(N); 9664 EVT VT = N->getValueType(0); 9665 assert(!VT.isVector()); 9666 9667 // Try to get the fneg to fold into the source modifier. This undoes generic 9668 // DAG combines and folds them into the mad. 9669 // 9670 // Only do this if we are not trying to support denormals. v_mad_f32 does 9671 // not support denormals ever. 9672 SDValue LHS = N->getOperand(0); 9673 SDValue RHS = N->getOperand(1); 9674 if (LHS.getOpcode() == ISD::FADD) { 9675 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9676 SDValue A = LHS.getOperand(0); 9677 if (A == LHS.getOperand(1)) { 9678 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9679 if (FusedOp != 0){ 9680 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9681 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9682 9683 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9684 } 9685 } 9686 } 9687 9688 if (RHS.getOpcode() == ISD::FADD) { 9689 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9690 9691 SDValue A = RHS.getOperand(0); 9692 if (A == RHS.getOperand(1)) { 9693 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9694 if (FusedOp != 0){ 9695 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9696 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9697 } 9698 } 9699 } 9700 9701 return SDValue(); 9702 } 9703 9704 SDValue SITargetLowering::performFMACombine(SDNode *N, 9705 DAGCombinerInfo &DCI) const { 9706 SelectionDAG &DAG = DCI.DAG; 9707 EVT VT = N->getValueType(0); 9708 SDLoc SL(N); 9709 9710 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9711 return SDValue(); 9712 9713 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9714 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9715 SDValue Op1 = N->getOperand(0); 9716 SDValue Op2 = N->getOperand(1); 9717 SDValue FMA = N->getOperand(2); 9718 9719 if (FMA.getOpcode() != ISD::FMA || 9720 Op1.getOpcode() != ISD::FP_EXTEND || 9721 Op2.getOpcode() != ISD::FP_EXTEND) 9722 return SDValue(); 9723 9724 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9725 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9726 // is sufficient to allow generaing fdot2. 9727 const TargetOptions &Options = DAG.getTarget().Options; 9728 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9729 (N->getFlags().hasAllowContract() && 9730 FMA->getFlags().hasAllowContract())) { 9731 Op1 = Op1.getOperand(0); 9732 Op2 = Op2.getOperand(0); 9733 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9734 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9735 return SDValue(); 9736 9737 SDValue Vec1 = Op1.getOperand(0); 9738 SDValue Idx1 = Op1.getOperand(1); 9739 SDValue Vec2 = Op2.getOperand(0); 9740 9741 SDValue FMAOp1 = FMA.getOperand(0); 9742 SDValue FMAOp2 = FMA.getOperand(1); 9743 SDValue FMAAcc = FMA.getOperand(2); 9744 9745 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9746 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9747 return SDValue(); 9748 9749 FMAOp1 = FMAOp1.getOperand(0); 9750 FMAOp2 = FMAOp2.getOperand(0); 9751 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9752 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9753 return SDValue(); 9754 9755 SDValue Vec3 = FMAOp1.getOperand(0); 9756 SDValue Vec4 = FMAOp2.getOperand(0); 9757 SDValue Idx2 = FMAOp1.getOperand(1); 9758 9759 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9760 // Idx1 and Idx2 cannot be the same. 9761 Idx1 == Idx2) 9762 return SDValue(); 9763 9764 if (Vec1 == Vec2 || Vec3 == Vec4) 9765 return SDValue(); 9766 9767 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9768 return SDValue(); 9769 9770 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9771 (Vec1 == Vec4 && Vec2 == Vec3)) { 9772 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9773 DAG.getTargetConstant(0, SL, MVT::i1)); 9774 } 9775 } 9776 return SDValue(); 9777 } 9778 9779 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9780 DAGCombinerInfo &DCI) const { 9781 SelectionDAG &DAG = DCI.DAG; 9782 SDLoc SL(N); 9783 9784 SDValue LHS = N->getOperand(0); 9785 SDValue RHS = N->getOperand(1); 9786 EVT VT = LHS.getValueType(); 9787 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9788 9789 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9790 if (!CRHS) { 9791 CRHS = dyn_cast<ConstantSDNode>(LHS); 9792 if (CRHS) { 9793 std::swap(LHS, RHS); 9794 CC = getSetCCSwappedOperands(CC); 9795 } 9796 } 9797 9798 if (CRHS) { 9799 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9800 isBoolSGPR(LHS.getOperand(0))) { 9801 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9802 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9803 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9804 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9805 if ((CRHS->isAllOnesValue() && 9806 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9807 (CRHS->isNullValue() && 9808 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9809 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9810 DAG.getConstant(-1, SL, MVT::i1)); 9811 if ((CRHS->isAllOnesValue() && 9812 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9813 (CRHS->isNullValue() && 9814 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9815 return LHS.getOperand(0); 9816 } 9817 9818 uint64_t CRHSVal = CRHS->getZExtValue(); 9819 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9820 LHS.getOpcode() == ISD::SELECT && 9821 isa<ConstantSDNode>(LHS.getOperand(1)) && 9822 isa<ConstantSDNode>(LHS.getOperand(2)) && 9823 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9824 isBoolSGPR(LHS.getOperand(0))) { 9825 // Given CT != FT: 9826 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9827 // setcc (select cc, CT, CF), CF, ne => cc 9828 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9829 // setcc (select cc, CT, CF), CT, eq => cc 9830 uint64_t CT = LHS.getConstantOperandVal(1); 9831 uint64_t CF = LHS.getConstantOperandVal(2); 9832 9833 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9834 (CT == CRHSVal && CC == ISD::SETNE)) 9835 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9836 DAG.getConstant(-1, SL, MVT::i1)); 9837 if ((CF == CRHSVal && CC == ISD::SETNE) || 9838 (CT == CRHSVal && CC == ISD::SETEQ)) 9839 return LHS.getOperand(0); 9840 } 9841 } 9842 9843 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9844 VT != MVT::f16)) 9845 return SDValue(); 9846 9847 // Match isinf/isfinite pattern 9848 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9849 // (fcmp one (fabs x), inf) -> (fp_class x, 9850 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9851 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9852 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9853 if (!CRHS) 9854 return SDValue(); 9855 9856 const APFloat &APF = CRHS->getValueAPF(); 9857 if (APF.isInfinity() && !APF.isNegative()) { 9858 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9859 SIInstrFlags::N_INFINITY; 9860 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9861 SIInstrFlags::P_ZERO | 9862 SIInstrFlags::N_NORMAL | 9863 SIInstrFlags::P_NORMAL | 9864 SIInstrFlags::N_SUBNORMAL | 9865 SIInstrFlags::P_SUBNORMAL; 9866 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9867 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9868 DAG.getConstant(Mask, SL, MVT::i32)); 9869 } 9870 } 9871 9872 return SDValue(); 9873 } 9874 9875 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9876 DAGCombinerInfo &DCI) const { 9877 SelectionDAG &DAG = DCI.DAG; 9878 SDLoc SL(N); 9879 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9880 9881 SDValue Src = N->getOperand(0); 9882 SDValue Srl = N->getOperand(0); 9883 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9884 Srl = Srl.getOperand(0); 9885 9886 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9887 if (Srl.getOpcode() == ISD::SRL) { 9888 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9889 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9890 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9891 9892 if (const ConstantSDNode *C = 9893 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9894 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9895 EVT(MVT::i32)); 9896 9897 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9898 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9899 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9900 MVT::f32, Srl); 9901 } 9902 } 9903 } 9904 9905 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9906 9907 KnownBits Known; 9908 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9909 !DCI.isBeforeLegalizeOps()); 9910 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9911 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9912 DCI.CommitTargetLoweringOpt(TLO); 9913 } 9914 9915 return SDValue(); 9916 } 9917 9918 SDValue SITargetLowering::performClampCombine(SDNode *N, 9919 DAGCombinerInfo &DCI) const { 9920 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9921 if (!CSrc) 9922 return SDValue(); 9923 9924 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9925 const APFloat &F = CSrc->getValueAPF(); 9926 APFloat Zero = APFloat::getZero(F.getSemantics()); 9927 APFloat::cmpResult Cmp0 = F.compare(Zero); 9928 if (Cmp0 == APFloat::cmpLessThan || 9929 (Cmp0 == APFloat::cmpUnordered && 9930 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9931 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9932 } 9933 9934 APFloat One(F.getSemantics(), "1.0"); 9935 APFloat::cmpResult Cmp1 = F.compare(One); 9936 if (Cmp1 == APFloat::cmpGreaterThan) 9937 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9938 9939 return SDValue(CSrc, 0); 9940 } 9941 9942 9943 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9944 DAGCombinerInfo &DCI) const { 9945 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9946 return SDValue(); 9947 switch (N->getOpcode()) { 9948 default: 9949 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9950 case ISD::ADD: 9951 return performAddCombine(N, DCI); 9952 case ISD::SUB: 9953 return performSubCombine(N, DCI); 9954 case ISD::ADDCARRY: 9955 case ISD::SUBCARRY: 9956 return performAddCarrySubCarryCombine(N, DCI); 9957 case ISD::FADD: 9958 return performFAddCombine(N, DCI); 9959 case ISD::FSUB: 9960 return performFSubCombine(N, DCI); 9961 case ISD::SETCC: 9962 return performSetCCCombine(N, DCI); 9963 case ISD::FMAXNUM: 9964 case ISD::FMINNUM: 9965 case ISD::FMAXNUM_IEEE: 9966 case ISD::FMINNUM_IEEE: 9967 case ISD::SMAX: 9968 case ISD::SMIN: 9969 case ISD::UMAX: 9970 case ISD::UMIN: 9971 case AMDGPUISD::FMIN_LEGACY: 9972 case AMDGPUISD::FMAX_LEGACY: 9973 return performMinMaxCombine(N, DCI); 9974 case ISD::FMA: 9975 return performFMACombine(N, DCI); 9976 case ISD::LOAD: { 9977 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9978 return Widended; 9979 LLVM_FALLTHROUGH; 9980 } 9981 case ISD::STORE: 9982 case ISD::ATOMIC_LOAD: 9983 case ISD::ATOMIC_STORE: 9984 case ISD::ATOMIC_CMP_SWAP: 9985 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9986 case ISD::ATOMIC_SWAP: 9987 case ISD::ATOMIC_LOAD_ADD: 9988 case ISD::ATOMIC_LOAD_SUB: 9989 case ISD::ATOMIC_LOAD_AND: 9990 case ISD::ATOMIC_LOAD_OR: 9991 case ISD::ATOMIC_LOAD_XOR: 9992 case ISD::ATOMIC_LOAD_NAND: 9993 case ISD::ATOMIC_LOAD_MIN: 9994 case ISD::ATOMIC_LOAD_MAX: 9995 case ISD::ATOMIC_LOAD_UMIN: 9996 case ISD::ATOMIC_LOAD_UMAX: 9997 case ISD::ATOMIC_LOAD_FADD: 9998 case AMDGPUISD::ATOMIC_INC: 9999 case AMDGPUISD::ATOMIC_DEC: 10000 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10001 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10002 if (DCI.isBeforeLegalize()) 10003 break; 10004 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10005 case ISD::AND: 10006 return performAndCombine(N, DCI); 10007 case ISD::OR: 10008 return performOrCombine(N, DCI); 10009 case ISD::XOR: 10010 return performXorCombine(N, DCI); 10011 case ISD::ZERO_EXTEND: 10012 return performZeroExtendCombine(N, DCI); 10013 case ISD::SIGN_EXTEND_INREG: 10014 return performSignExtendInRegCombine(N , DCI); 10015 case AMDGPUISD::FP_CLASS: 10016 return performClassCombine(N, DCI); 10017 case ISD::FCANONICALIZE: 10018 return performFCanonicalizeCombine(N, DCI); 10019 case AMDGPUISD::RCP: 10020 return performRcpCombine(N, DCI); 10021 case AMDGPUISD::FRACT: 10022 case AMDGPUISD::RSQ: 10023 case AMDGPUISD::RCP_LEGACY: 10024 case AMDGPUISD::RSQ_LEGACY: 10025 case AMDGPUISD::RCP_IFLAG: 10026 case AMDGPUISD::RSQ_CLAMP: 10027 case AMDGPUISD::LDEXP: { 10028 SDValue Src = N->getOperand(0); 10029 if (Src.isUndef()) 10030 return Src; 10031 break; 10032 } 10033 case ISD::SINT_TO_FP: 10034 case ISD::UINT_TO_FP: 10035 return performUCharToFloatCombine(N, DCI); 10036 case AMDGPUISD::CVT_F32_UBYTE0: 10037 case AMDGPUISD::CVT_F32_UBYTE1: 10038 case AMDGPUISD::CVT_F32_UBYTE2: 10039 case AMDGPUISD::CVT_F32_UBYTE3: 10040 return performCvtF32UByteNCombine(N, DCI); 10041 case AMDGPUISD::FMED3: 10042 return performFMed3Combine(N, DCI); 10043 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10044 return performCvtPkRTZCombine(N, DCI); 10045 case AMDGPUISD::CLAMP: 10046 return performClampCombine(N, DCI); 10047 case ISD::SCALAR_TO_VECTOR: { 10048 SelectionDAG &DAG = DCI.DAG; 10049 EVT VT = N->getValueType(0); 10050 10051 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10052 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10053 SDLoc SL(N); 10054 SDValue Src = N->getOperand(0); 10055 EVT EltVT = Src.getValueType(); 10056 if (EltVT == MVT::f16) 10057 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10058 10059 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10060 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10061 } 10062 10063 break; 10064 } 10065 case ISD::EXTRACT_VECTOR_ELT: 10066 return performExtractVectorEltCombine(N, DCI); 10067 case ISD::INSERT_VECTOR_ELT: 10068 return performInsertVectorEltCombine(N, DCI); 10069 } 10070 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10071 } 10072 10073 /// Helper function for adjustWritemask 10074 static unsigned SubIdx2Lane(unsigned Idx) { 10075 switch (Idx) { 10076 default: return 0; 10077 case AMDGPU::sub0: return 0; 10078 case AMDGPU::sub1: return 1; 10079 case AMDGPU::sub2: return 2; 10080 case AMDGPU::sub3: return 3; 10081 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10082 } 10083 } 10084 10085 /// Adjust the writemask of MIMG instructions 10086 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10087 SelectionDAG &DAG) const { 10088 unsigned Opcode = Node->getMachineOpcode(); 10089 10090 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10091 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10092 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10093 return Node; // not implemented for D16 10094 10095 SDNode *Users[5] = { nullptr }; 10096 unsigned Lane = 0; 10097 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10098 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10099 unsigned NewDmask = 0; 10100 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10101 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10102 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10103 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10104 unsigned TFCLane = 0; 10105 bool HasChain = Node->getNumValues() > 1; 10106 10107 if (OldDmask == 0) { 10108 // These are folded out, but on the chance it happens don't assert. 10109 return Node; 10110 } 10111 10112 unsigned OldBitsSet = countPopulation(OldDmask); 10113 // Work out which is the TFE/LWE lane if that is enabled. 10114 if (UsesTFC) { 10115 TFCLane = OldBitsSet; 10116 } 10117 10118 // Try to figure out the used register components 10119 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10120 I != E; ++I) { 10121 10122 // Don't look at users of the chain. 10123 if (I.getUse().getResNo() != 0) 10124 continue; 10125 10126 // Abort if we can't understand the usage 10127 if (!I->isMachineOpcode() || 10128 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10129 return Node; 10130 10131 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10132 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10133 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10134 // set, etc. 10135 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10136 10137 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10138 if (UsesTFC && Lane == TFCLane) { 10139 Users[Lane] = *I; 10140 } else { 10141 // Set which texture component corresponds to the lane. 10142 unsigned Comp; 10143 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10144 Comp = countTrailingZeros(Dmask); 10145 Dmask &= ~(1 << Comp); 10146 } 10147 10148 // Abort if we have more than one user per component. 10149 if (Users[Lane]) 10150 return Node; 10151 10152 Users[Lane] = *I; 10153 NewDmask |= 1 << Comp; 10154 } 10155 } 10156 10157 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10158 bool NoChannels = !NewDmask; 10159 if (NoChannels) { 10160 if (!UsesTFC) { 10161 // No uses of the result and not using TFC. Then do nothing. 10162 return Node; 10163 } 10164 // If the original dmask has one channel - then nothing to do 10165 if (OldBitsSet == 1) 10166 return Node; 10167 // Use an arbitrary dmask - required for the instruction to work 10168 NewDmask = 1; 10169 } 10170 // Abort if there's no change 10171 if (NewDmask == OldDmask) 10172 return Node; 10173 10174 unsigned BitsSet = countPopulation(NewDmask); 10175 10176 // Check for TFE or LWE - increase the number of channels by one to account 10177 // for the extra return value 10178 // This will need adjustment for D16 if this is also included in 10179 // adjustWriteMask (this function) but at present D16 are excluded. 10180 unsigned NewChannels = BitsSet + UsesTFC; 10181 10182 int NewOpcode = 10183 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10184 assert(NewOpcode != -1 && 10185 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10186 "failed to find equivalent MIMG op"); 10187 10188 // Adjust the writemask in the node 10189 SmallVector<SDValue, 12> Ops; 10190 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10191 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10192 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10193 10194 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10195 10196 MVT ResultVT = NewChannels == 1 ? 10197 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10198 NewChannels == 5 ? 8 : NewChannels); 10199 SDVTList NewVTList = HasChain ? 10200 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10201 10202 10203 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10204 NewVTList, Ops); 10205 10206 if (HasChain) { 10207 // Update chain. 10208 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10209 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10210 } 10211 10212 if (NewChannels == 1) { 10213 assert(Node->hasNUsesOfValue(1, 0)); 10214 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10215 SDLoc(Node), Users[Lane]->getValueType(0), 10216 SDValue(NewNode, 0)); 10217 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10218 return nullptr; 10219 } 10220 10221 // Update the users of the node with the new indices 10222 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10223 SDNode *User = Users[i]; 10224 if (!User) { 10225 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10226 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10227 if (i || !NoChannels) 10228 continue; 10229 } else { 10230 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10231 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10232 } 10233 10234 switch (Idx) { 10235 default: break; 10236 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10237 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10238 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10239 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10240 } 10241 } 10242 10243 DAG.RemoveDeadNode(Node); 10244 return nullptr; 10245 } 10246 10247 static bool isFrameIndexOp(SDValue Op) { 10248 if (Op.getOpcode() == ISD::AssertZext) 10249 Op = Op.getOperand(0); 10250 10251 return isa<FrameIndexSDNode>(Op); 10252 } 10253 10254 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10255 /// with frame index operands. 10256 /// LLVM assumes that inputs are to these instructions are registers. 10257 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10258 SelectionDAG &DAG) const { 10259 if (Node->getOpcode() == ISD::CopyToReg) { 10260 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10261 SDValue SrcVal = Node->getOperand(2); 10262 10263 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10264 // to try understanding copies to physical registers. 10265 if (SrcVal.getValueType() == MVT::i1 && 10266 Register::isPhysicalRegister(DestReg->getReg())) { 10267 SDLoc SL(Node); 10268 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10269 SDValue VReg = DAG.getRegister( 10270 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10271 10272 SDNode *Glued = Node->getGluedNode(); 10273 SDValue ToVReg 10274 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10275 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10276 SDValue ToResultReg 10277 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10278 VReg, ToVReg.getValue(1)); 10279 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10280 DAG.RemoveDeadNode(Node); 10281 return ToResultReg.getNode(); 10282 } 10283 } 10284 10285 SmallVector<SDValue, 8> Ops; 10286 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10287 if (!isFrameIndexOp(Node->getOperand(i))) { 10288 Ops.push_back(Node->getOperand(i)); 10289 continue; 10290 } 10291 10292 SDLoc DL(Node); 10293 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10294 Node->getOperand(i).getValueType(), 10295 Node->getOperand(i)), 0)); 10296 } 10297 10298 return DAG.UpdateNodeOperands(Node, Ops); 10299 } 10300 10301 /// Fold the instructions after selecting them. 10302 /// Returns null if users were already updated. 10303 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10304 SelectionDAG &DAG) const { 10305 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10306 unsigned Opcode = Node->getMachineOpcode(); 10307 10308 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10309 !TII->isGather4(Opcode)) { 10310 return adjustWritemask(Node, DAG); 10311 } 10312 10313 if (Opcode == AMDGPU::INSERT_SUBREG || 10314 Opcode == AMDGPU::REG_SEQUENCE) { 10315 legalizeTargetIndependentNode(Node, DAG); 10316 return Node; 10317 } 10318 10319 switch (Opcode) { 10320 case AMDGPU::V_DIV_SCALE_F32: 10321 case AMDGPU::V_DIV_SCALE_F64: { 10322 // Satisfy the operand register constraint when one of the inputs is 10323 // undefined. Ordinarily each undef value will have its own implicit_def of 10324 // a vreg, so force these to use a single register. 10325 SDValue Src0 = Node->getOperand(0); 10326 SDValue Src1 = Node->getOperand(1); 10327 SDValue Src2 = Node->getOperand(2); 10328 10329 if ((Src0.isMachineOpcode() && 10330 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10331 (Src0 == Src1 || Src0 == Src2)) 10332 break; 10333 10334 MVT VT = Src0.getValueType().getSimpleVT(); 10335 const TargetRegisterClass *RC = 10336 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10337 10338 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10339 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10340 10341 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10342 UndefReg, Src0, SDValue()); 10343 10344 // src0 must be the same register as src1 or src2, even if the value is 10345 // undefined, so make sure we don't violate this constraint. 10346 if (Src0.isMachineOpcode() && 10347 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10348 if (Src1.isMachineOpcode() && 10349 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10350 Src0 = Src1; 10351 else if (Src2.isMachineOpcode() && 10352 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10353 Src0 = Src2; 10354 else { 10355 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10356 Src0 = UndefReg; 10357 Src1 = UndefReg; 10358 } 10359 } else 10360 break; 10361 10362 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10363 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10364 Ops.push_back(Node->getOperand(I)); 10365 10366 Ops.push_back(ImpDef.getValue(1)); 10367 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10368 } 10369 case AMDGPU::V_PERMLANE16_B32: 10370 case AMDGPU::V_PERMLANEX16_B32: { 10371 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10372 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10373 if (!FI->getZExtValue() && !BC->getZExtValue()) 10374 break; 10375 SDValue VDstIn = Node->getOperand(6); 10376 if (VDstIn.isMachineOpcode() 10377 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10378 break; 10379 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10380 SDLoc(Node), MVT::i32); 10381 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10382 SDValue(BC, 0), Node->getOperand(3), 10383 Node->getOperand(4), Node->getOperand(5), 10384 SDValue(ImpDef, 0), Node->getOperand(7) }; 10385 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10386 } 10387 default: 10388 break; 10389 } 10390 10391 return Node; 10392 } 10393 10394 /// Assign the register class depending on the number of 10395 /// bits set in the writemask 10396 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10397 SDNode *Node) const { 10398 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10399 10400 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10401 10402 if (TII->isVOP3(MI.getOpcode())) { 10403 // Make sure constant bus requirements are respected. 10404 TII->legalizeOperandsVOP3(MRI, MI); 10405 10406 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10407 // This saves a chain-copy of registers and better ballance register 10408 // use between vgpr and agpr as agpr tuples tend to be big. 10409 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10410 unsigned Opc = MI.getOpcode(); 10411 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10412 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10413 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10414 if (I == -1) 10415 break; 10416 MachineOperand &Op = MI.getOperand(I); 10417 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10418 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10419 !Register::isVirtualRegister(Op.getReg()) || 10420 !TRI->isAGPR(MRI, Op.getReg())) 10421 continue; 10422 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10423 if (!Src || !Src->isCopy() || 10424 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10425 continue; 10426 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10427 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10428 // All uses of agpr64 and agpr32 can also accept vgpr except for 10429 // v_accvgpr_read, but we do not produce agpr reads during selection, 10430 // so no use checks are needed. 10431 MRI.setRegClass(Op.getReg(), NewRC); 10432 } 10433 } 10434 10435 return; 10436 } 10437 10438 // Replace unused atomics with the no return version. 10439 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10440 if (NoRetAtomicOp != -1) { 10441 if (!Node->hasAnyUseOfValue(0)) { 10442 MI.setDesc(TII->get(NoRetAtomicOp)); 10443 MI.RemoveOperand(0); 10444 return; 10445 } 10446 10447 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10448 // instruction, because the return type of these instructions is a vec2 of 10449 // the memory type, so it can be tied to the input operand. 10450 // This means these instructions always have a use, so we need to add a 10451 // special case to check if the atomic has only one extract_subreg use, 10452 // which itself has no uses. 10453 if ((Node->hasNUsesOfValue(1, 0) && 10454 Node->use_begin()->isMachineOpcode() && 10455 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10456 !Node->use_begin()->hasAnyUseOfValue(0))) { 10457 Register Def = MI.getOperand(0).getReg(); 10458 10459 // Change this into a noret atomic. 10460 MI.setDesc(TII->get(NoRetAtomicOp)); 10461 MI.RemoveOperand(0); 10462 10463 // If we only remove the def operand from the atomic instruction, the 10464 // extract_subreg will be left with a use of a vreg without a def. 10465 // So we need to insert an implicit_def to avoid machine verifier 10466 // errors. 10467 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10468 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10469 } 10470 return; 10471 } 10472 } 10473 10474 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10475 uint64_t Val) { 10476 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10477 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10478 } 10479 10480 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10481 const SDLoc &DL, 10482 SDValue Ptr) const { 10483 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10484 10485 // Build the half of the subregister with the constants before building the 10486 // full 128-bit register. If we are building multiple resource descriptors, 10487 // this will allow CSEing of the 2-component register. 10488 const SDValue Ops0[] = { 10489 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10490 buildSMovImm32(DAG, DL, 0), 10491 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10492 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10493 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10494 }; 10495 10496 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10497 MVT::v2i32, Ops0), 0); 10498 10499 // Combine the constants and the pointer. 10500 const SDValue Ops1[] = { 10501 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10502 Ptr, 10503 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10504 SubRegHi, 10505 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10506 }; 10507 10508 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10509 } 10510 10511 /// Return a resource descriptor with the 'Add TID' bit enabled 10512 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10513 /// of the resource descriptor) to create an offset, which is added to 10514 /// the resource pointer. 10515 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10516 SDValue Ptr, uint32_t RsrcDword1, 10517 uint64_t RsrcDword2And3) const { 10518 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10519 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10520 if (RsrcDword1) { 10521 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10522 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10523 0); 10524 } 10525 10526 SDValue DataLo = buildSMovImm32(DAG, DL, 10527 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10528 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10529 10530 const SDValue Ops[] = { 10531 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10532 PtrLo, 10533 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10534 PtrHi, 10535 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10536 DataLo, 10537 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10538 DataHi, 10539 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10540 }; 10541 10542 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10543 } 10544 10545 //===----------------------------------------------------------------------===// 10546 // SI Inline Assembly Support 10547 //===----------------------------------------------------------------------===// 10548 10549 std::pair<unsigned, const TargetRegisterClass *> 10550 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10551 StringRef Constraint, 10552 MVT VT) const { 10553 const TargetRegisterClass *RC = nullptr; 10554 if (Constraint.size() == 1) { 10555 switch (Constraint[0]) { 10556 default: 10557 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10558 case 's': 10559 case 'r': 10560 switch (VT.getSizeInBits()) { 10561 default: 10562 return std::make_pair(0U, nullptr); 10563 case 32: 10564 case 16: 10565 RC = &AMDGPU::SReg_32_XM0RegClass; 10566 break; 10567 case 64: 10568 RC = &AMDGPU::SGPR_64RegClass; 10569 break; 10570 case 96: 10571 RC = &AMDGPU::SReg_96RegClass; 10572 break; 10573 case 128: 10574 RC = &AMDGPU::SGPR_128RegClass; 10575 break; 10576 case 160: 10577 RC = &AMDGPU::SReg_160RegClass; 10578 break; 10579 case 256: 10580 RC = &AMDGPU::SReg_256RegClass; 10581 break; 10582 case 512: 10583 RC = &AMDGPU::SReg_512RegClass; 10584 break; 10585 } 10586 break; 10587 case 'v': 10588 switch (VT.getSizeInBits()) { 10589 default: 10590 return std::make_pair(0U, nullptr); 10591 case 32: 10592 case 16: 10593 RC = &AMDGPU::VGPR_32RegClass; 10594 break; 10595 case 64: 10596 RC = &AMDGPU::VReg_64RegClass; 10597 break; 10598 case 96: 10599 RC = &AMDGPU::VReg_96RegClass; 10600 break; 10601 case 128: 10602 RC = &AMDGPU::VReg_128RegClass; 10603 break; 10604 case 160: 10605 RC = &AMDGPU::VReg_160RegClass; 10606 break; 10607 case 256: 10608 RC = &AMDGPU::VReg_256RegClass; 10609 break; 10610 case 512: 10611 RC = &AMDGPU::VReg_512RegClass; 10612 break; 10613 } 10614 break; 10615 case 'a': 10616 if (!Subtarget->hasMAIInsts()) 10617 break; 10618 switch (VT.getSizeInBits()) { 10619 default: 10620 return std::make_pair(0U, nullptr); 10621 case 32: 10622 case 16: 10623 RC = &AMDGPU::AGPR_32RegClass; 10624 break; 10625 case 64: 10626 RC = &AMDGPU::AReg_64RegClass; 10627 break; 10628 case 128: 10629 RC = &AMDGPU::AReg_128RegClass; 10630 break; 10631 case 512: 10632 RC = &AMDGPU::AReg_512RegClass; 10633 break; 10634 case 1024: 10635 RC = &AMDGPU::AReg_1024RegClass; 10636 // v32 types are not legal but we support them here. 10637 return std::make_pair(0U, RC); 10638 } 10639 break; 10640 } 10641 // We actually support i128, i16 and f16 as inline parameters 10642 // even if they are not reported as legal 10643 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10644 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10645 return std::make_pair(0U, RC); 10646 } 10647 10648 if (Constraint.size() > 1) { 10649 if (Constraint[1] == 'v') { 10650 RC = &AMDGPU::VGPR_32RegClass; 10651 } else if (Constraint[1] == 's') { 10652 RC = &AMDGPU::SGPR_32RegClass; 10653 } else if (Constraint[1] == 'a') { 10654 RC = &AMDGPU::AGPR_32RegClass; 10655 } 10656 10657 if (RC) { 10658 uint32_t Idx; 10659 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10660 if (!Failed && Idx < RC->getNumRegs()) 10661 return std::make_pair(RC->getRegister(Idx), RC); 10662 } 10663 } 10664 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10665 } 10666 10667 SITargetLowering::ConstraintType 10668 SITargetLowering::getConstraintType(StringRef Constraint) const { 10669 if (Constraint.size() == 1) { 10670 switch (Constraint[0]) { 10671 default: break; 10672 case 's': 10673 case 'v': 10674 case 'a': 10675 return C_RegisterClass; 10676 } 10677 } 10678 return TargetLowering::getConstraintType(Constraint); 10679 } 10680 10681 // Figure out which registers should be reserved for stack access. Only after 10682 // the function is legalized do we know all of the non-spill stack objects or if 10683 // calls are present. 10684 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10685 MachineRegisterInfo &MRI = MF.getRegInfo(); 10686 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10687 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10688 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10689 10690 if (Info->isEntryFunction()) { 10691 // Callable functions have fixed registers used for stack access. 10692 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10693 } 10694 10695 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10696 Info->getStackPtrOffsetReg())); 10697 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10698 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10699 10700 // We need to worry about replacing the default register with itself in case 10701 // of MIR testcases missing the MFI. 10702 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10703 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10704 10705 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10706 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10707 10708 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10709 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10710 Info->getScratchWaveOffsetReg()); 10711 } 10712 10713 Info->limitOccupancy(MF); 10714 10715 if (ST.isWave32() && !MF.empty()) { 10716 // Add VCC_HI def because many instructions marked as imp-use VCC where 10717 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10718 // having a use of undef. 10719 10720 const SIInstrInfo *TII = ST.getInstrInfo(); 10721 DebugLoc DL; 10722 10723 MachineBasicBlock &MBB = MF.front(); 10724 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10725 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10726 10727 for (auto &MBB : MF) { 10728 for (auto &MI : MBB) { 10729 TII->fixImplicitOperands(MI); 10730 } 10731 } 10732 } 10733 10734 TargetLoweringBase::finalizeLowering(MF); 10735 } 10736 10737 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10738 KnownBits &Known, 10739 const APInt &DemandedElts, 10740 const SelectionDAG &DAG, 10741 unsigned Depth) const { 10742 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10743 DAG, Depth); 10744 10745 // Set the high bits to zero based on the maximum allowed scratch size per 10746 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10747 // calculation won't overflow, so assume the sign bit is never set. 10748 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10749 } 10750 10751 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10752 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10753 const Align CacheLineAlign = Align(64); 10754 10755 // Pre-GFX10 target did not benefit from loop alignment 10756 if (!ML || DisableLoopAlignment || 10757 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10758 getSubtarget()->hasInstFwdPrefetchBug()) 10759 return PrefAlign; 10760 10761 // On GFX10 I$ is 4 x 64 bytes cache lines. 10762 // By default prefetcher keeps one cache line behind and reads two ahead. 10763 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10764 // behind and one ahead. 10765 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10766 // If loop fits 64 bytes it always spans no more than two cache lines and 10767 // does not need an alignment. 10768 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10769 // Else if loop is less or equal 192 bytes we need two lines behind. 10770 10771 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10772 const MachineBasicBlock *Header = ML->getHeader(); 10773 if (Header->getAlignment() != PrefAlign) 10774 return Header->getAlignment(); // Already processed. 10775 10776 unsigned LoopSize = 0; 10777 for (const MachineBasicBlock *MBB : ML->blocks()) { 10778 // If inner loop block is aligned assume in average half of the alignment 10779 // size to be added as nops. 10780 if (MBB != Header) 10781 LoopSize += MBB->getAlignment().value() / 2; 10782 10783 for (const MachineInstr &MI : *MBB) { 10784 LoopSize += TII->getInstSizeInBytes(MI); 10785 if (LoopSize > 192) 10786 return PrefAlign; 10787 } 10788 } 10789 10790 if (LoopSize <= 64) 10791 return PrefAlign; 10792 10793 if (LoopSize <= 128) 10794 return CacheLineAlign; 10795 10796 // If any of parent loops is surrounded by prefetch instructions do not 10797 // insert new for inner loop, which would reset parent's settings. 10798 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10799 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10800 auto I = Exit->getFirstNonDebugInstr(); 10801 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10802 return CacheLineAlign; 10803 } 10804 } 10805 10806 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10807 MachineBasicBlock *Exit = ML->getExitBlock(); 10808 10809 if (Pre && Exit) { 10810 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10811 TII->get(AMDGPU::S_INST_PREFETCH)) 10812 .addImm(1); // prefetch 2 lines behind PC 10813 10814 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10815 TII->get(AMDGPU::S_INST_PREFETCH)) 10816 .addImm(2); // prefetch 1 line behind PC 10817 } 10818 10819 return CacheLineAlign; 10820 } 10821 10822 LLVM_ATTRIBUTE_UNUSED 10823 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10824 assert(N->getOpcode() == ISD::CopyFromReg); 10825 do { 10826 // Follow the chain until we find an INLINEASM node. 10827 N = N->getOperand(0).getNode(); 10828 if (N->getOpcode() == ISD::INLINEASM || 10829 N->getOpcode() == ISD::INLINEASM_BR) 10830 return true; 10831 } while (N->getOpcode() == ISD::CopyFromReg); 10832 return false; 10833 } 10834 10835 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10836 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10837 { 10838 switch (N->getOpcode()) { 10839 case ISD::CopyFromReg: 10840 { 10841 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10842 const MachineFunction * MF = FLI->MF; 10843 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10844 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10845 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10846 unsigned Reg = R->getReg(); 10847 if (Register::isPhysicalRegister(Reg)) 10848 return !TRI.isSGPRReg(MRI, Reg); 10849 10850 if (MRI.isLiveIn(Reg)) { 10851 // workitem.id.x workitem.id.y workitem.id.z 10852 // Any VGPR formal argument is also considered divergent 10853 if (!TRI.isSGPRReg(MRI, Reg)) 10854 return true; 10855 // Formal arguments of non-entry functions 10856 // are conservatively considered divergent 10857 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10858 return true; 10859 return false; 10860 } 10861 const Value *V = FLI->getValueFromVirtualReg(Reg); 10862 if (V) 10863 return KDA->isDivergent(V); 10864 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10865 return !TRI.isSGPRReg(MRI, Reg); 10866 } 10867 break; 10868 case ISD::LOAD: { 10869 const LoadSDNode *L = cast<LoadSDNode>(N); 10870 unsigned AS = L->getAddressSpace(); 10871 // A flat load may access private memory. 10872 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10873 } break; 10874 case ISD::CALLSEQ_END: 10875 return true; 10876 break; 10877 case ISD::INTRINSIC_WO_CHAIN: 10878 { 10879 10880 } 10881 return AMDGPU::isIntrinsicSourceOfDivergence( 10882 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10883 case ISD::INTRINSIC_W_CHAIN: 10884 return AMDGPU::isIntrinsicSourceOfDivergence( 10885 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10886 // In some cases intrinsics that are a source of divergence have been 10887 // lowered to AMDGPUISD so we also need to check those too. 10888 case AMDGPUISD::INTERP_MOV: 10889 case AMDGPUISD::INTERP_P1: 10890 case AMDGPUISD::INTERP_P2: 10891 return true; 10892 } 10893 return false; 10894 } 10895 10896 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 10897 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10898 case MVT::f32: 10899 return Subtarget->hasFP32Denormals(); 10900 case MVT::f64: 10901 return Subtarget->hasFP64Denormals(); 10902 case MVT::f16: 10903 return Subtarget->hasFP16Denormals(); 10904 default: 10905 return false; 10906 } 10907 } 10908 10909 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10910 const SelectionDAG &DAG, 10911 bool SNaN, 10912 unsigned Depth) const { 10913 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10914 const MachineFunction &MF = DAG.getMachineFunction(); 10915 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10916 10917 if (Info->getMode().DX10Clamp) 10918 return true; // Clamped to 0. 10919 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10920 } 10921 10922 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10923 SNaN, Depth); 10924 } 10925 10926 TargetLowering::AtomicExpansionKind 10927 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10928 switch (RMW->getOperation()) { 10929 case AtomicRMWInst::FAdd: { 10930 Type *Ty = RMW->getType(); 10931 10932 // We don't have a way to support 16-bit atomics now, so just leave them 10933 // as-is. 10934 if (Ty->isHalfTy()) 10935 return AtomicExpansionKind::None; 10936 10937 if (!Ty->isFloatTy()) 10938 return AtomicExpansionKind::CmpXChg; 10939 10940 // TODO: Do have these for flat. Older targets also had them for buffers. 10941 unsigned AS = RMW->getPointerAddressSpace(); 10942 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10943 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10944 } 10945 default: 10946 break; 10947 } 10948 10949 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10950 } 10951 10952 const TargetRegisterClass * 10953 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10954 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10955 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10956 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10957 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10958 : &AMDGPU::SReg_32RegClass; 10959 if (!TRI->isSGPRClass(RC) && !isDivergent) 10960 return TRI->getEquivalentSGPRClass(RC); 10961 else if (TRI->isSGPRClass(RC) && isDivergent) 10962 return TRI->getEquivalentVGPRClass(RC); 10963 10964 return RC; 10965 } 10966 10967 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) { 10968 if (!Visited.insert(V).second) 10969 return false; 10970 bool Result = false; 10971 for (auto U : V->users()) { 10972 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10973 if (V == U->getOperand(1)) { 10974 switch (Intrinsic->getIntrinsicID()) { 10975 default: 10976 Result = false; 10977 break; 10978 case Intrinsic::amdgcn_if_break: 10979 case Intrinsic::amdgcn_if: 10980 case Intrinsic::amdgcn_else: 10981 Result = true; 10982 break; 10983 } 10984 } 10985 if (V == U->getOperand(0)) { 10986 switch (Intrinsic->getIntrinsicID()) { 10987 default: 10988 Result = false; 10989 break; 10990 case Intrinsic::amdgcn_end_cf: 10991 case Intrinsic::amdgcn_loop: 10992 Result = true; 10993 break; 10994 } 10995 } 10996 } else { 10997 Result = hasCFUser(U, Visited); 10998 } 10999 if (Result) 11000 break; 11001 } 11002 return Result; 11003 } 11004 11005 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11006 const Value *V) const { 11007 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 11008 switch (Intrinsic->getIntrinsicID()) { 11009 default: 11010 return false; 11011 case Intrinsic::amdgcn_if_break: 11012 return true; 11013 } 11014 } 11015 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 11016 if (const IntrinsicInst *Intrinsic = 11017 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 11018 switch (Intrinsic->getIntrinsicID()) { 11019 default: 11020 return false; 11021 case Intrinsic::amdgcn_if: 11022 case Intrinsic::amdgcn_else: { 11023 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 11024 if (Indices.size() == 1 && Indices[0] == 1) { 11025 return true; 11026 } 11027 } 11028 } 11029 } 11030 } 11031 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11032 if (isa<InlineAsm>(CI->getCalledValue())) { 11033 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11034 ImmutableCallSite CS(CI); 11035 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11036 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 11037 for (auto &TC : TargetConstraints) { 11038 if (TC.Type == InlineAsm::isOutput) { 11039 ComputeConstraintToUse(TC, SDValue()); 11040 unsigned AssignedReg; 11041 const TargetRegisterClass *RC; 11042 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11043 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11044 if (RC) { 11045 MachineRegisterInfo &MRI = MF.getRegInfo(); 11046 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11047 return true; 11048 else if (SIRI->isSGPRClass(RC)) 11049 return true; 11050 } 11051 } 11052 } 11053 } 11054 } 11055 SmallPtrSet<const Value *, 16> Visited; 11056 return hasCFUser(V, Visited); 11057 } 11058