1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #if defined(_MSC_VER) || defined(__MINGW32__) 15 // Provide M_PI. 16 #define _USE_MATH_DEFINES 17 #endif 18 19 #include "SIISelLowering.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "SIDefines.h" 24 #include "SIInstrInfo.h" 25 #include "SIMachineFunctionInfo.h" 26 #include "SIRegisterInfo.h" 27 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 28 #include "Utils/AMDGPUBaseInfo.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/BitVector.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/CodeGen/Analysis.h" 39 #include "llvm/CodeGen/CallingConvLower.h" 40 #include "llvm/CodeGen/DAGCombine.h" 41 #include "llvm/CodeGen/ISDOpcodes.h" 42 #include "llvm/CodeGen/MachineBasicBlock.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineInstr.h" 46 #include "llvm/CodeGen/MachineInstrBuilder.h" 47 #include "llvm/CodeGen/MachineMemOperand.h" 48 #include "llvm/CodeGen/MachineModuleInfo.h" 49 #include "llvm/CodeGen/MachineOperand.h" 50 #include "llvm/CodeGen/MachineRegisterInfo.h" 51 #include "llvm/CodeGen/SelectionDAG.h" 52 #include "llvm/CodeGen/SelectionDAGNodes.h" 53 #include "llvm/CodeGen/TargetCallingConv.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/ValueTypes.h" 56 #include "llvm/IR/Constants.h" 57 #include "llvm/IR/DataLayout.h" 58 #include "llvm/IR/DebugLoc.h" 59 #include "llvm/IR/DerivedTypes.h" 60 #include "llvm/IR/DiagnosticInfo.h" 61 #include "llvm/IR/Function.h" 62 #include "llvm/IR/GlobalValue.h" 63 #include "llvm/IR/InstrTypes.h" 64 #include "llvm/IR/Instruction.h" 65 #include "llvm/IR/Instructions.h" 66 #include "llvm/IR/IntrinsicInst.h" 67 #include "llvm/IR/Type.h" 68 #include "llvm/Support/Casting.h" 69 #include "llvm/Support/CodeGen.h" 70 #include "llvm/Support/CommandLine.h" 71 #include "llvm/Support/Compiler.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/KnownBits.h" 74 #include "llvm/Support/MachineValueType.h" 75 #include "llvm/Support/MathExtras.h" 76 #include "llvm/Target/TargetOptions.h" 77 #include <cassert> 78 #include <cmath> 79 #include <cstdint> 80 #include <iterator> 81 #include <tuple> 82 #include <utility> 83 #include <vector> 84 85 using namespace llvm; 86 87 #define DEBUG_TYPE "si-lower" 88 89 STATISTIC(NumTailCalls, "Number of tail calls"); 90 91 static cl::opt<bool> EnableVGPRIndexMode( 92 "amdgpu-vgpr-index-mode", 93 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 94 cl::init(false)); 95 96 static cl::opt<bool> DisableLoopAlignment( 97 "amdgpu-disable-loop-alignment", 98 cl::desc("Do not align and prefetch loops"), 99 cl::init(false)); 100 101 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 102 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 103 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 104 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 105 return AMDGPU::SGPR0 + Reg; 106 } 107 } 108 llvm_unreachable("Cannot allocate sgpr"); 109 } 110 111 SITargetLowering::SITargetLowering(const TargetMachine &TM, 112 const GCNSubtarget &STI) 113 : AMDGPUTargetLowering(TM, STI), 114 Subtarget(&STI) { 115 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 116 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 117 118 addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass); 119 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 120 121 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 122 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 123 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 124 125 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 126 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 127 128 addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass); 129 addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass); 130 131 addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass); 132 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 133 134 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 135 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 136 137 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 138 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 139 140 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 141 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 142 143 if (Subtarget->has16BitInsts()) { 144 addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass); 145 addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass); 146 147 // Unless there are also VOP3P operations, not operations are really legal. 148 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass); 149 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass); 150 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 151 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 152 } 153 154 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::v4i32, MVT::v4i16, Expand); 182 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 183 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 184 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 185 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 186 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 187 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 188 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 189 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 190 191 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 192 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 193 194 setOperationAction(ISD::SELECT, MVT::i1, Promote); 195 setOperationAction(ISD::SELECT, MVT::i64, Custom); 196 setOperationAction(ISD::SELECT, MVT::f64, Promote); 197 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 198 199 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 200 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 201 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 202 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 203 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 204 205 setOperationAction(ISD::SETCC, MVT::i1, Promote); 206 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 207 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 208 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 209 210 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 211 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 212 213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 219 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 220 221 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 222 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 223 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 224 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 225 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 226 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 227 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 228 229 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 230 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 231 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 232 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 233 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 234 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 235 236 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 237 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 238 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 239 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 240 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 241 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 242 243 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 244 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 245 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 246 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 247 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 248 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 249 250 setOperationAction(ISD::UADDO, MVT::i32, Legal); 251 setOperationAction(ISD::USUBO, MVT::i32, Legal); 252 253 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 254 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 255 256 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 257 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 258 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 259 260 #if 0 261 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 262 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 263 #endif 264 265 // We only support LOAD/STORE and vector manipulation ops for vectors 266 // with > 4 elements. 267 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 268 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 269 MVT::v32i32, MVT::v32f32 }) { 270 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 271 switch (Op) { 272 case ISD::LOAD: 273 case ISD::STORE: 274 case ISD::BUILD_VECTOR: 275 case ISD::BITCAST: 276 case ISD::EXTRACT_VECTOR_ELT: 277 case ISD::INSERT_VECTOR_ELT: 278 case ISD::INSERT_SUBVECTOR: 279 case ISD::EXTRACT_SUBVECTOR: 280 case ISD::SCALAR_TO_VECTOR: 281 break; 282 case ISD::CONCAT_VECTORS: 283 setOperationAction(Op, VT, Custom); 284 break; 285 default: 286 setOperationAction(Op, VT, Expand); 287 break; 288 } 289 } 290 } 291 292 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 293 294 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 295 // is expanded to avoid having two separate loops in case the index is a VGPR. 296 297 // Most operations are naturally 32-bit vector operations. We only support 298 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 299 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 300 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 301 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 302 303 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 304 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 305 306 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 307 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 308 309 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 310 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 311 } 312 313 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 314 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 315 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 316 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 317 318 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 319 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 320 321 // Avoid stack access for these. 322 // TODO: Generalize to more vector types. 323 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 324 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 325 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 326 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 327 328 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 330 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 331 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 333 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 336 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 337 338 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 339 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 340 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 341 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 342 343 // Deal with vec3 vector operations when widened to vec4. 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 348 349 // Deal with vec5 vector operations when widened to vec8. 350 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 351 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 352 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 353 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 354 355 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 356 // and output demarshalling 357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 359 360 // We can't return success/failure, only the old value, 361 // let LLVM add the comparison 362 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 363 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 364 365 if (Subtarget->hasFlatAddressSpace()) { 366 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 367 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 368 } 369 370 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 371 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 372 373 // On SI this is s_memtime and s_memrealtime on VI. 374 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 375 setOperationAction(ISD::TRAP, MVT::Other, Custom); 376 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 377 378 if (Subtarget->has16BitInsts()) { 379 setOperationAction(ISD::FLOG, MVT::f16, Custom); 380 setOperationAction(ISD::FEXP, MVT::f16, Custom); 381 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 382 } 383 384 // v_mad_f32 does not support denormals according to some sources. 385 if (!Subtarget->hasFP32Denormals()) 386 setOperationAction(ISD::FMAD, MVT::f32, Legal); 387 388 if (!Subtarget->hasBFI()) { 389 // fcopysign can be done in a single instruction with BFI. 390 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 391 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 392 } 393 394 if (!Subtarget->hasBCNT(32)) 395 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 396 397 if (!Subtarget->hasBCNT(64)) 398 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 399 400 if (Subtarget->hasFFBH()) 401 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 402 403 if (Subtarget->hasFFBL()) 404 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 405 406 // We only really have 32-bit BFE instructions (and 16-bit on VI). 407 // 408 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 409 // effort to match them now. We want this to be false for i64 cases when the 410 // extraction isn't restricted to the upper or lower half. Ideally we would 411 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 412 // span the midpoint are probably relatively rare, so don't worry about them 413 // for now. 414 if (Subtarget->hasBFE()) 415 setHasExtractBitsInsn(true); 416 417 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 418 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 419 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 420 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 421 422 423 // These are really only legal for ieee_mode functions. We should be avoiding 424 // them for functions that don't have ieee_mode enabled, so just say they are 425 // legal. 426 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 427 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 428 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 429 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 430 431 432 if (Subtarget->haveRoundOpsF64()) { 433 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 434 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 435 setOperationAction(ISD::FRINT, MVT::f64, Legal); 436 } else { 437 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 438 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 439 setOperationAction(ISD::FRINT, MVT::f64, Custom); 440 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 441 } 442 443 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 444 445 setOperationAction(ISD::FSIN, MVT::f32, Custom); 446 setOperationAction(ISD::FCOS, MVT::f32, Custom); 447 setOperationAction(ISD::FDIV, MVT::f32, Custom); 448 setOperationAction(ISD::FDIV, MVT::f64, Custom); 449 450 if (Subtarget->has16BitInsts()) { 451 setOperationAction(ISD::Constant, MVT::i16, Legal); 452 453 setOperationAction(ISD::SMIN, MVT::i16, Legal); 454 setOperationAction(ISD::SMAX, MVT::i16, Legal); 455 456 setOperationAction(ISD::UMIN, MVT::i16, Legal); 457 setOperationAction(ISD::UMAX, MVT::i16, Legal); 458 459 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 460 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 461 462 setOperationAction(ISD::ROTR, MVT::i16, Promote); 463 setOperationAction(ISD::ROTL, MVT::i16, Promote); 464 465 setOperationAction(ISD::SDIV, MVT::i16, Promote); 466 setOperationAction(ISD::UDIV, MVT::i16, Promote); 467 setOperationAction(ISD::SREM, MVT::i16, Promote); 468 setOperationAction(ISD::UREM, MVT::i16, Promote); 469 470 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 471 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 472 473 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 475 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 477 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 478 479 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 480 481 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 482 483 setOperationAction(ISD::LOAD, MVT::i16, Custom); 484 485 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 486 487 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 488 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 489 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 490 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 491 492 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 493 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 494 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 495 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 496 497 // F16 - Constant Actions. 498 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 499 500 // F16 - Load/Store Actions. 501 setOperationAction(ISD::LOAD, MVT::f16, Promote); 502 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 503 setOperationAction(ISD::STORE, MVT::f16, Promote); 504 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 505 506 // F16 - VOP1 Actions. 507 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 508 setOperationAction(ISD::FCOS, MVT::f16, Promote); 509 setOperationAction(ISD::FSIN, MVT::f16, Promote); 510 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 511 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 512 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 513 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 514 setOperationAction(ISD::FROUND, MVT::f16, Custom); 515 516 // F16 - VOP2 Actions. 517 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 518 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 519 520 setOperationAction(ISD::FDIV, MVT::f16, Custom); 521 522 // F16 - VOP3 Actions. 523 setOperationAction(ISD::FMA, MVT::f16, Legal); 524 if (!Subtarget->hasFP16Denormals() && STI.hasMadF16()) 525 setOperationAction(ISD::FMAD, MVT::f16, Legal); 526 527 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 528 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 529 switch (Op) { 530 case ISD::LOAD: 531 case ISD::STORE: 532 case ISD::BUILD_VECTOR: 533 case ISD::BITCAST: 534 case ISD::EXTRACT_VECTOR_ELT: 535 case ISD::INSERT_VECTOR_ELT: 536 case ISD::INSERT_SUBVECTOR: 537 case ISD::EXTRACT_SUBVECTOR: 538 case ISD::SCALAR_TO_VECTOR: 539 break; 540 case ISD::CONCAT_VECTORS: 541 setOperationAction(Op, VT, Custom); 542 break; 543 default: 544 setOperationAction(Op, VT, Expand); 545 break; 546 } 547 } 548 } 549 550 // XXX - Do these do anything? Vector constants turn into build_vector. 551 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 552 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 553 554 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 555 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 556 557 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 558 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 559 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 560 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 561 562 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 563 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 564 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 565 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 566 567 setOperationAction(ISD::AND, MVT::v2i16, Promote); 568 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 569 setOperationAction(ISD::OR, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 571 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 572 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 573 574 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 575 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 576 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 577 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 578 579 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 580 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 581 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 582 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 583 584 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 585 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 586 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 587 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 588 589 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 590 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 591 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 592 593 if (!Subtarget->hasVOP3PInsts()) { 594 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 595 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 596 } 597 598 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 599 // This isn't really legal, but this avoids the legalizer unrolling it (and 600 // allows matching fneg (fabs x) patterns) 601 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 602 603 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 604 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 605 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 606 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 607 608 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 609 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 610 611 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 612 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 613 } 614 615 if (Subtarget->hasVOP3PInsts()) { 616 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 617 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 618 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 619 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 620 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 621 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 622 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 623 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 624 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 625 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 626 627 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 628 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 629 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 630 631 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 632 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 633 634 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 635 636 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 637 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 638 639 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 640 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 641 642 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 643 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 644 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 645 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 646 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 647 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 648 649 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 650 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 651 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 652 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 653 654 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 655 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 656 657 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 658 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 659 660 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 661 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 662 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 663 664 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 665 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 666 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 667 } 668 669 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 670 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 671 672 if (Subtarget->has16BitInsts()) { 673 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 674 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 675 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 676 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 677 } else { 678 // Legalization hack. 679 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 680 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 681 682 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 683 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 684 } 685 686 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 687 setOperationAction(ISD::SELECT, VT, Custom); 688 } 689 690 setTargetDAGCombine(ISD::ADD); 691 setTargetDAGCombine(ISD::ADDCARRY); 692 setTargetDAGCombine(ISD::SUB); 693 setTargetDAGCombine(ISD::SUBCARRY); 694 setTargetDAGCombine(ISD::FADD); 695 setTargetDAGCombine(ISD::FSUB); 696 setTargetDAGCombine(ISD::FMINNUM); 697 setTargetDAGCombine(ISD::FMAXNUM); 698 setTargetDAGCombine(ISD::FMINNUM_IEEE); 699 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 700 setTargetDAGCombine(ISD::FMA); 701 setTargetDAGCombine(ISD::SMIN); 702 setTargetDAGCombine(ISD::SMAX); 703 setTargetDAGCombine(ISD::UMIN); 704 setTargetDAGCombine(ISD::UMAX); 705 setTargetDAGCombine(ISD::SETCC); 706 setTargetDAGCombine(ISD::AND); 707 setTargetDAGCombine(ISD::OR); 708 setTargetDAGCombine(ISD::XOR); 709 setTargetDAGCombine(ISD::SINT_TO_FP); 710 setTargetDAGCombine(ISD::UINT_TO_FP); 711 setTargetDAGCombine(ISD::FCANONICALIZE); 712 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 713 setTargetDAGCombine(ISD::ZERO_EXTEND); 714 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 715 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 716 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 717 718 // All memory operations. Some folding on the pointer operand is done to help 719 // matching the constant offsets in the addressing modes. 720 setTargetDAGCombine(ISD::LOAD); 721 setTargetDAGCombine(ISD::STORE); 722 setTargetDAGCombine(ISD::ATOMIC_LOAD); 723 setTargetDAGCombine(ISD::ATOMIC_STORE); 724 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 725 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 726 setTargetDAGCombine(ISD::ATOMIC_SWAP); 727 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 728 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 729 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 730 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 731 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 732 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 733 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 734 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 735 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 736 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 737 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 738 739 setSchedulingPreference(Sched::RegPressure); 740 } 741 742 const GCNSubtarget *SITargetLowering::getSubtarget() const { 743 return Subtarget; 744 } 745 746 //===----------------------------------------------------------------------===// 747 // TargetLowering queries 748 //===----------------------------------------------------------------------===// 749 750 // v_mad_mix* support a conversion from f16 to f32. 751 // 752 // There is only one special case when denormals are enabled we don't currently, 753 // where this is OK to use. 754 bool SITargetLowering::isFPExtFoldable(unsigned Opcode, 755 EVT DestVT, EVT SrcVT) const { 756 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 757 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 758 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() && 759 SrcVT.getScalarType() == MVT::f16; 760 } 761 762 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 763 // SI has some legal vector types, but no legal vector operations. Say no 764 // shuffles are legal in order to prefer scalarizing some vector operations. 765 return false; 766 } 767 768 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 769 CallingConv::ID CC, 770 EVT VT) const { 771 if (CC == CallingConv::AMDGPU_KERNEL) 772 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 773 774 if (VT.isVector()) { 775 EVT ScalarVT = VT.getScalarType(); 776 unsigned Size = ScalarVT.getSizeInBits(); 777 if (Size == 32) 778 return ScalarVT.getSimpleVT(); 779 780 if (Size > 32) 781 return MVT::i32; 782 783 if (Size == 16 && Subtarget->has16BitInsts()) 784 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 785 } else if (VT.getSizeInBits() > 32) 786 return MVT::i32; 787 788 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 789 } 790 791 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 792 CallingConv::ID CC, 793 EVT VT) const { 794 if (CC == CallingConv::AMDGPU_KERNEL) 795 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 796 797 if (VT.isVector()) { 798 unsigned NumElts = VT.getVectorNumElements(); 799 EVT ScalarVT = VT.getScalarType(); 800 unsigned Size = ScalarVT.getSizeInBits(); 801 802 if (Size == 32) 803 return NumElts; 804 805 if (Size > 32) 806 return NumElts * ((Size + 31) / 32); 807 808 if (Size == 16 && Subtarget->has16BitInsts()) 809 return (NumElts + 1) / 2; 810 } else if (VT.getSizeInBits() > 32) 811 return (VT.getSizeInBits() + 31) / 32; 812 813 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 814 } 815 816 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 817 LLVMContext &Context, CallingConv::ID CC, 818 EVT VT, EVT &IntermediateVT, 819 unsigned &NumIntermediates, MVT &RegisterVT) const { 820 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 821 unsigned NumElts = VT.getVectorNumElements(); 822 EVT ScalarVT = VT.getScalarType(); 823 unsigned Size = ScalarVT.getSizeInBits(); 824 if (Size == 32) { 825 RegisterVT = ScalarVT.getSimpleVT(); 826 IntermediateVT = RegisterVT; 827 NumIntermediates = NumElts; 828 return NumIntermediates; 829 } 830 831 if (Size > 32) { 832 RegisterVT = MVT::i32; 833 IntermediateVT = RegisterVT; 834 NumIntermediates = NumElts * ((Size + 31) / 32); 835 return NumIntermediates; 836 } 837 838 // FIXME: We should fix the ABI to be the same on targets without 16-bit 839 // support, but unless we can properly handle 3-vectors, it will be still be 840 // inconsistent. 841 if (Size == 16 && Subtarget->has16BitInsts()) { 842 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 843 IntermediateVT = RegisterVT; 844 NumIntermediates = (NumElts + 1) / 2; 845 return NumIntermediates; 846 } 847 } 848 849 return TargetLowering::getVectorTypeBreakdownForCallingConv( 850 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 851 } 852 853 static MVT memVTFromAggregate(Type *Ty) { 854 // Only limited forms of aggregate type currently expected. 855 assert(Ty->isStructTy() && "Expected struct type"); 856 857 858 Type *ElementType = nullptr; 859 unsigned NumElts; 860 if (Ty->getContainedType(0)->isVectorTy()) { 861 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 862 ElementType = VecComponent->getElementType(); 863 NumElts = VecComponent->getNumElements(); 864 } else { 865 ElementType = Ty->getContainedType(0); 866 NumElts = 1; 867 } 868 869 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 870 871 // Calculate the size of the memVT type from the aggregate 872 unsigned Pow2Elts = 0; 873 unsigned ElementSize; 874 switch (ElementType->getTypeID()) { 875 default: 876 llvm_unreachable("Unknown type!"); 877 case Type::IntegerTyID: 878 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 879 break; 880 case Type::HalfTyID: 881 ElementSize = 16; 882 break; 883 case Type::FloatTyID: 884 ElementSize = 32; 885 break; 886 } 887 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 888 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 889 890 return MVT::getVectorVT(MVT::getVT(ElementType, false), 891 Pow2Elts); 892 } 893 894 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 895 const CallInst &CI, 896 MachineFunction &MF, 897 unsigned IntrID) const { 898 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 899 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 900 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 901 (Intrinsic::ID)IntrID); 902 if (Attr.hasFnAttribute(Attribute::ReadNone)) 903 return false; 904 905 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 906 907 if (RsrcIntr->IsImage) { 908 Info.ptrVal = MFI->getImagePSV( 909 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 910 CI.getArgOperand(RsrcIntr->RsrcArg)); 911 Info.align = 0; 912 } else { 913 Info.ptrVal = MFI->getBufferPSV( 914 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 915 CI.getArgOperand(RsrcIntr->RsrcArg)); 916 } 917 918 Info.flags = MachineMemOperand::MODereferenceable; 919 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 920 Info.opc = ISD::INTRINSIC_W_CHAIN; 921 Info.memVT = MVT::getVT(CI.getType(), true); 922 if (Info.memVT == MVT::Other) { 923 // Some intrinsics return an aggregate type - special case to work out 924 // the correct memVT 925 Info.memVT = memVTFromAggregate(CI.getType()); 926 } 927 Info.flags |= MachineMemOperand::MOLoad; 928 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 929 Info.opc = ISD::INTRINSIC_VOID; 930 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 931 Info.flags |= MachineMemOperand::MOStore; 932 } else { 933 // Atomic 934 Info.opc = ISD::INTRINSIC_W_CHAIN; 935 Info.memVT = MVT::getVT(CI.getType()); 936 Info.flags = MachineMemOperand::MOLoad | 937 MachineMemOperand::MOStore | 938 MachineMemOperand::MODereferenceable; 939 940 // XXX - Should this be volatile without known ordering? 941 Info.flags |= MachineMemOperand::MOVolatile; 942 } 943 return true; 944 } 945 946 switch (IntrID) { 947 case Intrinsic::amdgcn_atomic_inc: 948 case Intrinsic::amdgcn_atomic_dec: 949 case Intrinsic::amdgcn_ds_ordered_add: 950 case Intrinsic::amdgcn_ds_ordered_swap: 951 case Intrinsic::amdgcn_ds_fadd: 952 case Intrinsic::amdgcn_ds_fmin: 953 case Intrinsic::amdgcn_ds_fmax: { 954 Info.opc = ISD::INTRINSIC_W_CHAIN; 955 Info.memVT = MVT::getVT(CI.getType()); 956 Info.ptrVal = CI.getOperand(0); 957 Info.align = 0; 958 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 959 960 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 961 if (!Vol->isZero()) 962 Info.flags |= MachineMemOperand::MOVolatile; 963 964 return true; 965 } 966 case Intrinsic::amdgcn_buffer_atomic_fadd: { 967 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 968 969 Info.opc = ISD::INTRINSIC_VOID; 970 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 971 Info.ptrVal = MFI->getBufferPSV( 972 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 973 CI.getArgOperand(1)); 974 Info.align = 0; 975 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 976 977 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 978 if (!Vol || !Vol->isZero()) 979 Info.flags |= MachineMemOperand::MOVolatile; 980 981 return true; 982 } 983 case Intrinsic::amdgcn_global_atomic_fadd: { 984 Info.opc = ISD::INTRINSIC_VOID; 985 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 986 ->getPointerElementType()); 987 Info.ptrVal = CI.getOperand(0); 988 Info.align = 0; 989 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 990 991 return true; 992 } 993 case Intrinsic::amdgcn_ds_append: 994 case Intrinsic::amdgcn_ds_consume: { 995 Info.opc = ISD::INTRINSIC_W_CHAIN; 996 Info.memVT = MVT::getVT(CI.getType()); 997 Info.ptrVal = CI.getOperand(0); 998 Info.align = 0; 999 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1000 1001 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1002 if (!Vol->isZero()) 1003 Info.flags |= MachineMemOperand::MOVolatile; 1004 1005 return true; 1006 } 1007 case Intrinsic::amdgcn_ds_gws_init: 1008 case Intrinsic::amdgcn_ds_gws_barrier: 1009 case Intrinsic::amdgcn_ds_gws_sema_v: 1010 case Intrinsic::amdgcn_ds_gws_sema_br: 1011 case Intrinsic::amdgcn_ds_gws_sema_p: 1012 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1013 Info.opc = ISD::INTRINSIC_VOID; 1014 1015 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1016 Info.ptrVal = 1017 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1018 1019 // This is an abstract access, but we need to specify a type and size. 1020 Info.memVT = MVT::i32; 1021 Info.size = 4; 1022 Info.align = 4; 1023 1024 Info.flags = MachineMemOperand::MOStore; 1025 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1026 Info.flags = MachineMemOperand::MOLoad; 1027 return true; 1028 } 1029 default: 1030 return false; 1031 } 1032 } 1033 1034 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1035 SmallVectorImpl<Value*> &Ops, 1036 Type *&AccessTy) const { 1037 switch (II->getIntrinsicID()) { 1038 case Intrinsic::amdgcn_atomic_inc: 1039 case Intrinsic::amdgcn_atomic_dec: 1040 case Intrinsic::amdgcn_ds_ordered_add: 1041 case Intrinsic::amdgcn_ds_ordered_swap: 1042 case Intrinsic::amdgcn_ds_fadd: 1043 case Intrinsic::amdgcn_ds_fmin: 1044 case Intrinsic::amdgcn_ds_fmax: { 1045 Value *Ptr = II->getArgOperand(0); 1046 AccessTy = II->getType(); 1047 Ops.push_back(Ptr); 1048 return true; 1049 } 1050 default: 1051 return false; 1052 } 1053 } 1054 1055 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1056 if (!Subtarget->hasFlatInstOffsets()) { 1057 // Flat instructions do not have offsets, and only have the register 1058 // address. 1059 return AM.BaseOffs == 0 && AM.Scale == 0; 1060 } 1061 1062 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 1063 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 1064 1065 // GFX10 shrinked signed offset to 12 bits. When using regular flat 1066 // instructions, the sign bit is also ignored and is treated as 11-bit 1067 // unsigned offset. 1068 1069 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 1070 return isUInt<11>(AM.BaseOffs) && AM.Scale == 0; 1071 1072 // Just r + i 1073 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 1074 } 1075 1076 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1077 if (Subtarget->hasFlatGlobalInsts()) 1078 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 1079 1080 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1081 // Assume the we will use FLAT for all global memory accesses 1082 // on VI. 1083 // FIXME: This assumption is currently wrong. On VI we still use 1084 // MUBUF instructions for the r + i addressing mode. As currently 1085 // implemented, the MUBUF instructions only work on buffer < 4GB. 1086 // It may be possible to support > 4GB buffers with MUBUF instructions, 1087 // by setting the stride value in the resource descriptor which would 1088 // increase the size limit to (stride * 4GB). However, this is risky, 1089 // because it has never been validated. 1090 return isLegalFlatAddressingMode(AM); 1091 } 1092 1093 return isLegalMUBUFAddressingMode(AM); 1094 } 1095 1096 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1097 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1098 // additionally can do r + r + i with addr64. 32-bit has more addressing 1099 // mode options. Depending on the resource constant, it can also do 1100 // (i64 r0) + (i32 r1) * (i14 i). 1101 // 1102 // Private arrays end up using a scratch buffer most of the time, so also 1103 // assume those use MUBUF instructions. Scratch loads / stores are currently 1104 // implemented as mubuf instructions with offen bit set, so slightly 1105 // different than the normal addr64. 1106 if (!isUInt<12>(AM.BaseOffs)) 1107 return false; 1108 1109 // FIXME: Since we can split immediate into soffset and immediate offset, 1110 // would it make sense to allow any immediate? 1111 1112 switch (AM.Scale) { 1113 case 0: // r + i or just i, depending on HasBaseReg. 1114 return true; 1115 case 1: 1116 return true; // We have r + r or r + i. 1117 case 2: 1118 if (AM.HasBaseReg) { 1119 // Reject 2 * r + r. 1120 return false; 1121 } 1122 1123 // Allow 2 * r as r + r 1124 // Or 2 * r + i is allowed as r + r + i. 1125 return true; 1126 default: // Don't allow n * r 1127 return false; 1128 } 1129 } 1130 1131 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1132 const AddrMode &AM, Type *Ty, 1133 unsigned AS, Instruction *I) const { 1134 // No global is ever allowed as a base. 1135 if (AM.BaseGV) 1136 return false; 1137 1138 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1139 return isLegalGlobalAddressingMode(AM); 1140 1141 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1142 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1143 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1144 // If the offset isn't a multiple of 4, it probably isn't going to be 1145 // correctly aligned. 1146 // FIXME: Can we get the real alignment here? 1147 if (AM.BaseOffs % 4 != 0) 1148 return isLegalMUBUFAddressingMode(AM); 1149 1150 // There are no SMRD extloads, so if we have to do a small type access we 1151 // will use a MUBUF load. 1152 // FIXME?: We also need to do this if unaligned, but we don't know the 1153 // alignment here. 1154 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1155 return isLegalGlobalAddressingMode(AM); 1156 1157 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1158 // SMRD instructions have an 8-bit, dword offset on SI. 1159 if (!isUInt<8>(AM.BaseOffs / 4)) 1160 return false; 1161 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1162 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1163 // in 8-bits, it can use a smaller encoding. 1164 if (!isUInt<32>(AM.BaseOffs / 4)) 1165 return false; 1166 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1167 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1168 if (!isUInt<20>(AM.BaseOffs)) 1169 return false; 1170 } else 1171 llvm_unreachable("unhandled generation"); 1172 1173 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1174 return true; 1175 1176 if (AM.Scale == 1 && AM.HasBaseReg) 1177 return true; 1178 1179 return false; 1180 1181 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1182 return isLegalMUBUFAddressingMode(AM); 1183 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1184 AS == AMDGPUAS::REGION_ADDRESS) { 1185 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1186 // field. 1187 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1188 // an 8-bit dword offset but we don't know the alignment here. 1189 if (!isUInt<16>(AM.BaseOffs)) 1190 return false; 1191 1192 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1193 return true; 1194 1195 if (AM.Scale == 1 && AM.HasBaseReg) 1196 return true; 1197 1198 return false; 1199 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1200 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1201 // For an unknown address space, this usually means that this is for some 1202 // reason being used for pure arithmetic, and not based on some addressing 1203 // computation. We don't have instructions that compute pointers with any 1204 // addressing modes, so treat them as having no offset like flat 1205 // instructions. 1206 return isLegalFlatAddressingMode(AM); 1207 } else { 1208 llvm_unreachable("unhandled address space"); 1209 } 1210 } 1211 1212 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1213 const SelectionDAG &DAG) const { 1214 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1215 return (MemVT.getSizeInBits() <= 4 * 32); 1216 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1217 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1218 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1219 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1220 return (MemVT.getSizeInBits() <= 2 * 32); 1221 } 1222 return true; 1223 } 1224 1225 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1226 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1227 bool *IsFast) const { 1228 if (IsFast) 1229 *IsFast = false; 1230 1231 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1232 // which isn't a simple VT. 1233 // Until MVT is extended to handle this, simply check for the size and 1234 // rely on the condition below: allow accesses if the size is a multiple of 4. 1235 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1236 VT.getStoreSize() > 16)) { 1237 return false; 1238 } 1239 1240 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1241 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1242 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1243 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1244 // with adjacent offsets. 1245 bool AlignedBy4 = (Align % 4 == 0); 1246 if (IsFast) 1247 *IsFast = AlignedBy4; 1248 1249 return AlignedBy4; 1250 } 1251 1252 // FIXME: We have to be conservative here and assume that flat operations 1253 // will access scratch. If we had access to the IR function, then we 1254 // could determine if any private memory was used in the function. 1255 if (!Subtarget->hasUnalignedScratchAccess() && 1256 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1257 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1258 bool AlignedBy4 = Align >= 4; 1259 if (IsFast) 1260 *IsFast = AlignedBy4; 1261 1262 return AlignedBy4; 1263 } 1264 1265 if (Subtarget->hasUnalignedBufferAccess()) { 1266 // If we have an uniform constant load, it still requires using a slow 1267 // buffer instruction if unaligned. 1268 if (IsFast) { 1269 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1270 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1271 (Align % 4 == 0) : true; 1272 } 1273 1274 return true; 1275 } 1276 1277 // Smaller than dword value must be aligned. 1278 if (VT.bitsLT(MVT::i32)) 1279 return false; 1280 1281 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1282 // byte-address are ignored, thus forcing Dword alignment. 1283 // This applies to private, global, and constant memory. 1284 if (IsFast) 1285 *IsFast = true; 1286 1287 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 1288 } 1289 1290 EVT SITargetLowering::getOptimalMemOpType( 1291 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1292 bool ZeroMemset, bool MemcpyStrSrc, 1293 const AttributeList &FuncAttributes) const { 1294 // FIXME: Should account for address space here. 1295 1296 // The default fallback uses the private pointer size as a guess for a type to 1297 // use. Make sure we switch these to 64-bit accesses. 1298 1299 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1300 return MVT::v4i32; 1301 1302 if (Size >= 8 && DstAlign >= 4) 1303 return MVT::v2i32; 1304 1305 // Use the default. 1306 return MVT::Other; 1307 } 1308 1309 static bool isFlatGlobalAddrSpace(unsigned AS) { 1310 return AS == AMDGPUAS::GLOBAL_ADDRESS || 1311 AS == AMDGPUAS::FLAT_ADDRESS || 1312 AS == AMDGPUAS::CONSTANT_ADDRESS || 1313 AS > AMDGPUAS::MAX_AMDGPU_ADDRESS; 1314 } 1315 1316 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1317 unsigned DestAS) const { 1318 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1319 } 1320 1321 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1322 const MemSDNode *MemNode = cast<MemSDNode>(N); 1323 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1324 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1325 return I && I->getMetadata("amdgpu.noclobber"); 1326 } 1327 1328 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1329 unsigned DestAS) const { 1330 // Flat -> private/local is a simple truncate. 1331 // Flat -> global is no-op 1332 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1333 return true; 1334 1335 return isNoopAddrSpaceCast(SrcAS, DestAS); 1336 } 1337 1338 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1339 const MemSDNode *MemNode = cast<MemSDNode>(N); 1340 1341 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1342 } 1343 1344 TargetLoweringBase::LegalizeTypeAction 1345 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1346 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1347 return TypeSplitVector; 1348 1349 return TargetLoweringBase::getPreferredVectorAction(VT); 1350 } 1351 1352 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1353 Type *Ty) const { 1354 // FIXME: Could be smarter if called for vector constants. 1355 return true; 1356 } 1357 1358 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1359 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1360 switch (Op) { 1361 case ISD::LOAD: 1362 case ISD::STORE: 1363 1364 // These operations are done with 32-bit instructions anyway. 1365 case ISD::AND: 1366 case ISD::OR: 1367 case ISD::XOR: 1368 case ISD::SELECT: 1369 // TODO: Extensions? 1370 return true; 1371 default: 1372 return false; 1373 } 1374 } 1375 1376 // SimplifySetCC uses this function to determine whether or not it should 1377 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1378 if (VT == MVT::i1 && Op == ISD::SETCC) 1379 return false; 1380 1381 return TargetLowering::isTypeDesirableForOp(Op, VT); 1382 } 1383 1384 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1385 const SDLoc &SL, 1386 SDValue Chain, 1387 uint64_t Offset) const { 1388 const DataLayout &DL = DAG.getDataLayout(); 1389 MachineFunction &MF = DAG.getMachineFunction(); 1390 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1391 1392 const ArgDescriptor *InputPtrReg; 1393 const TargetRegisterClass *RC; 1394 1395 std::tie(InputPtrReg, RC) 1396 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1397 1398 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1399 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1400 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1401 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1402 1403 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1404 } 1405 1406 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1407 const SDLoc &SL) const { 1408 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1409 FIRST_IMPLICIT); 1410 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1411 } 1412 1413 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1414 const SDLoc &SL, SDValue Val, 1415 bool Signed, 1416 const ISD::InputArg *Arg) const { 1417 // First, if it is a widened vector, narrow it. 1418 if (VT.isVector() && 1419 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1420 EVT NarrowedVT = 1421 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1422 VT.getVectorNumElements()); 1423 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1424 DAG.getConstant(0, SL, MVT::i32)); 1425 } 1426 1427 // Then convert the vector elements or scalar value. 1428 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1429 VT.bitsLT(MemVT)) { 1430 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1431 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1432 } 1433 1434 if (MemVT.isFloatingPoint()) 1435 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1436 else if (Signed) 1437 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1438 else 1439 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1440 1441 return Val; 1442 } 1443 1444 SDValue SITargetLowering::lowerKernargMemParameter( 1445 SelectionDAG &DAG, EVT VT, EVT MemVT, 1446 const SDLoc &SL, SDValue Chain, 1447 uint64_t Offset, unsigned Align, bool Signed, 1448 const ISD::InputArg *Arg) const { 1449 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1450 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1451 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1452 1453 // Try to avoid using an extload by loading earlier than the argument address, 1454 // and extracting the relevant bits. The load should hopefully be merged with 1455 // the previous argument. 1456 if (MemVT.getStoreSize() < 4 && Align < 4) { 1457 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1458 int64_t AlignDownOffset = alignDown(Offset, 4); 1459 int64_t OffsetDiff = Offset - AlignDownOffset; 1460 1461 EVT IntVT = MemVT.changeTypeToInteger(); 1462 1463 // TODO: If we passed in the base kernel offset we could have a better 1464 // alignment than 4, but we don't really need it. 1465 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1466 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1467 MachineMemOperand::MODereferenceable | 1468 MachineMemOperand::MOInvariant); 1469 1470 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1471 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1472 1473 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1474 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1475 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1476 1477 1478 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1479 } 1480 1481 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1482 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1483 MachineMemOperand::MODereferenceable | 1484 MachineMemOperand::MOInvariant); 1485 1486 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1487 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1488 } 1489 1490 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1491 const SDLoc &SL, SDValue Chain, 1492 const ISD::InputArg &Arg) const { 1493 MachineFunction &MF = DAG.getMachineFunction(); 1494 MachineFrameInfo &MFI = MF.getFrameInfo(); 1495 1496 if (Arg.Flags.isByVal()) { 1497 unsigned Size = Arg.Flags.getByValSize(); 1498 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1499 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1500 } 1501 1502 unsigned ArgOffset = VA.getLocMemOffset(); 1503 unsigned ArgSize = VA.getValVT().getStoreSize(); 1504 1505 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1506 1507 // Create load nodes to retrieve arguments from the stack. 1508 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1509 SDValue ArgValue; 1510 1511 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1512 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1513 MVT MemVT = VA.getValVT(); 1514 1515 switch (VA.getLocInfo()) { 1516 default: 1517 break; 1518 case CCValAssign::BCvt: 1519 MemVT = VA.getLocVT(); 1520 break; 1521 case CCValAssign::SExt: 1522 ExtType = ISD::SEXTLOAD; 1523 break; 1524 case CCValAssign::ZExt: 1525 ExtType = ISD::ZEXTLOAD; 1526 break; 1527 case CCValAssign::AExt: 1528 ExtType = ISD::EXTLOAD; 1529 break; 1530 } 1531 1532 ArgValue = DAG.getExtLoad( 1533 ExtType, SL, VA.getLocVT(), Chain, FIN, 1534 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1535 MemVT); 1536 return ArgValue; 1537 } 1538 1539 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1540 const SIMachineFunctionInfo &MFI, 1541 EVT VT, 1542 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1543 const ArgDescriptor *Reg; 1544 const TargetRegisterClass *RC; 1545 1546 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1547 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1548 } 1549 1550 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1551 CallingConv::ID CallConv, 1552 ArrayRef<ISD::InputArg> Ins, 1553 BitVector &Skipped, 1554 FunctionType *FType, 1555 SIMachineFunctionInfo *Info) { 1556 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1557 const ISD::InputArg *Arg = &Ins[I]; 1558 1559 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1560 "vector type argument should have been split"); 1561 1562 // First check if it's a PS input addr. 1563 if (CallConv == CallingConv::AMDGPU_PS && 1564 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1565 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1566 1567 // Inconveniently only the first part of the split is marked as isSplit, 1568 // so skip to the end. We only want to increment PSInputNum once for the 1569 // entire split argument. 1570 if (Arg->Flags.isSplit()) { 1571 while (!Arg->Flags.isSplitEnd()) { 1572 assert((!Arg->VT.isVector() || 1573 Arg->VT.getScalarSizeInBits() == 16) && 1574 "unexpected vector split in ps argument type"); 1575 if (!SkipArg) 1576 Splits.push_back(*Arg); 1577 Arg = &Ins[++I]; 1578 } 1579 } 1580 1581 if (SkipArg) { 1582 // We can safely skip PS inputs. 1583 Skipped.set(Arg->getOrigArgIndex()); 1584 ++PSInputNum; 1585 continue; 1586 } 1587 1588 Info->markPSInputAllocated(PSInputNum); 1589 if (Arg->Used) 1590 Info->markPSInputEnabled(PSInputNum); 1591 1592 ++PSInputNum; 1593 } 1594 1595 Splits.push_back(*Arg); 1596 } 1597 } 1598 1599 // Allocate special inputs passed in VGPRs. 1600 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1601 MachineFunction &MF, 1602 const SIRegisterInfo &TRI, 1603 SIMachineFunctionInfo &Info) const { 1604 const LLT S32 = LLT::scalar(32); 1605 MachineRegisterInfo &MRI = MF.getRegInfo(); 1606 1607 if (Info.hasWorkItemIDX()) { 1608 Register Reg = AMDGPU::VGPR0; 1609 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1610 1611 CCInfo.AllocateReg(Reg); 1612 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1613 } 1614 1615 if (Info.hasWorkItemIDY()) { 1616 Register Reg = AMDGPU::VGPR1; 1617 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1618 1619 CCInfo.AllocateReg(Reg); 1620 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1621 } 1622 1623 if (Info.hasWorkItemIDZ()) { 1624 Register Reg = AMDGPU::VGPR2; 1625 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1626 1627 CCInfo.AllocateReg(Reg); 1628 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1629 } 1630 } 1631 1632 // Try to allocate a VGPR at the end of the argument list, or if no argument 1633 // VGPRs are left allocating a stack slot. 1634 // If \p Mask is is given it indicates bitfield position in the register. 1635 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1636 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1637 ArgDescriptor Arg = ArgDescriptor()) { 1638 if (Arg.isSet()) 1639 return ArgDescriptor::createArg(Arg, Mask); 1640 1641 ArrayRef<MCPhysReg> ArgVGPRs 1642 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1643 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1644 if (RegIdx == ArgVGPRs.size()) { 1645 // Spill to stack required. 1646 int64_t Offset = CCInfo.AllocateStack(4, 4); 1647 1648 return ArgDescriptor::createStack(Offset, Mask); 1649 } 1650 1651 unsigned Reg = ArgVGPRs[RegIdx]; 1652 Reg = CCInfo.AllocateReg(Reg); 1653 assert(Reg != AMDGPU::NoRegister); 1654 1655 MachineFunction &MF = CCInfo.getMachineFunction(); 1656 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1657 return ArgDescriptor::createRegister(Reg, Mask); 1658 } 1659 1660 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1661 const TargetRegisterClass *RC, 1662 unsigned NumArgRegs) { 1663 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1664 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1665 if (RegIdx == ArgSGPRs.size()) 1666 report_fatal_error("ran out of SGPRs for arguments"); 1667 1668 unsigned Reg = ArgSGPRs[RegIdx]; 1669 Reg = CCInfo.AllocateReg(Reg); 1670 assert(Reg != AMDGPU::NoRegister); 1671 1672 MachineFunction &MF = CCInfo.getMachineFunction(); 1673 MF.addLiveIn(Reg, RC); 1674 return ArgDescriptor::createRegister(Reg); 1675 } 1676 1677 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1678 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1679 } 1680 1681 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1682 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1683 } 1684 1685 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo, 1686 MachineFunction &MF, 1687 const SIRegisterInfo &TRI, 1688 SIMachineFunctionInfo &Info) const { 1689 const unsigned Mask = 0x3ff; 1690 ArgDescriptor Arg; 1691 1692 if (Info.hasWorkItemIDX()) { 1693 Arg = allocateVGPR32Input(CCInfo, Mask); 1694 Info.setWorkItemIDX(Arg); 1695 } 1696 1697 if (Info.hasWorkItemIDY()) { 1698 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1699 Info.setWorkItemIDY(Arg); 1700 } 1701 1702 if (Info.hasWorkItemIDZ()) 1703 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1704 } 1705 1706 void SITargetLowering::allocateSpecialInputSGPRs( 1707 CCState &CCInfo, 1708 MachineFunction &MF, 1709 const SIRegisterInfo &TRI, 1710 SIMachineFunctionInfo &Info) const { 1711 auto &ArgInfo = Info.getArgInfo(); 1712 1713 // TODO: Unify handling with private memory pointers. 1714 1715 if (Info.hasDispatchPtr()) 1716 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1717 1718 if (Info.hasQueuePtr()) 1719 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1720 1721 if (Info.hasKernargSegmentPtr()) 1722 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1723 1724 if (Info.hasDispatchID()) 1725 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1726 1727 // flat_scratch_init is not applicable for non-kernel functions. 1728 1729 if (Info.hasWorkGroupIDX()) 1730 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1731 1732 if (Info.hasWorkGroupIDY()) 1733 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1734 1735 if (Info.hasWorkGroupIDZ()) 1736 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1737 1738 if (Info.hasImplicitArgPtr()) 1739 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1740 } 1741 1742 // Allocate special inputs passed in user SGPRs. 1743 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1744 MachineFunction &MF, 1745 const SIRegisterInfo &TRI, 1746 SIMachineFunctionInfo &Info) const { 1747 if (Info.hasImplicitBufferPtr()) { 1748 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1749 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1750 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1751 } 1752 1753 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1754 if (Info.hasPrivateSegmentBuffer()) { 1755 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1756 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1757 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1758 } 1759 1760 if (Info.hasDispatchPtr()) { 1761 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1762 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1763 CCInfo.AllocateReg(DispatchPtrReg); 1764 } 1765 1766 if (Info.hasQueuePtr()) { 1767 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1768 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1769 CCInfo.AllocateReg(QueuePtrReg); 1770 } 1771 1772 if (Info.hasKernargSegmentPtr()) { 1773 MachineRegisterInfo &MRI = MF.getRegInfo(); 1774 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1775 CCInfo.AllocateReg(InputPtrReg); 1776 1777 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1778 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1779 } 1780 1781 if (Info.hasDispatchID()) { 1782 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1783 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1784 CCInfo.AllocateReg(DispatchIDReg); 1785 } 1786 1787 if (Info.hasFlatScratchInit()) { 1788 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1789 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1790 CCInfo.AllocateReg(FlatScratchInitReg); 1791 } 1792 1793 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1794 // these from the dispatch pointer. 1795 } 1796 1797 // Allocate special input registers that are initialized per-wave. 1798 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1799 MachineFunction &MF, 1800 SIMachineFunctionInfo &Info, 1801 CallingConv::ID CallConv, 1802 bool IsShader) const { 1803 if (Info.hasWorkGroupIDX()) { 1804 unsigned Reg = Info.addWorkGroupIDX(); 1805 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1806 CCInfo.AllocateReg(Reg); 1807 } 1808 1809 if (Info.hasWorkGroupIDY()) { 1810 unsigned Reg = Info.addWorkGroupIDY(); 1811 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1812 CCInfo.AllocateReg(Reg); 1813 } 1814 1815 if (Info.hasWorkGroupIDZ()) { 1816 unsigned Reg = Info.addWorkGroupIDZ(); 1817 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1818 CCInfo.AllocateReg(Reg); 1819 } 1820 1821 if (Info.hasWorkGroupInfo()) { 1822 unsigned Reg = Info.addWorkGroupInfo(); 1823 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1824 CCInfo.AllocateReg(Reg); 1825 } 1826 1827 if (Info.hasPrivateSegmentWaveByteOffset()) { 1828 // Scratch wave offset passed in system SGPR. 1829 unsigned PrivateSegmentWaveByteOffsetReg; 1830 1831 if (IsShader) { 1832 PrivateSegmentWaveByteOffsetReg = 1833 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1834 1835 // This is true if the scratch wave byte offset doesn't have a fixed 1836 // location. 1837 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1838 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1839 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1840 } 1841 } else 1842 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1843 1844 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1845 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1846 } 1847 } 1848 1849 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1850 MachineFunction &MF, 1851 const SIRegisterInfo &TRI, 1852 SIMachineFunctionInfo &Info) { 1853 // Now that we've figured out where the scratch register inputs are, see if 1854 // should reserve the arguments and use them directly. 1855 MachineFrameInfo &MFI = MF.getFrameInfo(); 1856 bool HasStackObjects = MFI.hasStackObjects(); 1857 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1858 1859 // Record that we know we have non-spill stack objects so we don't need to 1860 // check all stack objects later. 1861 if (HasStackObjects) 1862 Info.setHasNonSpillStackObjects(true); 1863 1864 // Everything live out of a block is spilled with fast regalloc, so it's 1865 // almost certain that spilling will be required. 1866 if (TM.getOptLevel() == CodeGenOpt::None) 1867 HasStackObjects = true; 1868 1869 // For now assume stack access is needed in any callee functions, so we need 1870 // the scratch registers to pass in. 1871 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1872 1873 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1874 // If we have stack objects, we unquestionably need the private buffer 1875 // resource. For the Code Object V2 ABI, this will be the first 4 user 1876 // SGPR inputs. We can reserve those and use them directly. 1877 1878 unsigned PrivateSegmentBufferReg = 1879 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1880 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1881 } else { 1882 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1883 // We tentatively reserve the last registers (skipping the last registers 1884 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1885 // we'll replace these with the ones immediately after those which were 1886 // really allocated. In the prologue copies will be inserted from the 1887 // argument to these reserved registers. 1888 1889 // Without HSA, relocations are used for the scratch pointer and the 1890 // buffer resource setup is always inserted in the prologue. Scratch wave 1891 // offset is still in an input SGPR. 1892 Info.setScratchRSrcReg(ReservedBufferReg); 1893 } 1894 1895 // hasFP should be accurate for kernels even before the frame is finalized. 1896 if (ST.getFrameLowering()->hasFP(MF)) { 1897 MachineRegisterInfo &MRI = MF.getRegInfo(); 1898 1899 // Try to use s32 as the SP, but move it if it would interfere with input 1900 // arguments. This won't work with calls though. 1901 // 1902 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1903 // registers. 1904 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1905 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1906 } else { 1907 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1908 1909 if (MFI.hasCalls()) 1910 report_fatal_error("call in graphics shader with too many input SGPRs"); 1911 1912 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1913 if (!MRI.isLiveIn(Reg)) { 1914 Info.setStackPtrOffsetReg(Reg); 1915 break; 1916 } 1917 } 1918 1919 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1920 report_fatal_error("failed to find register for SP"); 1921 } 1922 1923 if (MFI.hasCalls()) { 1924 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1925 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1926 } else { 1927 unsigned ReservedOffsetReg = 1928 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1929 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1930 Info.setFrameOffsetReg(ReservedOffsetReg); 1931 } 1932 } else if (RequiresStackAccess) { 1933 assert(!MFI.hasCalls()); 1934 // We know there are accesses and they will be done relative to SP, so just 1935 // pin it to the input. 1936 // 1937 // FIXME: Should not do this if inline asm is reading/writing these 1938 // registers. 1939 unsigned PreloadedSP = Info.getPreloadedReg( 1940 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1941 1942 Info.setStackPtrOffsetReg(PreloadedSP); 1943 Info.setScratchWaveOffsetReg(PreloadedSP); 1944 Info.setFrameOffsetReg(PreloadedSP); 1945 } else { 1946 assert(!MFI.hasCalls()); 1947 1948 // There may not be stack access at all. There may still be spills, or 1949 // access of a constant pointer (in which cases an extra copy will be 1950 // emitted in the prolog). 1951 unsigned ReservedOffsetReg 1952 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1953 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1954 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1955 Info.setFrameOffsetReg(ReservedOffsetReg); 1956 } 1957 } 1958 1959 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1960 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1961 return !Info->isEntryFunction(); 1962 } 1963 1964 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1965 1966 } 1967 1968 void SITargetLowering::insertCopiesSplitCSR( 1969 MachineBasicBlock *Entry, 1970 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1971 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1972 1973 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1974 if (!IStart) 1975 return; 1976 1977 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1978 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1979 MachineBasicBlock::iterator MBBI = Entry->begin(); 1980 for (const MCPhysReg *I = IStart; *I; ++I) { 1981 const TargetRegisterClass *RC = nullptr; 1982 if (AMDGPU::SReg_64RegClass.contains(*I)) 1983 RC = &AMDGPU::SGPR_64RegClass; 1984 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1985 RC = &AMDGPU::SGPR_32RegClass; 1986 else 1987 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1988 1989 unsigned NewVR = MRI->createVirtualRegister(RC); 1990 // Create copy from CSR to a virtual register. 1991 Entry->addLiveIn(*I); 1992 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1993 .addReg(*I); 1994 1995 // Insert the copy-back instructions right before the terminator. 1996 for (auto *Exit : Exits) 1997 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1998 TII->get(TargetOpcode::COPY), *I) 1999 .addReg(NewVR); 2000 } 2001 } 2002 2003 SDValue SITargetLowering::LowerFormalArguments( 2004 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2005 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2006 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2007 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2008 2009 MachineFunction &MF = DAG.getMachineFunction(); 2010 const Function &Fn = MF.getFunction(); 2011 FunctionType *FType = MF.getFunction().getFunctionType(); 2012 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2013 2014 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2015 DiagnosticInfoUnsupported NoGraphicsHSA( 2016 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2017 DAG.getContext()->diagnose(NoGraphicsHSA); 2018 return DAG.getEntryNode(); 2019 } 2020 2021 SmallVector<ISD::InputArg, 16> Splits; 2022 SmallVector<CCValAssign, 16> ArgLocs; 2023 BitVector Skipped(Ins.size()); 2024 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2025 *DAG.getContext()); 2026 2027 bool IsShader = AMDGPU::isShader(CallConv); 2028 bool IsKernel = AMDGPU::isKernel(CallConv); 2029 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2030 2031 if (IsShader) { 2032 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2033 2034 // At least one interpolation mode must be enabled or else the GPU will 2035 // hang. 2036 // 2037 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2038 // set PSInputAddr, the user wants to enable some bits after the compilation 2039 // based on run-time states. Since we can't know what the final PSInputEna 2040 // will look like, so we shouldn't do anything here and the user should take 2041 // responsibility for the correct programming. 2042 // 2043 // Otherwise, the following restrictions apply: 2044 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2045 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2046 // enabled too. 2047 if (CallConv == CallingConv::AMDGPU_PS) { 2048 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2049 ((Info->getPSInputAddr() & 0xF) == 0 && 2050 Info->isPSInputAllocated(11))) { 2051 CCInfo.AllocateReg(AMDGPU::VGPR0); 2052 CCInfo.AllocateReg(AMDGPU::VGPR1); 2053 Info->markPSInputAllocated(0); 2054 Info->markPSInputEnabled(0); 2055 } 2056 if (Subtarget->isAmdPalOS()) { 2057 // For isAmdPalOS, the user does not enable some bits after compilation 2058 // based on run-time states; the register values being generated here are 2059 // the final ones set in hardware. Therefore we need to apply the 2060 // workaround to PSInputAddr and PSInputEnable together. (The case where 2061 // a bit is set in PSInputAddr but not PSInputEnable is where the 2062 // frontend set up an input arg for a particular interpolation mode, but 2063 // nothing uses that input arg. Really we should have an earlier pass 2064 // that removes such an arg.) 2065 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2066 if ((PsInputBits & 0x7F) == 0 || 2067 ((PsInputBits & 0xF) == 0 && 2068 (PsInputBits >> 11 & 1))) 2069 Info->markPSInputEnabled( 2070 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2071 } 2072 } 2073 2074 assert(!Info->hasDispatchPtr() && 2075 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2076 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2077 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2078 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2079 !Info->hasWorkItemIDZ()); 2080 } else if (IsKernel) { 2081 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2082 } else { 2083 Splits.append(Ins.begin(), Ins.end()); 2084 } 2085 2086 if (IsEntryFunc) { 2087 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2088 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2089 } 2090 2091 if (IsKernel) { 2092 analyzeFormalArgumentsCompute(CCInfo, Ins); 2093 } else { 2094 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2095 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2096 } 2097 2098 SmallVector<SDValue, 16> Chains; 2099 2100 // FIXME: This is the minimum kernel argument alignment. We should improve 2101 // this to the maximum alignment of the arguments. 2102 // 2103 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2104 // kern arg offset. 2105 const unsigned KernelArgBaseAlign = 16; 2106 2107 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2108 const ISD::InputArg &Arg = Ins[i]; 2109 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2110 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2111 continue; 2112 } 2113 2114 CCValAssign &VA = ArgLocs[ArgIdx++]; 2115 MVT VT = VA.getLocVT(); 2116 2117 if (IsEntryFunc && VA.isMemLoc()) { 2118 VT = Ins[i].VT; 2119 EVT MemVT = VA.getLocVT(); 2120 2121 const uint64_t Offset = VA.getLocMemOffset(); 2122 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2123 2124 SDValue Arg = lowerKernargMemParameter( 2125 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2126 Chains.push_back(Arg.getValue(1)); 2127 2128 auto *ParamTy = 2129 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2130 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2131 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2132 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2133 // On SI local pointers are just offsets into LDS, so they are always 2134 // less than 16-bits. On CI and newer they could potentially be 2135 // real pointers, so we can't guarantee their size. 2136 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2137 DAG.getValueType(MVT::i16)); 2138 } 2139 2140 InVals.push_back(Arg); 2141 continue; 2142 } else if (!IsEntryFunc && VA.isMemLoc()) { 2143 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2144 InVals.push_back(Val); 2145 if (!Arg.Flags.isByVal()) 2146 Chains.push_back(Val.getValue(1)); 2147 continue; 2148 } 2149 2150 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2151 2152 unsigned Reg = VA.getLocReg(); 2153 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2154 EVT ValVT = VA.getValVT(); 2155 2156 Reg = MF.addLiveIn(Reg, RC); 2157 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2158 2159 if (Arg.Flags.isSRet()) { 2160 // The return object should be reasonably addressable. 2161 2162 // FIXME: This helps when the return is a real sret. If it is a 2163 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2164 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2165 unsigned NumBits 2166 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2167 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2168 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2169 } 2170 2171 // If this is an 8 or 16-bit value, it is really passed promoted 2172 // to 32 bits. Insert an assert[sz]ext to capture this, then 2173 // truncate to the right size. 2174 switch (VA.getLocInfo()) { 2175 case CCValAssign::Full: 2176 break; 2177 case CCValAssign::BCvt: 2178 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2179 break; 2180 case CCValAssign::SExt: 2181 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2182 DAG.getValueType(ValVT)); 2183 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2184 break; 2185 case CCValAssign::ZExt: 2186 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2187 DAG.getValueType(ValVT)); 2188 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2189 break; 2190 case CCValAssign::AExt: 2191 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2192 break; 2193 default: 2194 llvm_unreachable("Unknown loc info!"); 2195 } 2196 2197 InVals.push_back(Val); 2198 } 2199 2200 if (!IsEntryFunc) { 2201 // Special inputs come after user arguments. 2202 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2203 } 2204 2205 // Start adding system SGPRs. 2206 if (IsEntryFunc) { 2207 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2208 } else { 2209 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2210 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2211 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2212 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2213 } 2214 2215 auto &ArgUsageInfo = 2216 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2217 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2218 2219 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2220 Info->setBytesInStackArgArea(StackArgSize); 2221 2222 return Chains.empty() ? Chain : 2223 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2224 } 2225 2226 // TODO: If return values can't fit in registers, we should return as many as 2227 // possible in registers before passing on stack. 2228 bool SITargetLowering::CanLowerReturn( 2229 CallingConv::ID CallConv, 2230 MachineFunction &MF, bool IsVarArg, 2231 const SmallVectorImpl<ISD::OutputArg> &Outs, 2232 LLVMContext &Context) const { 2233 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2234 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2235 // for shaders. Vector types should be explicitly handled by CC. 2236 if (AMDGPU::isEntryFunctionCC(CallConv)) 2237 return true; 2238 2239 SmallVector<CCValAssign, 16> RVLocs; 2240 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2241 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2242 } 2243 2244 SDValue 2245 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2246 bool isVarArg, 2247 const SmallVectorImpl<ISD::OutputArg> &Outs, 2248 const SmallVectorImpl<SDValue> &OutVals, 2249 const SDLoc &DL, SelectionDAG &DAG) const { 2250 MachineFunction &MF = DAG.getMachineFunction(); 2251 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2252 2253 if (AMDGPU::isKernel(CallConv)) { 2254 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2255 OutVals, DL, DAG); 2256 } 2257 2258 bool IsShader = AMDGPU::isShader(CallConv); 2259 2260 Info->setIfReturnsVoid(Outs.empty()); 2261 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2262 2263 // CCValAssign - represent the assignment of the return value to a location. 2264 SmallVector<CCValAssign, 48> RVLocs; 2265 SmallVector<ISD::OutputArg, 48> Splits; 2266 2267 // CCState - Info about the registers and stack slots. 2268 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2269 *DAG.getContext()); 2270 2271 // Analyze outgoing return values. 2272 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2273 2274 SDValue Flag; 2275 SmallVector<SDValue, 48> RetOps; 2276 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2277 2278 // Add return address for callable functions. 2279 if (!Info->isEntryFunction()) { 2280 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2281 SDValue ReturnAddrReg = CreateLiveInRegister( 2282 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2283 2284 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2285 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2286 MVT::i64); 2287 Chain = 2288 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2289 Flag = Chain.getValue(1); 2290 RetOps.push_back(ReturnAddrVirtualReg); 2291 } 2292 2293 // Copy the result values into the output registers. 2294 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2295 ++I, ++RealRVLocIdx) { 2296 CCValAssign &VA = RVLocs[I]; 2297 assert(VA.isRegLoc() && "Can only return in registers!"); 2298 // TODO: Partially return in registers if return values don't fit. 2299 SDValue Arg = OutVals[RealRVLocIdx]; 2300 2301 // Copied from other backends. 2302 switch (VA.getLocInfo()) { 2303 case CCValAssign::Full: 2304 break; 2305 case CCValAssign::BCvt: 2306 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2307 break; 2308 case CCValAssign::SExt: 2309 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2310 break; 2311 case CCValAssign::ZExt: 2312 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2313 break; 2314 case CCValAssign::AExt: 2315 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2316 break; 2317 default: 2318 llvm_unreachable("Unknown loc info!"); 2319 } 2320 2321 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2322 Flag = Chain.getValue(1); 2323 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2324 } 2325 2326 // FIXME: Does sret work properly? 2327 if (!Info->isEntryFunction()) { 2328 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2329 const MCPhysReg *I = 2330 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2331 if (I) { 2332 for (; *I; ++I) { 2333 if (AMDGPU::SReg_64RegClass.contains(*I)) 2334 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2335 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2336 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2337 else 2338 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2339 } 2340 } 2341 } 2342 2343 // Update chain and glue. 2344 RetOps[0] = Chain; 2345 if (Flag.getNode()) 2346 RetOps.push_back(Flag); 2347 2348 unsigned Opc = AMDGPUISD::ENDPGM; 2349 if (!IsWaveEnd) 2350 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2351 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2352 } 2353 2354 SDValue SITargetLowering::LowerCallResult( 2355 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2356 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2357 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2358 SDValue ThisVal) const { 2359 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2360 2361 // Assign locations to each value returned by this call. 2362 SmallVector<CCValAssign, 16> RVLocs; 2363 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2364 *DAG.getContext()); 2365 CCInfo.AnalyzeCallResult(Ins, RetCC); 2366 2367 // Copy all of the result registers out of their specified physreg. 2368 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2369 CCValAssign VA = RVLocs[i]; 2370 SDValue Val; 2371 2372 if (VA.isRegLoc()) { 2373 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2374 Chain = Val.getValue(1); 2375 InFlag = Val.getValue(2); 2376 } else if (VA.isMemLoc()) { 2377 report_fatal_error("TODO: return values in memory"); 2378 } else 2379 llvm_unreachable("unknown argument location type"); 2380 2381 switch (VA.getLocInfo()) { 2382 case CCValAssign::Full: 2383 break; 2384 case CCValAssign::BCvt: 2385 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2386 break; 2387 case CCValAssign::ZExt: 2388 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2389 DAG.getValueType(VA.getValVT())); 2390 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2391 break; 2392 case CCValAssign::SExt: 2393 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2394 DAG.getValueType(VA.getValVT())); 2395 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2396 break; 2397 case CCValAssign::AExt: 2398 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2399 break; 2400 default: 2401 llvm_unreachable("Unknown loc info!"); 2402 } 2403 2404 InVals.push_back(Val); 2405 } 2406 2407 return Chain; 2408 } 2409 2410 // Add code to pass special inputs required depending on used features separate 2411 // from the explicit user arguments present in the IR. 2412 void SITargetLowering::passSpecialInputs( 2413 CallLoweringInfo &CLI, 2414 CCState &CCInfo, 2415 const SIMachineFunctionInfo &Info, 2416 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2417 SmallVectorImpl<SDValue> &MemOpChains, 2418 SDValue Chain) const { 2419 // If we don't have a call site, this was a call inserted by 2420 // legalization. These can never use special inputs. 2421 if (!CLI.CS) 2422 return; 2423 2424 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2425 assert(CalleeFunc); 2426 2427 SelectionDAG &DAG = CLI.DAG; 2428 const SDLoc &DL = CLI.DL; 2429 2430 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2431 2432 auto &ArgUsageInfo = 2433 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2434 const AMDGPUFunctionArgInfo &CalleeArgInfo 2435 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2436 2437 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2438 2439 // TODO: Unify with private memory register handling. This is complicated by 2440 // the fact that at least in kernels, the input argument is not necessarily 2441 // in the same location as the input. 2442 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2443 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2444 AMDGPUFunctionArgInfo::QUEUE_PTR, 2445 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2446 AMDGPUFunctionArgInfo::DISPATCH_ID, 2447 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2448 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2449 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2450 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2451 }; 2452 2453 for (auto InputID : InputRegs) { 2454 const ArgDescriptor *OutgoingArg; 2455 const TargetRegisterClass *ArgRC; 2456 2457 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2458 if (!OutgoingArg) 2459 continue; 2460 2461 const ArgDescriptor *IncomingArg; 2462 const TargetRegisterClass *IncomingArgRC; 2463 std::tie(IncomingArg, IncomingArgRC) 2464 = CallerArgInfo.getPreloadedValue(InputID); 2465 assert(IncomingArgRC == ArgRC); 2466 2467 // All special arguments are ints for now. 2468 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2469 SDValue InputReg; 2470 2471 if (IncomingArg) { 2472 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2473 } else { 2474 // The implicit arg ptr is special because it doesn't have a corresponding 2475 // input for kernels, and is computed from the kernarg segment pointer. 2476 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2477 InputReg = getImplicitArgPtr(DAG, DL); 2478 } 2479 2480 if (OutgoingArg->isRegister()) { 2481 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2482 } else { 2483 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2484 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2485 SpecialArgOffset); 2486 MemOpChains.push_back(ArgStore); 2487 } 2488 } 2489 2490 // Pack workitem IDs into a single register or pass it as is if already 2491 // packed. 2492 const ArgDescriptor *OutgoingArg; 2493 const TargetRegisterClass *ArgRC; 2494 2495 std::tie(OutgoingArg, ArgRC) = 2496 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2497 if (!OutgoingArg) 2498 std::tie(OutgoingArg, ArgRC) = 2499 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2500 if (!OutgoingArg) 2501 std::tie(OutgoingArg, ArgRC) = 2502 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2503 if (!OutgoingArg) 2504 return; 2505 2506 const ArgDescriptor *IncomingArgX 2507 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2508 const ArgDescriptor *IncomingArgY 2509 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2510 const ArgDescriptor *IncomingArgZ 2511 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2512 2513 SDValue InputReg; 2514 SDLoc SL; 2515 2516 // If incoming ids are not packed we need to pack them. 2517 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2518 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2519 2520 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2521 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2522 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2523 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2524 InputReg = InputReg.getNode() ? 2525 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2526 } 2527 2528 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2529 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2530 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2531 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2532 InputReg = InputReg.getNode() ? 2533 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2534 } 2535 2536 if (!InputReg.getNode()) { 2537 // Workitem ids are already packed, any of present incoming arguments 2538 // will carry all required fields. 2539 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2540 IncomingArgX ? *IncomingArgX : 2541 IncomingArgY ? *IncomingArgY : 2542 *IncomingArgZ, ~0u); 2543 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2544 } 2545 2546 if (OutgoingArg->isRegister()) { 2547 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2548 } else { 2549 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2550 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2551 SpecialArgOffset); 2552 MemOpChains.push_back(ArgStore); 2553 } 2554 } 2555 2556 static bool canGuaranteeTCO(CallingConv::ID CC) { 2557 return CC == CallingConv::Fast; 2558 } 2559 2560 /// Return true if we might ever do TCO for calls with this calling convention. 2561 static bool mayTailCallThisCC(CallingConv::ID CC) { 2562 switch (CC) { 2563 case CallingConv::C: 2564 return true; 2565 default: 2566 return canGuaranteeTCO(CC); 2567 } 2568 } 2569 2570 bool SITargetLowering::isEligibleForTailCallOptimization( 2571 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2572 const SmallVectorImpl<ISD::OutputArg> &Outs, 2573 const SmallVectorImpl<SDValue> &OutVals, 2574 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2575 if (!mayTailCallThisCC(CalleeCC)) 2576 return false; 2577 2578 MachineFunction &MF = DAG.getMachineFunction(); 2579 const Function &CallerF = MF.getFunction(); 2580 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2581 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2582 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2583 2584 // Kernels aren't callable, and don't have a live in return address so it 2585 // doesn't make sense to do a tail call with entry functions. 2586 if (!CallerPreserved) 2587 return false; 2588 2589 bool CCMatch = CallerCC == CalleeCC; 2590 2591 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2592 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2593 return true; 2594 return false; 2595 } 2596 2597 // TODO: Can we handle var args? 2598 if (IsVarArg) 2599 return false; 2600 2601 for (const Argument &Arg : CallerF.args()) { 2602 if (Arg.hasByValAttr()) 2603 return false; 2604 } 2605 2606 LLVMContext &Ctx = *DAG.getContext(); 2607 2608 // Check that the call results are passed in the same way. 2609 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2610 CCAssignFnForCall(CalleeCC, IsVarArg), 2611 CCAssignFnForCall(CallerCC, IsVarArg))) 2612 return false; 2613 2614 // The callee has to preserve all registers the caller needs to preserve. 2615 if (!CCMatch) { 2616 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2617 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2618 return false; 2619 } 2620 2621 // Nothing more to check if the callee is taking no arguments. 2622 if (Outs.empty()) 2623 return true; 2624 2625 SmallVector<CCValAssign, 16> ArgLocs; 2626 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2627 2628 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2629 2630 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2631 // If the stack arguments for this call do not fit into our own save area then 2632 // the call cannot be made tail. 2633 // TODO: Is this really necessary? 2634 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2635 return false; 2636 2637 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2638 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2639 } 2640 2641 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2642 if (!CI->isTailCall()) 2643 return false; 2644 2645 const Function *ParentFn = CI->getParent()->getParent(); 2646 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2647 return false; 2648 2649 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2650 return (Attr.getValueAsString() != "true"); 2651 } 2652 2653 // The wave scratch offset register is used as the global base pointer. 2654 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2655 SmallVectorImpl<SDValue> &InVals) const { 2656 SelectionDAG &DAG = CLI.DAG; 2657 const SDLoc &DL = CLI.DL; 2658 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2659 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2660 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2661 SDValue Chain = CLI.Chain; 2662 SDValue Callee = CLI.Callee; 2663 bool &IsTailCall = CLI.IsTailCall; 2664 CallingConv::ID CallConv = CLI.CallConv; 2665 bool IsVarArg = CLI.IsVarArg; 2666 bool IsSibCall = false; 2667 bool IsThisReturn = false; 2668 MachineFunction &MF = DAG.getMachineFunction(); 2669 2670 if (IsVarArg) { 2671 return lowerUnhandledCall(CLI, InVals, 2672 "unsupported call to variadic function "); 2673 } 2674 2675 if (!CLI.CS.getInstruction()) 2676 report_fatal_error("unsupported libcall legalization"); 2677 2678 if (!CLI.CS.getCalledFunction()) { 2679 return lowerUnhandledCall(CLI, InVals, 2680 "unsupported indirect call to function "); 2681 } 2682 2683 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2684 return lowerUnhandledCall(CLI, InVals, 2685 "unsupported required tail call to function "); 2686 } 2687 2688 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2689 // Note the issue is with the CC of the calling function, not of the call 2690 // itself. 2691 return lowerUnhandledCall(CLI, InVals, 2692 "unsupported call from graphics shader of function "); 2693 } 2694 2695 if (IsTailCall) { 2696 IsTailCall = isEligibleForTailCallOptimization( 2697 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2698 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2699 report_fatal_error("failed to perform tail call elimination on a call " 2700 "site marked musttail"); 2701 } 2702 2703 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2704 2705 // A sibling call is one where we're under the usual C ABI and not planning 2706 // to change that but can still do a tail call: 2707 if (!TailCallOpt && IsTailCall) 2708 IsSibCall = true; 2709 2710 if (IsTailCall) 2711 ++NumTailCalls; 2712 } 2713 2714 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2715 2716 // Analyze operands of the call, assigning locations to each operand. 2717 SmallVector<CCValAssign, 16> ArgLocs; 2718 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2719 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2720 2721 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2722 2723 // Get a count of how many bytes are to be pushed on the stack. 2724 unsigned NumBytes = CCInfo.getNextStackOffset(); 2725 2726 if (IsSibCall) { 2727 // Since we're not changing the ABI to make this a tail call, the memory 2728 // operands are already available in the caller's incoming argument space. 2729 NumBytes = 0; 2730 } 2731 2732 // FPDiff is the byte offset of the call's argument area from the callee's. 2733 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2734 // by this amount for a tail call. In a sibling call it must be 0 because the 2735 // caller will deallocate the entire stack and the callee still expects its 2736 // arguments to begin at SP+0. Completely unused for non-tail calls. 2737 int32_t FPDiff = 0; 2738 MachineFrameInfo &MFI = MF.getFrameInfo(); 2739 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2740 2741 // Adjust the stack pointer for the new arguments... 2742 // These operations are automatically eliminated by the prolog/epilog pass 2743 if (!IsSibCall) { 2744 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2745 2746 SmallVector<SDValue, 4> CopyFromChains; 2747 2748 // In the HSA case, this should be an identity copy. 2749 SDValue ScratchRSrcReg 2750 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2751 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2752 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2753 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2754 } 2755 2756 SmallVector<SDValue, 8> MemOpChains; 2757 MVT PtrVT = MVT::i32; 2758 2759 // Walk the register/memloc assignments, inserting copies/loads. 2760 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2761 ++i, ++realArgIdx) { 2762 CCValAssign &VA = ArgLocs[i]; 2763 SDValue Arg = OutVals[realArgIdx]; 2764 2765 // Promote the value if needed. 2766 switch (VA.getLocInfo()) { 2767 case CCValAssign::Full: 2768 break; 2769 case CCValAssign::BCvt: 2770 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2771 break; 2772 case CCValAssign::ZExt: 2773 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2774 break; 2775 case CCValAssign::SExt: 2776 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2777 break; 2778 case CCValAssign::AExt: 2779 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2780 break; 2781 case CCValAssign::FPExt: 2782 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2783 break; 2784 default: 2785 llvm_unreachable("Unknown loc info!"); 2786 } 2787 2788 if (VA.isRegLoc()) { 2789 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2790 } else { 2791 assert(VA.isMemLoc()); 2792 2793 SDValue DstAddr; 2794 MachinePointerInfo DstInfo; 2795 2796 unsigned LocMemOffset = VA.getLocMemOffset(); 2797 int32_t Offset = LocMemOffset; 2798 2799 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2800 unsigned Align = 0; 2801 2802 if (IsTailCall) { 2803 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2804 unsigned OpSize = Flags.isByVal() ? 2805 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2806 2807 // FIXME: We can have better than the minimum byval required alignment. 2808 Align = Flags.isByVal() ? Flags.getByValAlign() : 2809 MinAlign(Subtarget->getStackAlignment(), Offset); 2810 2811 Offset = Offset + FPDiff; 2812 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2813 2814 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2815 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2816 2817 // Make sure any stack arguments overlapping with where we're storing 2818 // are loaded before this eventual operation. Otherwise they'll be 2819 // clobbered. 2820 2821 // FIXME: Why is this really necessary? This seems to just result in a 2822 // lot of code to copy the stack and write them back to the same 2823 // locations, which are supposed to be immutable? 2824 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2825 } else { 2826 DstAddr = PtrOff; 2827 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2828 Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset); 2829 } 2830 2831 if (Outs[i].Flags.isByVal()) { 2832 SDValue SizeNode = 2833 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2834 SDValue Cpy = DAG.getMemcpy( 2835 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2836 /*isVol = */ false, /*AlwaysInline = */ true, 2837 /*isTailCall = */ false, DstInfo, 2838 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2839 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS)))); 2840 2841 MemOpChains.push_back(Cpy); 2842 } else { 2843 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align); 2844 MemOpChains.push_back(Store); 2845 } 2846 } 2847 } 2848 2849 // Copy special input registers after user input arguments. 2850 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2851 2852 if (!MemOpChains.empty()) 2853 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2854 2855 // Build a sequence of copy-to-reg nodes chained together with token chain 2856 // and flag operands which copy the outgoing args into the appropriate regs. 2857 SDValue InFlag; 2858 for (auto &RegToPass : RegsToPass) { 2859 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2860 RegToPass.second, InFlag); 2861 InFlag = Chain.getValue(1); 2862 } 2863 2864 2865 SDValue PhysReturnAddrReg; 2866 if (IsTailCall) { 2867 // Since the return is being combined with the call, we need to pass on the 2868 // return address. 2869 2870 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2871 SDValue ReturnAddrReg = CreateLiveInRegister( 2872 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2873 2874 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2875 MVT::i64); 2876 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2877 InFlag = Chain.getValue(1); 2878 } 2879 2880 // We don't usually want to end the call-sequence here because we would tidy 2881 // the frame up *after* the call, however in the ABI-changing tail-call case 2882 // we've carefully laid out the parameters so that when sp is reset they'll be 2883 // in the correct location. 2884 if (IsTailCall && !IsSibCall) { 2885 Chain = DAG.getCALLSEQ_END(Chain, 2886 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2887 DAG.getTargetConstant(0, DL, MVT::i32), 2888 InFlag, DL); 2889 InFlag = Chain.getValue(1); 2890 } 2891 2892 std::vector<SDValue> Ops; 2893 Ops.push_back(Chain); 2894 Ops.push_back(Callee); 2895 // Add a redundant copy of the callee global which will not be legalized, as 2896 // we need direct access to the callee later. 2897 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2898 const GlobalValue *GV = GSD->getGlobal(); 2899 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2900 2901 if (IsTailCall) { 2902 // Each tail call may have to adjust the stack by a different amount, so 2903 // this information must travel along with the operation for eventual 2904 // consumption by emitEpilogue. 2905 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2906 2907 Ops.push_back(PhysReturnAddrReg); 2908 } 2909 2910 // Add argument registers to the end of the list so that they are known live 2911 // into the call. 2912 for (auto &RegToPass : RegsToPass) { 2913 Ops.push_back(DAG.getRegister(RegToPass.first, 2914 RegToPass.second.getValueType())); 2915 } 2916 2917 // Add a register mask operand representing the call-preserved registers. 2918 2919 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2920 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2921 assert(Mask && "Missing call preserved mask for calling convention"); 2922 Ops.push_back(DAG.getRegisterMask(Mask)); 2923 2924 if (InFlag.getNode()) 2925 Ops.push_back(InFlag); 2926 2927 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2928 2929 // If we're doing a tall call, use a TC_RETURN here rather than an 2930 // actual call instruction. 2931 if (IsTailCall) { 2932 MFI.setHasTailCall(); 2933 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2934 } 2935 2936 // Returns a chain and a flag for retval copy to use. 2937 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2938 Chain = Call.getValue(0); 2939 InFlag = Call.getValue(1); 2940 2941 uint64_t CalleePopBytes = NumBytes; 2942 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2943 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2944 InFlag, DL); 2945 if (!Ins.empty()) 2946 InFlag = Chain.getValue(1); 2947 2948 // Handle result values, copying them out of physregs into vregs that we 2949 // return. 2950 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2951 InVals, IsThisReturn, 2952 IsThisReturn ? OutVals[0] : SDValue()); 2953 } 2954 2955 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2956 SelectionDAG &DAG) const { 2957 unsigned Reg = StringSwitch<unsigned>(RegName) 2958 .Case("m0", AMDGPU::M0) 2959 .Case("exec", AMDGPU::EXEC) 2960 .Case("exec_lo", AMDGPU::EXEC_LO) 2961 .Case("exec_hi", AMDGPU::EXEC_HI) 2962 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2963 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2964 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2965 .Default(AMDGPU::NoRegister); 2966 2967 if (Reg == AMDGPU::NoRegister) { 2968 report_fatal_error(Twine("invalid register name \"" 2969 + StringRef(RegName) + "\".")); 2970 2971 } 2972 2973 if (!Subtarget->hasFlatScrRegister() && 2974 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2975 report_fatal_error(Twine("invalid register \"" 2976 + StringRef(RegName) + "\" for subtarget.")); 2977 } 2978 2979 switch (Reg) { 2980 case AMDGPU::M0: 2981 case AMDGPU::EXEC_LO: 2982 case AMDGPU::EXEC_HI: 2983 case AMDGPU::FLAT_SCR_LO: 2984 case AMDGPU::FLAT_SCR_HI: 2985 if (VT.getSizeInBits() == 32) 2986 return Reg; 2987 break; 2988 case AMDGPU::EXEC: 2989 case AMDGPU::FLAT_SCR: 2990 if (VT.getSizeInBits() == 64) 2991 return Reg; 2992 break; 2993 default: 2994 llvm_unreachable("missing register type checking"); 2995 } 2996 2997 report_fatal_error(Twine("invalid type for register \"" 2998 + StringRef(RegName) + "\".")); 2999 } 3000 3001 // If kill is not the last instruction, split the block so kill is always a 3002 // proper terminator. 3003 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3004 MachineBasicBlock *BB) const { 3005 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3006 3007 MachineBasicBlock::iterator SplitPoint(&MI); 3008 ++SplitPoint; 3009 3010 if (SplitPoint == BB->end()) { 3011 // Don't bother with a new block. 3012 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3013 return BB; 3014 } 3015 3016 MachineFunction *MF = BB->getParent(); 3017 MachineBasicBlock *SplitBB 3018 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3019 3020 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3021 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3022 3023 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3024 BB->addSuccessor(SplitBB); 3025 3026 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3027 return SplitBB; 3028 } 3029 3030 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3031 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3032 // be the first instruction in the remainder block. 3033 // 3034 /// \returns { LoopBody, Remainder } 3035 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3036 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3037 MachineFunction *MF = MBB.getParent(); 3038 MachineBasicBlock::iterator I(&MI); 3039 3040 // To insert the loop we need to split the block. Move everything after this 3041 // point to a new block, and insert a new empty block between the two. 3042 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3043 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3044 MachineFunction::iterator MBBI(MBB); 3045 ++MBBI; 3046 3047 MF->insert(MBBI, LoopBB); 3048 MF->insert(MBBI, RemainderBB); 3049 3050 LoopBB->addSuccessor(LoopBB); 3051 LoopBB->addSuccessor(RemainderBB); 3052 3053 // Move the rest of the block into a new block. 3054 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3055 3056 if (InstInLoop) { 3057 auto Next = std::next(I); 3058 3059 // Move instruction to loop body. 3060 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3061 3062 // Move the rest of the block. 3063 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3064 } else { 3065 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3066 } 3067 3068 MBB.addSuccessor(LoopBB); 3069 3070 return std::make_pair(LoopBB, RemainderBB); 3071 } 3072 3073 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3074 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3075 MachineBasicBlock *MBB = MI.getParent(); 3076 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3077 auto I = MI.getIterator(); 3078 auto E = std::next(I); 3079 3080 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3081 .addImm(0); 3082 3083 MIBundleBuilder Bundler(*MBB, I, E); 3084 finalizeBundle(*MBB, Bundler.begin()); 3085 } 3086 3087 MachineBasicBlock * 3088 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3089 MachineBasicBlock *BB) const { 3090 const DebugLoc &DL = MI.getDebugLoc(); 3091 3092 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3093 3094 MachineBasicBlock *LoopBB; 3095 MachineBasicBlock *RemainderBB; 3096 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3097 3098 MachineBasicBlock::iterator Prev = std::prev(MI.getIterator()); 3099 3100 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3101 3102 MachineBasicBlock::iterator I = LoopBB->end(); 3103 MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 3104 3105 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3106 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3107 3108 // Clear TRAP_STS.MEM_VIOL 3109 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3110 .addImm(0) 3111 .addImm(EncodedReg); 3112 3113 // This is a pain, but we're not allowed to have physical register live-ins 3114 // yet. Insert a pair of copies if the VGPR0 hack is necessary. 3115 if (Src && TargetRegisterInfo::isPhysicalRegister(Src->getReg())) { 3116 unsigned Data0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3117 BuildMI(*BB, std::next(Prev), DL, TII->get(AMDGPU::COPY), Data0) 3118 .add(*Src); 3119 3120 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::COPY), Src->getReg()) 3121 .addReg(Data0); 3122 3123 MRI.setSimpleHint(Data0, Src->getReg()); 3124 } 3125 3126 bundleInstWithWaitcnt(MI); 3127 3128 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3129 3130 // Load and check TRAP_STS.MEM_VIOL 3131 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3132 .addImm(EncodedReg); 3133 3134 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3135 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3136 .addReg(Reg, RegState::Kill) 3137 .addImm(0); 3138 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3139 .addMBB(LoopBB); 3140 3141 return RemainderBB; 3142 } 3143 3144 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3145 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3146 // will only do one iteration. In the worst case, this will loop 64 times. 3147 // 3148 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3149 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3150 const SIInstrInfo *TII, 3151 MachineRegisterInfo &MRI, 3152 MachineBasicBlock &OrigBB, 3153 MachineBasicBlock &LoopBB, 3154 const DebugLoc &DL, 3155 const MachineOperand &IdxReg, 3156 unsigned InitReg, 3157 unsigned ResultReg, 3158 unsigned PhiReg, 3159 unsigned InitSaveExecReg, 3160 int Offset, 3161 bool UseGPRIdxMode, 3162 bool IsIndirectSrc) { 3163 MachineFunction *MF = OrigBB.getParent(); 3164 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3165 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3166 MachineBasicBlock::iterator I = LoopBB.begin(); 3167 3168 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3169 unsigned PhiExec = MRI.createVirtualRegister(BoolRC); 3170 unsigned NewExec = MRI.createVirtualRegister(BoolRC); 3171 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3172 unsigned CondReg = MRI.createVirtualRegister(BoolRC); 3173 3174 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3175 .addReg(InitReg) 3176 .addMBB(&OrigBB) 3177 .addReg(ResultReg) 3178 .addMBB(&LoopBB); 3179 3180 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3181 .addReg(InitSaveExecReg) 3182 .addMBB(&OrigBB) 3183 .addReg(NewExec) 3184 .addMBB(&LoopBB); 3185 3186 // Read the next variant <- also loop target. 3187 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3188 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3189 3190 // Compare the just read M0 value to all possible Idx values. 3191 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3192 .addReg(CurrentIdxReg) 3193 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3194 3195 // Update EXEC, save the original EXEC value to VCC. 3196 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3197 : AMDGPU::S_AND_SAVEEXEC_B64), 3198 NewExec) 3199 .addReg(CondReg, RegState::Kill); 3200 3201 MRI.setSimpleHint(NewExec, CondReg); 3202 3203 if (UseGPRIdxMode) { 3204 unsigned IdxReg; 3205 if (Offset == 0) { 3206 IdxReg = CurrentIdxReg; 3207 } else { 3208 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3209 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3210 .addReg(CurrentIdxReg, RegState::Kill) 3211 .addImm(Offset); 3212 } 3213 unsigned IdxMode = IsIndirectSrc ? 3214 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3215 MachineInstr *SetOn = 3216 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3217 .addReg(IdxReg, RegState::Kill) 3218 .addImm(IdxMode); 3219 SetOn->getOperand(3).setIsUndef(); 3220 } else { 3221 // Move index from VCC into M0 3222 if (Offset == 0) { 3223 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3224 .addReg(CurrentIdxReg, RegState::Kill); 3225 } else { 3226 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3227 .addReg(CurrentIdxReg, RegState::Kill) 3228 .addImm(Offset); 3229 } 3230 } 3231 3232 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3233 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3234 MachineInstr *InsertPt = 3235 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3236 : AMDGPU::S_XOR_B64_term), Exec) 3237 .addReg(Exec) 3238 .addReg(NewExec); 3239 3240 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3241 // s_cbranch_scc0? 3242 3243 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3244 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3245 .addMBB(&LoopBB); 3246 3247 return InsertPt->getIterator(); 3248 } 3249 3250 // This has slightly sub-optimal regalloc when the source vector is killed by 3251 // the read. The register allocator does not understand that the kill is 3252 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3253 // subregister from it, using 1 more VGPR than necessary. This was saved when 3254 // this was expanded after register allocation. 3255 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3256 MachineBasicBlock &MBB, 3257 MachineInstr &MI, 3258 unsigned InitResultReg, 3259 unsigned PhiReg, 3260 int Offset, 3261 bool UseGPRIdxMode, 3262 bool IsIndirectSrc) { 3263 MachineFunction *MF = MBB.getParent(); 3264 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3265 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3266 MachineRegisterInfo &MRI = MF->getRegInfo(); 3267 const DebugLoc &DL = MI.getDebugLoc(); 3268 MachineBasicBlock::iterator I(&MI); 3269 3270 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3271 unsigned DstReg = MI.getOperand(0).getReg(); 3272 unsigned SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3273 unsigned TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3274 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3275 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3276 3277 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3278 3279 // Save the EXEC mask 3280 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3281 .addReg(Exec); 3282 3283 MachineBasicBlock *LoopBB; 3284 MachineBasicBlock *RemainderBB; 3285 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3286 3287 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3288 3289 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3290 InitResultReg, DstReg, PhiReg, TmpExec, 3291 Offset, UseGPRIdxMode, IsIndirectSrc); 3292 3293 MachineBasicBlock::iterator First = RemainderBB->begin(); 3294 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3295 .addReg(SaveExec); 3296 3297 return InsPt; 3298 } 3299 3300 // Returns subreg index, offset 3301 static std::pair<unsigned, int> 3302 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3303 const TargetRegisterClass *SuperRC, 3304 unsigned VecReg, 3305 int Offset) { 3306 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3307 3308 // Skip out of bounds offsets, or else we would end up using an undefined 3309 // register. 3310 if (Offset >= NumElts || Offset < 0) 3311 return std::make_pair(AMDGPU::sub0, Offset); 3312 3313 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3314 } 3315 3316 // Return true if the index is an SGPR and was set. 3317 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3318 MachineRegisterInfo &MRI, 3319 MachineInstr &MI, 3320 int Offset, 3321 bool UseGPRIdxMode, 3322 bool IsIndirectSrc) { 3323 MachineBasicBlock *MBB = MI.getParent(); 3324 const DebugLoc &DL = MI.getDebugLoc(); 3325 MachineBasicBlock::iterator I(&MI); 3326 3327 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3328 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3329 3330 assert(Idx->getReg() != AMDGPU::NoRegister); 3331 3332 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3333 return false; 3334 3335 if (UseGPRIdxMode) { 3336 unsigned IdxMode = IsIndirectSrc ? 3337 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3338 if (Offset == 0) { 3339 MachineInstr *SetOn = 3340 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3341 .add(*Idx) 3342 .addImm(IdxMode); 3343 3344 SetOn->getOperand(3).setIsUndef(); 3345 } else { 3346 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3347 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3348 .add(*Idx) 3349 .addImm(Offset); 3350 MachineInstr *SetOn = 3351 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3352 .addReg(Tmp, RegState::Kill) 3353 .addImm(IdxMode); 3354 3355 SetOn->getOperand(3).setIsUndef(); 3356 } 3357 3358 return true; 3359 } 3360 3361 if (Offset == 0) { 3362 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3363 .add(*Idx); 3364 } else { 3365 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3366 .add(*Idx) 3367 .addImm(Offset); 3368 } 3369 3370 return true; 3371 } 3372 3373 // Control flow needs to be inserted if indexing with a VGPR. 3374 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3375 MachineBasicBlock &MBB, 3376 const GCNSubtarget &ST) { 3377 const SIInstrInfo *TII = ST.getInstrInfo(); 3378 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3379 MachineFunction *MF = MBB.getParent(); 3380 MachineRegisterInfo &MRI = MF->getRegInfo(); 3381 3382 unsigned Dst = MI.getOperand(0).getReg(); 3383 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3384 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3385 3386 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3387 3388 unsigned SubReg; 3389 std::tie(SubReg, Offset) 3390 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3391 3392 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3393 3394 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3395 MachineBasicBlock::iterator I(&MI); 3396 const DebugLoc &DL = MI.getDebugLoc(); 3397 3398 if (UseGPRIdxMode) { 3399 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3400 // to avoid interfering with other uses, so probably requires a new 3401 // optimization pass. 3402 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3403 .addReg(SrcReg, RegState::Undef, SubReg) 3404 .addReg(SrcReg, RegState::Implicit) 3405 .addReg(AMDGPU::M0, RegState::Implicit); 3406 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3407 } else { 3408 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3409 .addReg(SrcReg, RegState::Undef, SubReg) 3410 .addReg(SrcReg, RegState::Implicit); 3411 } 3412 3413 MI.eraseFromParent(); 3414 3415 return &MBB; 3416 } 3417 3418 const DebugLoc &DL = MI.getDebugLoc(); 3419 MachineBasicBlock::iterator I(&MI); 3420 3421 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3422 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3423 3424 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3425 3426 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3427 Offset, UseGPRIdxMode, true); 3428 MachineBasicBlock *LoopBB = InsPt->getParent(); 3429 3430 if (UseGPRIdxMode) { 3431 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3432 .addReg(SrcReg, RegState::Undef, SubReg) 3433 .addReg(SrcReg, RegState::Implicit) 3434 .addReg(AMDGPU::M0, RegState::Implicit); 3435 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3436 } else { 3437 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3438 .addReg(SrcReg, RegState::Undef, SubReg) 3439 .addReg(SrcReg, RegState::Implicit); 3440 } 3441 3442 MI.eraseFromParent(); 3443 3444 return LoopBB; 3445 } 3446 3447 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3448 const TargetRegisterClass *VecRC) { 3449 switch (TRI.getRegSizeInBits(*VecRC)) { 3450 case 32: // 4 bytes 3451 return AMDGPU::V_MOVRELD_B32_V1; 3452 case 64: // 8 bytes 3453 return AMDGPU::V_MOVRELD_B32_V2; 3454 case 128: // 16 bytes 3455 return AMDGPU::V_MOVRELD_B32_V4; 3456 case 256: // 32 bytes 3457 return AMDGPU::V_MOVRELD_B32_V8; 3458 case 512: // 64 bytes 3459 return AMDGPU::V_MOVRELD_B32_V16; 3460 default: 3461 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3462 } 3463 } 3464 3465 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3466 MachineBasicBlock &MBB, 3467 const GCNSubtarget &ST) { 3468 const SIInstrInfo *TII = ST.getInstrInfo(); 3469 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3470 MachineFunction *MF = MBB.getParent(); 3471 MachineRegisterInfo &MRI = MF->getRegInfo(); 3472 3473 unsigned Dst = MI.getOperand(0).getReg(); 3474 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3475 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3476 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3477 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3478 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3479 3480 // This can be an immediate, but will be folded later. 3481 assert(Val->getReg()); 3482 3483 unsigned SubReg; 3484 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3485 SrcVec->getReg(), 3486 Offset); 3487 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3488 3489 if (Idx->getReg() == AMDGPU::NoRegister) { 3490 MachineBasicBlock::iterator I(&MI); 3491 const DebugLoc &DL = MI.getDebugLoc(); 3492 3493 assert(Offset == 0); 3494 3495 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3496 .add(*SrcVec) 3497 .add(*Val) 3498 .addImm(SubReg); 3499 3500 MI.eraseFromParent(); 3501 return &MBB; 3502 } 3503 3504 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3505 MachineBasicBlock::iterator I(&MI); 3506 const DebugLoc &DL = MI.getDebugLoc(); 3507 3508 if (UseGPRIdxMode) { 3509 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3510 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3511 .add(*Val) 3512 .addReg(Dst, RegState::ImplicitDefine) 3513 .addReg(SrcVec->getReg(), RegState::Implicit) 3514 .addReg(AMDGPU::M0, RegState::Implicit); 3515 3516 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3517 } else { 3518 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3519 3520 BuildMI(MBB, I, DL, MovRelDesc) 3521 .addReg(Dst, RegState::Define) 3522 .addReg(SrcVec->getReg()) 3523 .add(*Val) 3524 .addImm(SubReg - AMDGPU::sub0); 3525 } 3526 3527 MI.eraseFromParent(); 3528 return &MBB; 3529 } 3530 3531 if (Val->isReg()) 3532 MRI.clearKillFlags(Val->getReg()); 3533 3534 const DebugLoc &DL = MI.getDebugLoc(); 3535 3536 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 3537 3538 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3539 Offset, UseGPRIdxMode, false); 3540 MachineBasicBlock *LoopBB = InsPt->getParent(); 3541 3542 if (UseGPRIdxMode) { 3543 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3544 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3545 .add(*Val) // src0 3546 .addReg(Dst, RegState::ImplicitDefine) 3547 .addReg(PhiReg, RegState::Implicit) 3548 .addReg(AMDGPU::M0, RegState::Implicit); 3549 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3550 } else { 3551 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3552 3553 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3554 .addReg(Dst, RegState::Define) 3555 .addReg(PhiReg) 3556 .add(*Val) 3557 .addImm(SubReg - AMDGPU::sub0); 3558 } 3559 3560 MI.eraseFromParent(); 3561 3562 return LoopBB; 3563 } 3564 3565 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3566 MachineInstr &MI, MachineBasicBlock *BB) const { 3567 3568 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3569 MachineFunction *MF = BB->getParent(); 3570 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3571 3572 if (TII->isMIMG(MI)) { 3573 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3574 report_fatal_error("missing mem operand from MIMG instruction"); 3575 } 3576 // Add a memoperand for mimg instructions so that they aren't assumed to 3577 // be ordered memory instuctions. 3578 3579 return BB; 3580 } 3581 3582 switch (MI.getOpcode()) { 3583 case AMDGPU::S_ADD_U64_PSEUDO: 3584 case AMDGPU::S_SUB_U64_PSEUDO: { 3585 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3586 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3587 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3588 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3589 const DebugLoc &DL = MI.getDebugLoc(); 3590 3591 MachineOperand &Dest = MI.getOperand(0); 3592 MachineOperand &Src0 = MI.getOperand(1); 3593 MachineOperand &Src1 = MI.getOperand(2); 3594 3595 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3596 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3597 3598 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3599 Src0, BoolRC, AMDGPU::sub0, 3600 &AMDGPU::SReg_32_XM0RegClass); 3601 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3602 Src0, BoolRC, AMDGPU::sub1, 3603 &AMDGPU::SReg_32_XM0RegClass); 3604 3605 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3606 Src1, BoolRC, AMDGPU::sub0, 3607 &AMDGPU::SReg_32_XM0RegClass); 3608 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3609 Src1, BoolRC, AMDGPU::sub1, 3610 &AMDGPU::SReg_32_XM0RegClass); 3611 3612 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3613 3614 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3615 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3616 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3617 .add(Src0Sub0) 3618 .add(Src1Sub0); 3619 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3620 .add(Src0Sub1) 3621 .add(Src1Sub1); 3622 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3623 .addReg(DestSub0) 3624 .addImm(AMDGPU::sub0) 3625 .addReg(DestSub1) 3626 .addImm(AMDGPU::sub1); 3627 MI.eraseFromParent(); 3628 return BB; 3629 } 3630 case AMDGPU::SI_INIT_M0: { 3631 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3632 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3633 .add(MI.getOperand(0)); 3634 MI.eraseFromParent(); 3635 return BB; 3636 } 3637 case AMDGPU::SI_INIT_EXEC: 3638 // This should be before all vector instructions. 3639 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3640 AMDGPU::EXEC) 3641 .addImm(MI.getOperand(0).getImm()); 3642 MI.eraseFromParent(); 3643 return BB; 3644 3645 case AMDGPU::SI_INIT_EXEC_LO: 3646 // This should be before all vector instructions. 3647 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3648 AMDGPU::EXEC_LO) 3649 .addImm(MI.getOperand(0).getImm()); 3650 MI.eraseFromParent(); 3651 return BB; 3652 3653 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3654 // Extract the thread count from an SGPR input and set EXEC accordingly. 3655 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3656 // 3657 // S_BFE_U32 count, input, {shift, 7} 3658 // S_BFM_B64 exec, count, 0 3659 // S_CMP_EQ_U32 count, 64 3660 // S_CMOV_B64 exec, -1 3661 MachineInstr *FirstMI = &*BB->begin(); 3662 MachineRegisterInfo &MRI = MF->getRegInfo(); 3663 unsigned InputReg = MI.getOperand(0).getReg(); 3664 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3665 bool Found = false; 3666 3667 // Move the COPY of the input reg to the beginning, so that we can use it. 3668 for (auto I = BB->begin(); I != &MI; I++) { 3669 if (I->getOpcode() != TargetOpcode::COPY || 3670 I->getOperand(0).getReg() != InputReg) 3671 continue; 3672 3673 if (I == FirstMI) { 3674 FirstMI = &*++BB->begin(); 3675 } else { 3676 I->removeFromParent(); 3677 BB->insert(FirstMI, &*I); 3678 } 3679 Found = true; 3680 break; 3681 } 3682 assert(Found); 3683 (void)Found; 3684 3685 // This should be before all vector instructions. 3686 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3687 bool isWave32 = getSubtarget()->isWave32(); 3688 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3689 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3690 .addReg(InputReg) 3691 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3692 BuildMI(*BB, FirstMI, DebugLoc(), 3693 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3694 Exec) 3695 .addReg(CountReg) 3696 .addImm(0); 3697 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3698 .addReg(CountReg, RegState::Kill) 3699 .addImm(getSubtarget()->getWavefrontSize()); 3700 BuildMI(*BB, FirstMI, DebugLoc(), 3701 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3702 Exec) 3703 .addImm(-1); 3704 MI.eraseFromParent(); 3705 return BB; 3706 } 3707 3708 case AMDGPU::GET_GROUPSTATICSIZE: { 3709 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3710 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3711 DebugLoc DL = MI.getDebugLoc(); 3712 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3713 .add(MI.getOperand(0)) 3714 .addImm(MFI->getLDSSize()); 3715 MI.eraseFromParent(); 3716 return BB; 3717 } 3718 case AMDGPU::SI_INDIRECT_SRC_V1: 3719 case AMDGPU::SI_INDIRECT_SRC_V2: 3720 case AMDGPU::SI_INDIRECT_SRC_V4: 3721 case AMDGPU::SI_INDIRECT_SRC_V8: 3722 case AMDGPU::SI_INDIRECT_SRC_V16: 3723 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3724 case AMDGPU::SI_INDIRECT_DST_V1: 3725 case AMDGPU::SI_INDIRECT_DST_V2: 3726 case AMDGPU::SI_INDIRECT_DST_V4: 3727 case AMDGPU::SI_INDIRECT_DST_V8: 3728 case AMDGPU::SI_INDIRECT_DST_V16: 3729 return emitIndirectDst(MI, *BB, *getSubtarget()); 3730 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3731 case AMDGPU::SI_KILL_I1_PSEUDO: 3732 return splitKillBlock(MI, BB); 3733 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3734 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3735 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3736 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3737 3738 unsigned Dst = MI.getOperand(0).getReg(); 3739 unsigned Src0 = MI.getOperand(1).getReg(); 3740 unsigned Src1 = MI.getOperand(2).getReg(); 3741 const DebugLoc &DL = MI.getDebugLoc(); 3742 unsigned SrcCond = MI.getOperand(3).getReg(); 3743 3744 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3745 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3746 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3747 unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC); 3748 3749 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3750 .addReg(SrcCond); 3751 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3752 .addImm(0) 3753 .addReg(Src0, 0, AMDGPU::sub0) 3754 .addImm(0) 3755 .addReg(Src1, 0, AMDGPU::sub0) 3756 .addReg(SrcCondCopy); 3757 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3758 .addImm(0) 3759 .addReg(Src0, 0, AMDGPU::sub1) 3760 .addImm(0) 3761 .addReg(Src1, 0, AMDGPU::sub1) 3762 .addReg(SrcCondCopy); 3763 3764 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3765 .addReg(DstLo) 3766 .addImm(AMDGPU::sub0) 3767 .addReg(DstHi) 3768 .addImm(AMDGPU::sub1); 3769 MI.eraseFromParent(); 3770 return BB; 3771 } 3772 case AMDGPU::SI_BR_UNDEF: { 3773 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3774 const DebugLoc &DL = MI.getDebugLoc(); 3775 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3776 .add(MI.getOperand(0)); 3777 Br->getOperand(1).setIsUndef(true); // read undef SCC 3778 MI.eraseFromParent(); 3779 return BB; 3780 } 3781 case AMDGPU::ADJCALLSTACKUP: 3782 case AMDGPU::ADJCALLSTACKDOWN: { 3783 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3784 MachineInstrBuilder MIB(*MF, &MI); 3785 3786 // Add an implicit use of the frame offset reg to prevent the restore copy 3787 // inserted after the call from being reorderd after stack operations in the 3788 // the caller's frame. 3789 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3790 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3791 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3792 return BB; 3793 } 3794 case AMDGPU::SI_CALL_ISEL: { 3795 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3796 const DebugLoc &DL = MI.getDebugLoc(); 3797 3798 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3799 3800 MachineInstrBuilder MIB; 3801 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3802 3803 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3804 MIB.add(MI.getOperand(I)); 3805 3806 MIB.cloneMemRefs(MI); 3807 MI.eraseFromParent(); 3808 return BB; 3809 } 3810 case AMDGPU::V_ADD_I32_e32: 3811 case AMDGPU::V_SUB_I32_e32: 3812 case AMDGPU::V_SUBREV_I32_e32: { 3813 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3814 const DebugLoc &DL = MI.getDebugLoc(); 3815 unsigned Opc = MI.getOpcode(); 3816 3817 bool NeedClampOperand = false; 3818 if (TII->pseudoToMCOpcode(Opc) == -1) { 3819 Opc = AMDGPU::getVOPe64(Opc); 3820 NeedClampOperand = true; 3821 } 3822 3823 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3824 if (TII->isVOP3(*I)) { 3825 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3826 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3827 I.addReg(TRI->getVCC(), RegState::Define); 3828 } 3829 I.add(MI.getOperand(1)) 3830 .add(MI.getOperand(2)); 3831 if (NeedClampOperand) 3832 I.addImm(0); // clamp bit for e64 encoding 3833 3834 TII->legalizeOperands(*I); 3835 3836 MI.eraseFromParent(); 3837 return BB; 3838 } 3839 case AMDGPU::DS_GWS_INIT: 3840 case AMDGPU::DS_GWS_SEMA_V: 3841 case AMDGPU::DS_GWS_SEMA_BR: 3842 case AMDGPU::DS_GWS_SEMA_P: 3843 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3844 case AMDGPU::DS_GWS_BARRIER: 3845 // A s_waitcnt 0 is required to be the instruction immediately following. 3846 if (getSubtarget()->hasGWSAutoReplay()) { 3847 bundleInstWithWaitcnt(MI); 3848 return BB; 3849 } 3850 3851 return emitGWSMemViolTestLoop(MI, BB); 3852 default: 3853 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3854 } 3855 } 3856 3857 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3858 return isTypeLegal(VT.getScalarType()); 3859 } 3860 3861 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3862 // This currently forces unfolding various combinations of fsub into fma with 3863 // free fneg'd operands. As long as we have fast FMA (controlled by 3864 // isFMAFasterThanFMulAndFAdd), we should perform these. 3865 3866 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3867 // most of these combines appear to be cycle neutral but save on instruction 3868 // count / code size. 3869 return true; 3870 } 3871 3872 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3873 EVT VT) const { 3874 if (!VT.isVector()) { 3875 return MVT::i1; 3876 } 3877 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3878 } 3879 3880 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3881 // TODO: Should i16 be used always if legal? For now it would force VALU 3882 // shifts. 3883 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3884 } 3885 3886 // Answering this is somewhat tricky and depends on the specific device which 3887 // have different rates for fma or all f64 operations. 3888 // 3889 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3890 // regardless of which device (although the number of cycles differs between 3891 // devices), so it is always profitable for f64. 3892 // 3893 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3894 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3895 // which we can always do even without fused FP ops since it returns the same 3896 // result as the separate operations and since it is always full 3897 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3898 // however does not support denormals, so we do report fma as faster if we have 3899 // a fast fma device and require denormals. 3900 // 3901 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3902 VT = VT.getScalarType(); 3903 3904 switch (VT.getSimpleVT().SimpleTy) { 3905 case MVT::f32: { 3906 // This is as fast on some subtargets. However, we always have full rate f32 3907 // mad available which returns the same result as the separate operations 3908 // which we should prefer over fma. We can't use this if we want to support 3909 // denormals, so only report this in these cases. 3910 if (Subtarget->hasFP32Denormals()) 3911 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3912 3913 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3914 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3915 } 3916 case MVT::f64: 3917 return true; 3918 case MVT::f16: 3919 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3920 default: 3921 break; 3922 } 3923 3924 return false; 3925 } 3926 3927 //===----------------------------------------------------------------------===// 3928 // Custom DAG Lowering Operations 3929 //===----------------------------------------------------------------------===// 3930 3931 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3932 // wider vector type is legal. 3933 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3934 SelectionDAG &DAG) const { 3935 unsigned Opc = Op.getOpcode(); 3936 EVT VT = Op.getValueType(); 3937 assert(VT == MVT::v4f16); 3938 3939 SDValue Lo, Hi; 3940 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3941 3942 SDLoc SL(Op); 3943 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3944 Op->getFlags()); 3945 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3946 Op->getFlags()); 3947 3948 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3949 } 3950 3951 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3952 // wider vector type is legal. 3953 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3954 SelectionDAG &DAG) const { 3955 unsigned Opc = Op.getOpcode(); 3956 EVT VT = Op.getValueType(); 3957 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3958 3959 SDValue Lo0, Hi0; 3960 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3961 SDValue Lo1, Hi1; 3962 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3963 3964 SDLoc SL(Op); 3965 3966 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3967 Op->getFlags()); 3968 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3969 Op->getFlags()); 3970 3971 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3972 } 3973 3974 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3975 switch (Op.getOpcode()) { 3976 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3977 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3978 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 3979 case ISD::LOAD: { 3980 SDValue Result = LowerLOAD(Op, DAG); 3981 assert((!Result.getNode() || 3982 Result.getNode()->getNumValues() == 2) && 3983 "Load should return a value and a chain"); 3984 return Result; 3985 } 3986 3987 case ISD::FSIN: 3988 case ISD::FCOS: 3989 return LowerTrig(Op, DAG); 3990 case ISD::SELECT: return LowerSELECT(Op, DAG); 3991 case ISD::FDIV: return LowerFDIV(Op, DAG); 3992 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3993 case ISD::STORE: return LowerSTORE(Op, DAG); 3994 case ISD::GlobalAddress: { 3995 MachineFunction &MF = DAG.getMachineFunction(); 3996 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3997 return LowerGlobalAddress(MFI, Op, DAG); 3998 } 3999 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4000 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4001 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4002 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4003 case ISD::INSERT_SUBVECTOR: 4004 return lowerINSERT_SUBVECTOR(Op, DAG); 4005 case ISD::INSERT_VECTOR_ELT: 4006 return lowerINSERT_VECTOR_ELT(Op, DAG); 4007 case ISD::EXTRACT_VECTOR_ELT: 4008 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4009 case ISD::VECTOR_SHUFFLE: 4010 return lowerVECTOR_SHUFFLE(Op, DAG); 4011 case ISD::BUILD_VECTOR: 4012 return lowerBUILD_VECTOR(Op, DAG); 4013 case ISD::FP_ROUND: 4014 return lowerFP_ROUND(Op, DAG); 4015 case ISD::TRAP: 4016 return lowerTRAP(Op, DAG); 4017 case ISD::DEBUGTRAP: 4018 return lowerDEBUGTRAP(Op, DAG); 4019 case ISD::FABS: 4020 case ISD::FNEG: 4021 case ISD::FCANONICALIZE: 4022 return splitUnaryVectorOp(Op, DAG); 4023 case ISD::FMINNUM: 4024 case ISD::FMAXNUM: 4025 return lowerFMINNUM_FMAXNUM(Op, DAG); 4026 case ISD::SHL: 4027 case ISD::SRA: 4028 case ISD::SRL: 4029 case ISD::ADD: 4030 case ISD::SUB: 4031 case ISD::MUL: 4032 case ISD::SMIN: 4033 case ISD::SMAX: 4034 case ISD::UMIN: 4035 case ISD::UMAX: 4036 case ISD::FADD: 4037 case ISD::FMUL: 4038 case ISD::FMINNUM_IEEE: 4039 case ISD::FMAXNUM_IEEE: 4040 return splitBinaryVectorOp(Op, DAG); 4041 } 4042 return SDValue(); 4043 } 4044 4045 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4046 const SDLoc &DL, 4047 SelectionDAG &DAG, bool Unpacked) { 4048 if (!LoadVT.isVector()) 4049 return Result; 4050 4051 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4052 // Truncate to v2i16/v4i16. 4053 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4054 4055 // Workaround legalizer not scalarizing truncate after vector op 4056 // legalization byt not creating intermediate vector trunc. 4057 SmallVector<SDValue, 4> Elts; 4058 DAG.ExtractVectorElements(Result, Elts); 4059 for (SDValue &Elt : Elts) 4060 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4061 4062 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4063 4064 // Bitcast to original type (v2f16/v4f16). 4065 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4066 } 4067 4068 // Cast back to the original packed type. 4069 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4070 } 4071 4072 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4073 MemSDNode *M, 4074 SelectionDAG &DAG, 4075 ArrayRef<SDValue> Ops, 4076 bool IsIntrinsic) const { 4077 SDLoc DL(M); 4078 4079 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4080 EVT LoadVT = M->getValueType(0); 4081 4082 EVT EquivLoadVT = LoadVT; 4083 if (Unpacked && LoadVT.isVector()) { 4084 EquivLoadVT = LoadVT.isVector() ? 4085 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4086 LoadVT.getVectorNumElements()) : LoadVT; 4087 } 4088 4089 // Change from v4f16/v2f16 to EquivLoadVT. 4090 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4091 4092 SDValue Load 4093 = DAG.getMemIntrinsicNode( 4094 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4095 VTList, Ops, M->getMemoryVT(), 4096 M->getMemOperand()); 4097 if (!Unpacked) // Just adjusted the opcode. 4098 return Load; 4099 4100 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4101 4102 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4103 } 4104 4105 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4106 SDNode *N, SelectionDAG &DAG) { 4107 EVT VT = N->getValueType(0); 4108 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4109 int CondCode = CD->getSExtValue(); 4110 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4111 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4112 return DAG.getUNDEF(VT); 4113 4114 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4115 4116 SDValue LHS = N->getOperand(1); 4117 SDValue RHS = N->getOperand(2); 4118 4119 SDLoc DL(N); 4120 4121 EVT CmpVT = LHS.getValueType(); 4122 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4123 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4124 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4125 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4126 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4127 } 4128 4129 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4130 4131 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4132 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4133 4134 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4135 DAG.getCondCode(CCOpcode)); 4136 if (VT.bitsEq(CCVT)) 4137 return SetCC; 4138 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4139 } 4140 4141 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4142 SDNode *N, SelectionDAG &DAG) { 4143 EVT VT = N->getValueType(0); 4144 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4145 4146 int CondCode = CD->getSExtValue(); 4147 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4148 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4149 return DAG.getUNDEF(VT); 4150 } 4151 4152 SDValue Src0 = N->getOperand(1); 4153 SDValue Src1 = N->getOperand(2); 4154 EVT CmpVT = Src0.getValueType(); 4155 SDLoc SL(N); 4156 4157 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4158 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4159 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4160 } 4161 4162 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4163 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4164 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4165 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4166 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4167 Src1, DAG.getCondCode(CCOpcode)); 4168 if (VT.bitsEq(CCVT)) 4169 return SetCC; 4170 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4171 } 4172 4173 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4174 SmallVectorImpl<SDValue> &Results, 4175 SelectionDAG &DAG) const { 4176 switch (N->getOpcode()) { 4177 case ISD::INSERT_VECTOR_ELT: { 4178 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4179 Results.push_back(Res); 4180 return; 4181 } 4182 case ISD::EXTRACT_VECTOR_ELT: { 4183 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4184 Results.push_back(Res); 4185 return; 4186 } 4187 case ISD::INTRINSIC_WO_CHAIN: { 4188 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4189 switch (IID) { 4190 case Intrinsic::amdgcn_cvt_pkrtz: { 4191 SDValue Src0 = N->getOperand(1); 4192 SDValue Src1 = N->getOperand(2); 4193 SDLoc SL(N); 4194 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4195 Src0, Src1); 4196 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4197 return; 4198 } 4199 case Intrinsic::amdgcn_cvt_pknorm_i16: 4200 case Intrinsic::amdgcn_cvt_pknorm_u16: 4201 case Intrinsic::amdgcn_cvt_pk_i16: 4202 case Intrinsic::amdgcn_cvt_pk_u16: { 4203 SDValue Src0 = N->getOperand(1); 4204 SDValue Src1 = N->getOperand(2); 4205 SDLoc SL(N); 4206 unsigned Opcode; 4207 4208 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4209 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4210 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4211 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4212 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4213 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4214 else 4215 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4216 4217 EVT VT = N->getValueType(0); 4218 if (isTypeLegal(VT)) 4219 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4220 else { 4221 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4222 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4223 } 4224 return; 4225 } 4226 } 4227 break; 4228 } 4229 case ISD::INTRINSIC_W_CHAIN: { 4230 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4231 Results.push_back(Res); 4232 Results.push_back(Res.getValue(1)); 4233 return; 4234 } 4235 4236 break; 4237 } 4238 case ISD::SELECT: { 4239 SDLoc SL(N); 4240 EVT VT = N->getValueType(0); 4241 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4242 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4243 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4244 4245 EVT SelectVT = NewVT; 4246 if (NewVT.bitsLT(MVT::i32)) { 4247 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4248 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4249 SelectVT = MVT::i32; 4250 } 4251 4252 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4253 N->getOperand(0), LHS, RHS); 4254 4255 if (NewVT != SelectVT) 4256 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4257 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4258 return; 4259 } 4260 case ISD::FNEG: { 4261 if (N->getValueType(0) != MVT::v2f16) 4262 break; 4263 4264 SDLoc SL(N); 4265 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4266 4267 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4268 BC, 4269 DAG.getConstant(0x80008000, SL, MVT::i32)); 4270 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4271 return; 4272 } 4273 case ISD::FABS: { 4274 if (N->getValueType(0) != MVT::v2f16) 4275 break; 4276 4277 SDLoc SL(N); 4278 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4279 4280 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4281 BC, 4282 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4283 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4284 return; 4285 } 4286 default: 4287 break; 4288 } 4289 } 4290 4291 /// Helper function for LowerBRCOND 4292 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4293 4294 SDNode *Parent = Value.getNode(); 4295 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4296 I != E; ++I) { 4297 4298 if (I.getUse().get() != Value) 4299 continue; 4300 4301 if (I->getOpcode() == Opcode) 4302 return *I; 4303 } 4304 return nullptr; 4305 } 4306 4307 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4308 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4309 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4310 case Intrinsic::amdgcn_if: 4311 return AMDGPUISD::IF; 4312 case Intrinsic::amdgcn_else: 4313 return AMDGPUISD::ELSE; 4314 case Intrinsic::amdgcn_loop: 4315 return AMDGPUISD::LOOP; 4316 case Intrinsic::amdgcn_end_cf: 4317 llvm_unreachable("should not occur"); 4318 default: 4319 return 0; 4320 } 4321 } 4322 4323 // break, if_break, else_break are all only used as inputs to loop, not 4324 // directly as branch conditions. 4325 return 0; 4326 } 4327 4328 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4329 const Triple &TT = getTargetMachine().getTargetTriple(); 4330 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4331 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4332 AMDGPU::shouldEmitConstantsToTextSection(TT); 4333 } 4334 4335 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4336 // FIXME: Either avoid relying on address space here or change the default 4337 // address space for functions to avoid the explicit check. 4338 return (GV->getValueType()->isFunctionTy() || 4339 GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4340 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4341 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4342 !shouldEmitFixup(GV) && 4343 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4344 } 4345 4346 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4347 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4348 } 4349 4350 /// This transforms the control flow intrinsics to get the branch destination as 4351 /// last parameter, also switches branch target with BR if the need arise 4352 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4353 SelectionDAG &DAG) const { 4354 SDLoc DL(BRCOND); 4355 4356 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4357 SDValue Target = BRCOND.getOperand(2); 4358 SDNode *BR = nullptr; 4359 SDNode *SetCC = nullptr; 4360 4361 if (Intr->getOpcode() == ISD::SETCC) { 4362 // As long as we negate the condition everything is fine 4363 SetCC = Intr; 4364 Intr = SetCC->getOperand(0).getNode(); 4365 4366 } else { 4367 // Get the target from BR if we don't negate the condition 4368 BR = findUser(BRCOND, ISD::BR); 4369 Target = BR->getOperand(1); 4370 } 4371 4372 // FIXME: This changes the types of the intrinsics instead of introducing new 4373 // nodes with the correct types. 4374 // e.g. llvm.amdgcn.loop 4375 4376 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4377 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4378 4379 unsigned CFNode = isCFIntrinsic(Intr); 4380 if (CFNode == 0) { 4381 // This is a uniform branch so we don't need to legalize. 4382 return BRCOND; 4383 } 4384 4385 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4386 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4387 4388 assert(!SetCC || 4389 (SetCC->getConstantOperandVal(1) == 1 && 4390 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4391 ISD::SETNE)); 4392 4393 // operands of the new intrinsic call 4394 SmallVector<SDValue, 4> Ops; 4395 if (HaveChain) 4396 Ops.push_back(BRCOND.getOperand(0)); 4397 4398 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4399 Ops.push_back(Target); 4400 4401 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4402 4403 // build the new intrinsic call 4404 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4405 4406 if (!HaveChain) { 4407 SDValue Ops[] = { 4408 SDValue(Result, 0), 4409 BRCOND.getOperand(0) 4410 }; 4411 4412 Result = DAG.getMergeValues(Ops, DL).getNode(); 4413 } 4414 4415 if (BR) { 4416 // Give the branch instruction our target 4417 SDValue Ops[] = { 4418 BR->getOperand(0), 4419 BRCOND.getOperand(2) 4420 }; 4421 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4422 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4423 BR = NewBR.getNode(); 4424 } 4425 4426 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4427 4428 // Copy the intrinsic results to registers 4429 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4430 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4431 if (!CopyToReg) 4432 continue; 4433 4434 Chain = DAG.getCopyToReg( 4435 Chain, DL, 4436 CopyToReg->getOperand(1), 4437 SDValue(Result, i - 1), 4438 SDValue()); 4439 4440 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4441 } 4442 4443 // Remove the old intrinsic from the chain 4444 DAG.ReplaceAllUsesOfValueWith( 4445 SDValue(Intr, Intr->getNumValues() - 1), 4446 Intr->getOperand(0)); 4447 4448 return Chain; 4449 } 4450 4451 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4452 SelectionDAG &DAG) const { 4453 MVT VT = Op.getSimpleValueType(); 4454 SDLoc DL(Op); 4455 // Checking the depth 4456 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4457 return DAG.getConstant(0, DL, VT); 4458 4459 MachineFunction &MF = DAG.getMachineFunction(); 4460 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4461 // Check for kernel and shader functions 4462 if (Info->isEntryFunction()) 4463 return DAG.getConstant(0, DL, VT); 4464 4465 MachineFrameInfo &MFI = MF.getFrameInfo(); 4466 // There is a call to @llvm.returnaddress in this function 4467 MFI.setReturnAddressIsTaken(true); 4468 4469 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4470 // Get the return address reg and mark it as an implicit live-in 4471 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4472 4473 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4474 } 4475 4476 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4477 SDValue Op, 4478 const SDLoc &DL, 4479 EVT VT) const { 4480 return Op.getValueType().bitsLE(VT) ? 4481 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4482 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4483 } 4484 4485 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4486 assert(Op.getValueType() == MVT::f16 && 4487 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4488 4489 SDValue Src = Op.getOperand(0); 4490 EVT SrcVT = Src.getValueType(); 4491 if (SrcVT != MVT::f64) 4492 return Op; 4493 4494 SDLoc DL(Op); 4495 4496 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4497 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4498 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4499 } 4500 4501 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4502 SelectionDAG &DAG) const { 4503 EVT VT = Op.getValueType(); 4504 const MachineFunction &MF = DAG.getMachineFunction(); 4505 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4506 bool IsIEEEMode = Info->getMode().IEEE; 4507 4508 // FIXME: Assert during eslection that this is only selected for 4509 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4510 // mode functions, but this happens to be OK since it's only done in cases 4511 // where there is known no sNaN. 4512 if (IsIEEEMode) 4513 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4514 4515 if (VT == MVT::v4f16) 4516 return splitBinaryVectorOp(Op, DAG); 4517 return Op; 4518 } 4519 4520 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4521 SDLoc SL(Op); 4522 SDValue Chain = Op.getOperand(0); 4523 4524 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4525 !Subtarget->isTrapHandlerEnabled()) 4526 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4527 4528 MachineFunction &MF = DAG.getMachineFunction(); 4529 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4530 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4531 assert(UserSGPR != AMDGPU::NoRegister); 4532 SDValue QueuePtr = CreateLiveInRegister( 4533 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4534 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4535 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4536 QueuePtr, SDValue()); 4537 SDValue Ops[] = { 4538 ToReg, 4539 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4540 SGPR01, 4541 ToReg.getValue(1) 4542 }; 4543 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4544 } 4545 4546 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4547 SDLoc SL(Op); 4548 SDValue Chain = Op.getOperand(0); 4549 MachineFunction &MF = DAG.getMachineFunction(); 4550 4551 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4552 !Subtarget->isTrapHandlerEnabled()) { 4553 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4554 "debugtrap handler not supported", 4555 Op.getDebugLoc(), 4556 DS_Warning); 4557 LLVMContext &Ctx = MF.getFunction().getContext(); 4558 Ctx.diagnose(NoTrap); 4559 return Chain; 4560 } 4561 4562 SDValue Ops[] = { 4563 Chain, 4564 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4565 }; 4566 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4567 } 4568 4569 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4570 SelectionDAG &DAG) const { 4571 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4572 if (Subtarget->hasApertureRegs()) { 4573 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4574 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4575 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4576 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4577 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4578 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4579 unsigned Encoding = 4580 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4581 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4582 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4583 4584 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4585 SDValue ApertureReg = SDValue( 4586 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4587 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4588 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4589 } 4590 4591 MachineFunction &MF = DAG.getMachineFunction(); 4592 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4593 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4594 assert(UserSGPR != AMDGPU::NoRegister); 4595 4596 SDValue QueuePtr = CreateLiveInRegister( 4597 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4598 4599 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4600 // private_segment_aperture_base_hi. 4601 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4602 4603 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4604 4605 // TODO: Use custom target PseudoSourceValue. 4606 // TODO: We should use the value from the IR intrinsic call, but it might not 4607 // be available and how do we get it? 4608 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4609 AMDGPUAS::CONSTANT_ADDRESS)); 4610 4611 MachinePointerInfo PtrInfo(V, StructOffset); 4612 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4613 MinAlign(64, StructOffset), 4614 MachineMemOperand::MODereferenceable | 4615 MachineMemOperand::MOInvariant); 4616 } 4617 4618 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4619 SelectionDAG &DAG) const { 4620 SDLoc SL(Op); 4621 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4622 4623 SDValue Src = ASC->getOperand(0); 4624 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4625 4626 const AMDGPUTargetMachine &TM = 4627 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4628 4629 // flat -> local/private 4630 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4631 unsigned DestAS = ASC->getDestAddressSpace(); 4632 4633 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4634 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4635 unsigned NullVal = TM.getNullPointerValue(DestAS); 4636 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4637 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4638 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4639 4640 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4641 NonNull, Ptr, SegmentNullPtr); 4642 } 4643 } 4644 4645 // local/private -> flat 4646 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4647 unsigned SrcAS = ASC->getSrcAddressSpace(); 4648 4649 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4650 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4651 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4652 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4653 4654 SDValue NonNull 4655 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4656 4657 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4658 SDValue CvtPtr 4659 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4660 4661 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4662 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4663 FlatNullPtr); 4664 } 4665 } 4666 4667 // global <-> flat are no-ops and never emitted. 4668 4669 const MachineFunction &MF = DAG.getMachineFunction(); 4670 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4671 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4672 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4673 4674 return DAG.getUNDEF(ASC->getValueType(0)); 4675 } 4676 4677 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4678 // the small vector and inserting them into the big vector. That is better than 4679 // the default expansion of doing it via a stack slot. Even though the use of 4680 // the stack slot would be optimized away afterwards, the stack slot itself 4681 // remains. 4682 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4683 SelectionDAG &DAG) const { 4684 SDValue Vec = Op.getOperand(0); 4685 SDValue Ins = Op.getOperand(1); 4686 SDValue Idx = Op.getOperand(2); 4687 EVT VecVT = Vec.getValueType(); 4688 EVT InsVT = Ins.getValueType(); 4689 EVT EltVT = VecVT.getVectorElementType(); 4690 unsigned InsNumElts = InsVT.getVectorNumElements(); 4691 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4692 SDLoc SL(Op); 4693 4694 for (unsigned I = 0; I != InsNumElts; ++I) { 4695 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4696 DAG.getConstant(I, SL, MVT::i32)); 4697 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4698 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4699 } 4700 return Vec; 4701 } 4702 4703 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4704 SelectionDAG &DAG) const { 4705 SDValue Vec = Op.getOperand(0); 4706 SDValue InsVal = Op.getOperand(1); 4707 SDValue Idx = Op.getOperand(2); 4708 EVT VecVT = Vec.getValueType(); 4709 EVT EltVT = VecVT.getVectorElementType(); 4710 unsigned VecSize = VecVT.getSizeInBits(); 4711 unsigned EltSize = EltVT.getSizeInBits(); 4712 4713 4714 assert(VecSize <= 64); 4715 4716 unsigned NumElts = VecVT.getVectorNumElements(); 4717 SDLoc SL(Op); 4718 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4719 4720 if (NumElts == 4 && EltSize == 16 && KIdx) { 4721 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4722 4723 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4724 DAG.getConstant(0, SL, MVT::i32)); 4725 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4726 DAG.getConstant(1, SL, MVT::i32)); 4727 4728 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4729 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4730 4731 unsigned Idx = KIdx->getZExtValue(); 4732 bool InsertLo = Idx < 2; 4733 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4734 InsertLo ? LoVec : HiVec, 4735 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4736 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4737 4738 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4739 4740 SDValue Concat = InsertLo ? 4741 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4742 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4743 4744 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4745 } 4746 4747 if (isa<ConstantSDNode>(Idx)) 4748 return SDValue(); 4749 4750 MVT IntVT = MVT::getIntegerVT(VecSize); 4751 4752 // Avoid stack access for dynamic indexing. 4753 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4754 4755 // Create a congruent vector with the target value in each element so that 4756 // the required element can be masked and ORed into the target vector. 4757 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4758 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4759 4760 assert(isPowerOf2_32(EltSize)); 4761 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4762 4763 // Convert vector index to bit-index. 4764 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4765 4766 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4767 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4768 DAG.getConstant(0xffff, SL, IntVT), 4769 ScaledIdx); 4770 4771 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4772 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4773 DAG.getNOT(SL, BFM, IntVT), BCVec); 4774 4775 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4776 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4777 } 4778 4779 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4780 SelectionDAG &DAG) const { 4781 SDLoc SL(Op); 4782 4783 EVT ResultVT = Op.getValueType(); 4784 SDValue Vec = Op.getOperand(0); 4785 SDValue Idx = Op.getOperand(1); 4786 EVT VecVT = Vec.getValueType(); 4787 unsigned VecSize = VecVT.getSizeInBits(); 4788 EVT EltVT = VecVT.getVectorElementType(); 4789 assert(VecSize <= 64); 4790 4791 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4792 4793 // Make sure we do any optimizations that will make it easier to fold 4794 // source modifiers before obscuring it with bit operations. 4795 4796 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4797 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4798 return Combined; 4799 4800 unsigned EltSize = EltVT.getSizeInBits(); 4801 assert(isPowerOf2_32(EltSize)); 4802 4803 MVT IntVT = MVT::getIntegerVT(VecSize); 4804 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4805 4806 // Convert vector index to bit-index (* EltSize) 4807 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4808 4809 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4810 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4811 4812 if (ResultVT == MVT::f16) { 4813 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4814 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4815 } 4816 4817 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4818 } 4819 4820 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4821 assert(Elt % 2 == 0); 4822 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4823 } 4824 4825 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4826 SelectionDAG &DAG) const { 4827 SDLoc SL(Op); 4828 EVT ResultVT = Op.getValueType(); 4829 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4830 4831 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4832 EVT EltVT = PackVT.getVectorElementType(); 4833 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4834 4835 // vector_shuffle <0,1,6,7> lhs, rhs 4836 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4837 // 4838 // vector_shuffle <6,7,2,3> lhs, rhs 4839 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4840 // 4841 // vector_shuffle <6,7,0,1> lhs, rhs 4842 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4843 4844 // Avoid scalarizing when both halves are reading from consecutive elements. 4845 SmallVector<SDValue, 4> Pieces; 4846 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4847 if (elementPairIsContiguous(SVN->getMask(), I)) { 4848 const int Idx = SVN->getMaskElt(I); 4849 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4850 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4851 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4852 PackVT, SVN->getOperand(VecIdx), 4853 DAG.getConstant(EltIdx, SL, MVT::i32)); 4854 Pieces.push_back(SubVec); 4855 } else { 4856 const int Idx0 = SVN->getMaskElt(I); 4857 const int Idx1 = SVN->getMaskElt(I + 1); 4858 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4859 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4860 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4861 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4862 4863 SDValue Vec0 = SVN->getOperand(VecIdx0); 4864 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4865 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4866 4867 SDValue Vec1 = SVN->getOperand(VecIdx1); 4868 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4869 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4870 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4871 } 4872 } 4873 4874 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4875 } 4876 4877 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4878 SelectionDAG &DAG) const { 4879 SDLoc SL(Op); 4880 EVT VT = Op.getValueType(); 4881 4882 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4883 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4884 4885 // Turn into pair of packed build_vectors. 4886 // TODO: Special case for constants that can be materialized with s_mov_b64. 4887 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4888 { Op.getOperand(0), Op.getOperand(1) }); 4889 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4890 { Op.getOperand(2), Op.getOperand(3) }); 4891 4892 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4893 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4894 4895 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4896 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4897 } 4898 4899 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4900 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4901 4902 SDValue Lo = Op.getOperand(0); 4903 SDValue Hi = Op.getOperand(1); 4904 4905 // Avoid adding defined bits with the zero_extend. 4906 if (Hi.isUndef()) { 4907 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4908 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4909 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4910 } 4911 4912 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4913 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4914 4915 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4916 DAG.getConstant(16, SL, MVT::i32)); 4917 if (Lo.isUndef()) 4918 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4919 4920 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4921 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4922 4923 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4924 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4925 } 4926 4927 bool 4928 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4929 // We can fold offsets for anything that doesn't require a GOT relocation. 4930 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4931 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4932 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4933 !shouldEmitGOTReloc(GA->getGlobal()); 4934 } 4935 4936 static SDValue 4937 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4938 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4939 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4940 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4941 // lowered to the following code sequence: 4942 // 4943 // For constant address space: 4944 // s_getpc_b64 s[0:1] 4945 // s_add_u32 s0, s0, $symbol 4946 // s_addc_u32 s1, s1, 0 4947 // 4948 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4949 // a fixup or relocation is emitted to replace $symbol with a literal 4950 // constant, which is a pc-relative offset from the encoding of the $symbol 4951 // operand to the global variable. 4952 // 4953 // For global address space: 4954 // s_getpc_b64 s[0:1] 4955 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4956 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4957 // 4958 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4959 // fixups or relocations are emitted to replace $symbol@*@lo and 4960 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4961 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4962 // operand to the global variable. 4963 // 4964 // What we want here is an offset from the value returned by s_getpc 4965 // (which is the address of the s_add_u32 instruction) to the global 4966 // variable, but since the encoding of $symbol starts 4 bytes after the start 4967 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4968 // small. This requires us to add 4 to the global variable offset in order to 4969 // compute the correct address. 4970 unsigned LoFlags = GAFlags; 4971 if (LoFlags == SIInstrInfo::MO_NONE) 4972 LoFlags = SIInstrInfo::MO_REL32; 4973 SDValue PtrLo = 4974 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags); 4975 SDValue PtrHi; 4976 if (GAFlags == SIInstrInfo::MO_NONE) { 4977 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 4978 } else { 4979 PtrHi = 4980 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 4981 } 4982 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4983 } 4984 4985 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4986 SDValue Op, 4987 SelectionDAG &DAG) const { 4988 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4989 const GlobalValue *GV = GSD->getGlobal(); 4990 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 4991 (!GV->hasExternalLinkage() || 4992 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4993 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 4994 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 4995 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 4996 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4997 4998 SDLoc DL(GSD); 4999 EVT PtrVT = Op.getValueType(); 5000 5001 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5002 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5003 SIInstrInfo::MO_ABS32_LO); 5004 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5005 } 5006 5007 if (shouldEmitFixup(GV)) 5008 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5009 else if (shouldEmitPCReloc(GV)) 5010 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5011 SIInstrInfo::MO_REL32); 5012 5013 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5014 SIInstrInfo::MO_GOTPCREL32); 5015 5016 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5017 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5018 const DataLayout &DataLayout = DAG.getDataLayout(); 5019 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5020 MachinePointerInfo PtrInfo 5021 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5022 5023 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5024 MachineMemOperand::MODereferenceable | 5025 MachineMemOperand::MOInvariant); 5026 } 5027 5028 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5029 const SDLoc &DL, SDValue V) const { 5030 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5031 // the destination register. 5032 // 5033 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5034 // so we will end up with redundant moves to m0. 5035 // 5036 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5037 5038 // A Null SDValue creates a glue result. 5039 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5040 V, Chain); 5041 return SDValue(M0, 0); 5042 } 5043 5044 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5045 SDValue Op, 5046 MVT VT, 5047 unsigned Offset) const { 5048 SDLoc SL(Op); 5049 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5050 DAG.getEntryNode(), Offset, 4, false); 5051 // The local size values will have the hi 16-bits as zero. 5052 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5053 DAG.getValueType(VT)); 5054 } 5055 5056 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5057 EVT VT) { 5058 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5059 "non-hsa intrinsic with hsa target", 5060 DL.getDebugLoc()); 5061 DAG.getContext()->diagnose(BadIntrin); 5062 return DAG.getUNDEF(VT); 5063 } 5064 5065 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5066 EVT VT) { 5067 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5068 "intrinsic not supported on subtarget", 5069 DL.getDebugLoc()); 5070 DAG.getContext()->diagnose(BadIntrin); 5071 return DAG.getUNDEF(VT); 5072 } 5073 5074 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5075 ArrayRef<SDValue> Elts) { 5076 assert(!Elts.empty()); 5077 MVT Type; 5078 unsigned NumElts; 5079 5080 if (Elts.size() == 1) { 5081 Type = MVT::f32; 5082 NumElts = 1; 5083 } else if (Elts.size() == 2) { 5084 Type = MVT::v2f32; 5085 NumElts = 2; 5086 } else if (Elts.size() <= 4) { 5087 Type = MVT::v4f32; 5088 NumElts = 4; 5089 } else if (Elts.size() <= 8) { 5090 Type = MVT::v8f32; 5091 NumElts = 8; 5092 } else { 5093 assert(Elts.size() <= 16); 5094 Type = MVT::v16f32; 5095 NumElts = 16; 5096 } 5097 5098 SmallVector<SDValue, 16> VecElts(NumElts); 5099 for (unsigned i = 0; i < Elts.size(); ++i) { 5100 SDValue Elt = Elts[i]; 5101 if (Elt.getValueType() != MVT::f32) 5102 Elt = DAG.getBitcast(MVT::f32, Elt); 5103 VecElts[i] = Elt; 5104 } 5105 for (unsigned i = Elts.size(); i < NumElts; ++i) 5106 VecElts[i] = DAG.getUNDEF(MVT::f32); 5107 5108 if (NumElts == 1) 5109 return VecElts[0]; 5110 return DAG.getBuildVector(Type, DL, VecElts); 5111 } 5112 5113 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5114 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5115 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5116 5117 uint64_t Value = CachePolicyConst->getZExtValue(); 5118 SDLoc DL(CachePolicy); 5119 if (GLC) { 5120 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5121 Value &= ~(uint64_t)0x1; 5122 } 5123 if (SLC) { 5124 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5125 Value &= ~(uint64_t)0x2; 5126 } 5127 if (DLC) { 5128 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5129 Value &= ~(uint64_t)0x4; 5130 } 5131 5132 return Value == 0; 5133 } 5134 5135 // Re-construct the required return value for a image load intrinsic. 5136 // This is more complicated due to the optional use TexFailCtrl which means the required 5137 // return type is an aggregate 5138 static SDValue constructRetValue(SelectionDAG &DAG, 5139 MachineSDNode *Result, 5140 ArrayRef<EVT> ResultTypes, 5141 bool IsTexFail, bool Unpacked, bool IsD16, 5142 int DMaskPop, int NumVDataDwords, 5143 const SDLoc &DL, LLVMContext &Context) { 5144 // Determine the required return type. This is the same regardless of IsTexFail flag 5145 EVT ReqRetVT = ResultTypes[0]; 5146 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5147 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5148 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5149 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5150 : AdjEltVT 5151 : ReqRetVT; 5152 5153 // Extract data part of the result 5154 // Bitcast the result to the same type as the required return type 5155 int NumElts; 5156 if (IsD16 && !Unpacked) 5157 NumElts = NumVDataDwords << 1; 5158 else 5159 NumElts = NumVDataDwords; 5160 5161 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5162 : AdjEltVT; 5163 5164 // Special case for v6f16. Rather than add support for this, use v3i32 to 5165 // extract the data elements 5166 bool V6F16Special = false; 5167 if (NumElts == 6) { 5168 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5169 DMaskPop >>= 1; 5170 ReqRetNumElts >>= 1; 5171 V6F16Special = true; 5172 AdjVT = MVT::v2i32; 5173 } 5174 5175 SDValue N = SDValue(Result, 0); 5176 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5177 5178 // Iterate over the result 5179 SmallVector<SDValue, 4> BVElts; 5180 5181 if (CastVT.isVector()) { 5182 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5183 } else { 5184 BVElts.push_back(CastRes); 5185 } 5186 int ExtraElts = ReqRetNumElts - DMaskPop; 5187 while(ExtraElts--) 5188 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5189 5190 SDValue PreTFCRes; 5191 if (ReqRetNumElts > 1) { 5192 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5193 if (IsD16 && Unpacked) 5194 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5195 else 5196 PreTFCRes = NewVec; 5197 } else { 5198 PreTFCRes = BVElts[0]; 5199 } 5200 5201 if (V6F16Special) 5202 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5203 5204 if (!IsTexFail) { 5205 if (Result->getNumValues() > 1) 5206 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5207 else 5208 return PreTFCRes; 5209 } 5210 5211 // Extract the TexFail result and insert into aggregate return 5212 SmallVector<SDValue, 1> TFCElt; 5213 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5214 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5215 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5216 } 5217 5218 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5219 SDValue *LWE, bool &IsTexFail) { 5220 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5221 5222 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5223 if (Value) { 5224 IsTexFail = true; 5225 } 5226 5227 SDLoc DL(TexFailCtrlConst); 5228 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5229 Value &= ~(uint64_t)0x1; 5230 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5231 Value &= ~(uint64_t)0x2; 5232 5233 return Value == 0; 5234 } 5235 5236 SDValue SITargetLowering::lowerImage(SDValue Op, 5237 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5238 SelectionDAG &DAG) const { 5239 SDLoc DL(Op); 5240 MachineFunction &MF = DAG.getMachineFunction(); 5241 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5242 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5243 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5244 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5245 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5246 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5247 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5248 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5249 unsigned IntrOpcode = Intr->BaseOpcode; 5250 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5251 5252 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5253 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5254 bool IsD16 = false; 5255 bool IsA16 = false; 5256 SDValue VData; 5257 int NumVDataDwords; 5258 bool AdjustRetType = false; 5259 5260 unsigned AddrIdx; // Index of first address argument 5261 unsigned DMask; 5262 unsigned DMaskLanes = 0; 5263 5264 if (BaseOpcode->Atomic) { 5265 VData = Op.getOperand(2); 5266 5267 bool Is64Bit = VData.getValueType() == MVT::i64; 5268 if (BaseOpcode->AtomicX2) { 5269 SDValue VData2 = Op.getOperand(3); 5270 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5271 {VData, VData2}); 5272 if (Is64Bit) 5273 VData = DAG.getBitcast(MVT::v4i32, VData); 5274 5275 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5276 DMask = Is64Bit ? 0xf : 0x3; 5277 NumVDataDwords = Is64Bit ? 4 : 2; 5278 AddrIdx = 4; 5279 } else { 5280 DMask = Is64Bit ? 0x3 : 0x1; 5281 NumVDataDwords = Is64Bit ? 2 : 1; 5282 AddrIdx = 3; 5283 } 5284 } else { 5285 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5286 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5287 DMask = DMaskConst->getZExtValue(); 5288 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5289 5290 if (BaseOpcode->Store) { 5291 VData = Op.getOperand(2); 5292 5293 MVT StoreVT = VData.getSimpleValueType(); 5294 if (StoreVT.getScalarType() == MVT::f16) { 5295 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5296 return Op; // D16 is unsupported for this instruction 5297 5298 IsD16 = true; 5299 VData = handleD16VData(VData, DAG); 5300 } 5301 5302 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5303 } else { 5304 // Work out the num dwords based on the dmask popcount and underlying type 5305 // and whether packing is supported. 5306 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5307 if (LoadVT.getScalarType() == MVT::f16) { 5308 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5309 return Op; // D16 is unsupported for this instruction 5310 5311 IsD16 = true; 5312 } 5313 5314 // Confirm that the return type is large enough for the dmask specified 5315 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5316 (!LoadVT.isVector() && DMaskLanes > 1)) 5317 return Op; 5318 5319 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5320 NumVDataDwords = (DMaskLanes + 1) / 2; 5321 else 5322 NumVDataDwords = DMaskLanes; 5323 5324 AdjustRetType = true; 5325 } 5326 5327 AddrIdx = DMaskIdx + 1; 5328 } 5329 5330 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5331 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5332 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5333 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5334 NumCoords + NumLCM; 5335 unsigned NumMIVAddrs = NumVAddrs; 5336 5337 SmallVector<SDValue, 4> VAddrs; 5338 5339 // Optimize _L to _LZ when _L is zero 5340 if (LZMappingInfo) { 5341 if (auto ConstantLod = 5342 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5343 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5344 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5345 NumMIVAddrs--; // remove 'lod' 5346 } 5347 } 5348 } 5349 5350 // Optimize _mip away, when 'lod' is zero 5351 if (MIPMappingInfo) { 5352 if (auto ConstantLod = 5353 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5354 if (ConstantLod->isNullValue()) { 5355 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5356 NumMIVAddrs--; // remove 'lod' 5357 } 5358 } 5359 } 5360 5361 // Check for 16 bit addresses and pack if true. 5362 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5363 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5364 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5365 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5366 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5367 IsA16 = true; 5368 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5369 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5370 SDValue AddrLo, AddrHi; 5371 // Push back extra arguments. 5372 if (i < DimIdx) { 5373 AddrLo = Op.getOperand(i); 5374 } else { 5375 AddrLo = Op.getOperand(i); 5376 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5377 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5378 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5379 ((NumGradients / 2) % 2 == 1 && 5380 (i == DimIdx + (NumGradients / 2) - 1 || 5381 i == DimIdx + NumGradients - 1))) { 5382 AddrHi = DAG.getUNDEF(MVT::f16); 5383 } else { 5384 AddrHi = Op.getOperand(i + 1); 5385 i++; 5386 } 5387 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5388 {AddrLo, AddrHi}); 5389 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5390 } 5391 VAddrs.push_back(AddrLo); 5392 } 5393 } else { 5394 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5395 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5396 } 5397 5398 // If the register allocator cannot place the address registers contiguously 5399 // without introducing moves, then using the non-sequential address encoding 5400 // is always preferable, since it saves VALU instructions and is usually a 5401 // wash in terms of code size or even better. 5402 // 5403 // However, we currently have no way of hinting to the register allocator that 5404 // MIMG addresses should be placed contiguously when it is possible to do so, 5405 // so force non-NSA for the common 2-address case as a heuristic. 5406 // 5407 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5408 // allocation when possible. 5409 bool UseNSA = 5410 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5411 SDValue VAddr; 5412 if (!UseNSA) 5413 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5414 5415 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5416 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5417 unsigned CtrlIdx; // Index of texfailctrl argument 5418 SDValue Unorm; 5419 if (!BaseOpcode->Sampler) { 5420 Unorm = True; 5421 CtrlIdx = AddrIdx + NumVAddrs + 1; 5422 } else { 5423 auto UnormConst = 5424 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5425 5426 Unorm = UnormConst->getZExtValue() ? True : False; 5427 CtrlIdx = AddrIdx + NumVAddrs + 3; 5428 } 5429 5430 SDValue TFE; 5431 SDValue LWE; 5432 SDValue TexFail = Op.getOperand(CtrlIdx); 5433 bool IsTexFail = false; 5434 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5435 return Op; 5436 5437 if (IsTexFail) { 5438 if (!DMaskLanes) { 5439 // Expecting to get an error flag since TFC is on - and dmask is 0 5440 // Force dmask to be at least 1 otherwise the instruction will fail 5441 DMask = 0x1; 5442 DMaskLanes = 1; 5443 NumVDataDwords = 1; 5444 } 5445 NumVDataDwords += 1; 5446 AdjustRetType = true; 5447 } 5448 5449 // Has something earlier tagged that the return type needs adjusting 5450 // This happens if the instruction is a load or has set TexFailCtrl flags 5451 if (AdjustRetType) { 5452 // NumVDataDwords reflects the true number of dwords required in the return type 5453 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5454 // This is a no-op load. This can be eliminated 5455 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5456 if (isa<MemSDNode>(Op)) 5457 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5458 return Undef; 5459 } 5460 5461 EVT NewVT = NumVDataDwords > 1 ? 5462 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5463 : MVT::f32; 5464 5465 ResultTypes[0] = NewVT; 5466 if (ResultTypes.size() == 3) { 5467 // Original result was aggregate type used for TexFailCtrl results 5468 // The actual instruction returns as a vector type which has now been 5469 // created. Remove the aggregate result. 5470 ResultTypes.erase(&ResultTypes[1]); 5471 } 5472 } 5473 5474 SDValue GLC; 5475 SDValue SLC; 5476 SDValue DLC; 5477 if (BaseOpcode->Atomic) { 5478 GLC = True; // TODO no-return optimization 5479 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5480 IsGFX10 ? &DLC : nullptr)) 5481 return Op; 5482 } else { 5483 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5484 IsGFX10 ? &DLC : nullptr)) 5485 return Op; 5486 } 5487 5488 SmallVector<SDValue, 26> Ops; 5489 if (BaseOpcode->Store || BaseOpcode->Atomic) 5490 Ops.push_back(VData); // vdata 5491 if (UseNSA) { 5492 for (const SDValue &Addr : VAddrs) 5493 Ops.push_back(Addr); 5494 } else { 5495 Ops.push_back(VAddr); 5496 } 5497 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5498 if (BaseOpcode->Sampler) 5499 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5500 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5501 if (IsGFX10) 5502 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5503 Ops.push_back(Unorm); 5504 if (IsGFX10) 5505 Ops.push_back(DLC); 5506 Ops.push_back(GLC); 5507 Ops.push_back(SLC); 5508 Ops.push_back(IsA16 && // a16 or r128 5509 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5510 Ops.push_back(TFE); // tfe 5511 Ops.push_back(LWE); // lwe 5512 if (!IsGFX10) 5513 Ops.push_back(DimInfo->DA ? True : False); 5514 if (BaseOpcode->HasD16) 5515 Ops.push_back(IsD16 ? True : False); 5516 if (isa<MemSDNode>(Op)) 5517 Ops.push_back(Op.getOperand(0)); // chain 5518 5519 int NumVAddrDwords = 5520 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5521 int Opcode = -1; 5522 5523 if (IsGFX10) { 5524 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5525 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5526 : AMDGPU::MIMGEncGfx10Default, 5527 NumVDataDwords, NumVAddrDwords); 5528 } else { 5529 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5530 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5531 NumVDataDwords, NumVAddrDwords); 5532 if (Opcode == -1) 5533 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5534 NumVDataDwords, NumVAddrDwords); 5535 } 5536 assert(Opcode != -1); 5537 5538 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5539 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5540 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5541 DAG.setNodeMemRefs(NewNode, {MemRef}); 5542 } 5543 5544 if (BaseOpcode->AtomicX2) { 5545 SmallVector<SDValue, 1> Elt; 5546 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5547 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5548 } else if (!BaseOpcode->Store) { 5549 return constructRetValue(DAG, NewNode, 5550 OrigResultTypes, IsTexFail, 5551 Subtarget->hasUnpackedD16VMem(), IsD16, 5552 DMaskLanes, NumVDataDwords, DL, 5553 *DAG.getContext()); 5554 } 5555 5556 return SDValue(NewNode, 0); 5557 } 5558 5559 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5560 SDValue Offset, SDValue GLC, SDValue DLC, 5561 SelectionDAG &DAG) const { 5562 MachineFunction &MF = DAG.getMachineFunction(); 5563 MachineMemOperand *MMO = MF.getMachineMemOperand( 5564 MachinePointerInfo(), 5565 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5566 MachineMemOperand::MOInvariant, 5567 VT.getStoreSize(), VT.getStoreSize()); 5568 5569 if (!Offset->isDivergent()) { 5570 SDValue Ops[] = { 5571 Rsrc, 5572 Offset, // Offset 5573 GLC, 5574 DLC, 5575 }; 5576 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5577 DAG.getVTList(VT), Ops, VT, MMO); 5578 } 5579 5580 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5581 // assume that the buffer is unswizzled. 5582 SmallVector<SDValue, 4> Loads; 5583 unsigned NumLoads = 1; 5584 MVT LoadVT = VT.getSimpleVT(); 5585 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5586 assert((LoadVT.getScalarType() == MVT::i32 || 5587 LoadVT.getScalarType() == MVT::f32) && 5588 isPowerOf2_32(NumElts)); 5589 5590 if (NumElts == 8 || NumElts == 16) { 5591 NumLoads = NumElts == 16 ? 4 : 2; 5592 LoadVT = MVT::v4i32; 5593 } 5594 5595 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5596 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5597 SDValue Ops[] = { 5598 DAG.getEntryNode(), // Chain 5599 Rsrc, // rsrc 5600 DAG.getConstant(0, DL, MVT::i32), // vindex 5601 {}, // voffset 5602 {}, // soffset 5603 {}, // offset 5604 DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5605 DAG.getConstant(0, DL, MVT::i1), // idxen 5606 }; 5607 5608 // Use the alignment to ensure that the required offsets will fit into the 5609 // immediate offsets. 5610 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5611 5612 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5613 for (unsigned i = 0; i < NumLoads; ++i) { 5614 Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32); 5615 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, 5616 Ops, LoadVT, MMO)); 5617 } 5618 5619 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5620 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5621 5622 return Loads[0]; 5623 } 5624 5625 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5626 SelectionDAG &DAG) const { 5627 MachineFunction &MF = DAG.getMachineFunction(); 5628 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5629 5630 EVT VT = Op.getValueType(); 5631 SDLoc DL(Op); 5632 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5633 5634 // TODO: Should this propagate fast-math-flags? 5635 5636 switch (IntrinsicID) { 5637 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5638 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5639 return emitNonHSAIntrinsicError(DAG, DL, VT); 5640 return getPreloadedValue(DAG, *MFI, VT, 5641 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5642 } 5643 case Intrinsic::amdgcn_dispatch_ptr: 5644 case Intrinsic::amdgcn_queue_ptr: { 5645 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5646 DiagnosticInfoUnsupported BadIntrin( 5647 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5648 DL.getDebugLoc()); 5649 DAG.getContext()->diagnose(BadIntrin); 5650 return DAG.getUNDEF(VT); 5651 } 5652 5653 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5654 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5655 return getPreloadedValue(DAG, *MFI, VT, RegID); 5656 } 5657 case Intrinsic::amdgcn_implicitarg_ptr: { 5658 if (MFI->isEntryFunction()) 5659 return getImplicitArgPtr(DAG, DL); 5660 return getPreloadedValue(DAG, *MFI, VT, 5661 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5662 } 5663 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5664 return getPreloadedValue(DAG, *MFI, VT, 5665 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5666 } 5667 case Intrinsic::amdgcn_dispatch_id: { 5668 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5669 } 5670 case Intrinsic::amdgcn_rcp: 5671 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5672 case Intrinsic::amdgcn_rsq: 5673 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5674 case Intrinsic::amdgcn_rsq_legacy: 5675 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5676 return emitRemovedIntrinsicError(DAG, DL, VT); 5677 5678 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5679 case Intrinsic::amdgcn_rcp_legacy: 5680 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5681 return emitRemovedIntrinsicError(DAG, DL, VT); 5682 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5683 case Intrinsic::amdgcn_rsq_clamp: { 5684 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5685 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5686 5687 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5688 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5689 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5690 5691 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5692 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5693 DAG.getConstantFP(Max, DL, VT)); 5694 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5695 DAG.getConstantFP(Min, DL, VT)); 5696 } 5697 case Intrinsic::r600_read_ngroups_x: 5698 if (Subtarget->isAmdHsaOS()) 5699 return emitNonHSAIntrinsicError(DAG, DL, VT); 5700 5701 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5702 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5703 case Intrinsic::r600_read_ngroups_y: 5704 if (Subtarget->isAmdHsaOS()) 5705 return emitNonHSAIntrinsicError(DAG, DL, VT); 5706 5707 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5708 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5709 case Intrinsic::r600_read_ngroups_z: 5710 if (Subtarget->isAmdHsaOS()) 5711 return emitNonHSAIntrinsicError(DAG, DL, VT); 5712 5713 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5714 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5715 case Intrinsic::r600_read_global_size_x: 5716 if (Subtarget->isAmdHsaOS()) 5717 return emitNonHSAIntrinsicError(DAG, DL, VT); 5718 5719 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5720 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5721 case Intrinsic::r600_read_global_size_y: 5722 if (Subtarget->isAmdHsaOS()) 5723 return emitNonHSAIntrinsicError(DAG, DL, VT); 5724 5725 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5726 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5727 case Intrinsic::r600_read_global_size_z: 5728 if (Subtarget->isAmdHsaOS()) 5729 return emitNonHSAIntrinsicError(DAG, DL, VT); 5730 5731 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5732 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5733 case Intrinsic::r600_read_local_size_x: 5734 if (Subtarget->isAmdHsaOS()) 5735 return emitNonHSAIntrinsicError(DAG, DL, VT); 5736 5737 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5738 SI::KernelInputOffsets::LOCAL_SIZE_X); 5739 case Intrinsic::r600_read_local_size_y: 5740 if (Subtarget->isAmdHsaOS()) 5741 return emitNonHSAIntrinsicError(DAG, DL, VT); 5742 5743 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5744 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5745 case Intrinsic::r600_read_local_size_z: 5746 if (Subtarget->isAmdHsaOS()) 5747 return emitNonHSAIntrinsicError(DAG, DL, VT); 5748 5749 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5750 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5751 case Intrinsic::amdgcn_workgroup_id_x: 5752 case Intrinsic::r600_read_tgid_x: 5753 return getPreloadedValue(DAG, *MFI, VT, 5754 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5755 case Intrinsic::amdgcn_workgroup_id_y: 5756 case Intrinsic::r600_read_tgid_y: 5757 return getPreloadedValue(DAG, *MFI, VT, 5758 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5759 case Intrinsic::amdgcn_workgroup_id_z: 5760 case Intrinsic::r600_read_tgid_z: 5761 return getPreloadedValue(DAG, *MFI, VT, 5762 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5763 case Intrinsic::amdgcn_workitem_id_x: 5764 case Intrinsic::r600_read_tidig_x: 5765 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5766 SDLoc(DAG.getEntryNode()), 5767 MFI->getArgInfo().WorkItemIDX); 5768 case Intrinsic::amdgcn_workitem_id_y: 5769 case Intrinsic::r600_read_tidig_y: 5770 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5771 SDLoc(DAG.getEntryNode()), 5772 MFI->getArgInfo().WorkItemIDY); 5773 case Intrinsic::amdgcn_workitem_id_z: 5774 case Intrinsic::r600_read_tidig_z: 5775 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5776 SDLoc(DAG.getEntryNode()), 5777 MFI->getArgInfo().WorkItemIDZ); 5778 case Intrinsic::amdgcn_wavefrontsize: 5779 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5780 SDLoc(Op), MVT::i32); 5781 case Intrinsic::amdgcn_s_buffer_load: { 5782 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5783 SDValue GLC; 5784 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5785 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5786 IsGFX10 ? &DLC : nullptr)) 5787 return Op; 5788 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5789 DAG); 5790 } 5791 case Intrinsic::amdgcn_fdiv_fast: 5792 return lowerFDIV_FAST(Op, DAG); 5793 case Intrinsic::amdgcn_interp_mov: { 5794 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5795 SDValue Glue = M0.getValue(1); 5796 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 5797 Op.getOperand(2), Op.getOperand(3), Glue); 5798 } 5799 case Intrinsic::amdgcn_interp_p1: { 5800 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5801 SDValue Glue = M0.getValue(1); 5802 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 5803 Op.getOperand(2), Op.getOperand(3), Glue); 5804 } 5805 case Intrinsic::amdgcn_interp_p2: { 5806 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5807 SDValue Glue = SDValue(M0.getNode(), 1); 5808 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 5809 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 5810 Glue); 5811 } 5812 case Intrinsic::amdgcn_interp_p1_f16: { 5813 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5814 SDValue Glue = M0.getValue(1); 5815 if (getSubtarget()->getLDSBankCount() == 16) { 5816 // 16 bank LDS 5817 SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 5818 DAG.getConstant(2, DL, MVT::i32), // P0 5819 Op.getOperand(2), // Attrchan 5820 Op.getOperand(3), // Attr 5821 Glue); 5822 SDValue Ops[] = { 5823 Op.getOperand(1), // Src0 5824 Op.getOperand(2), // Attrchan 5825 Op.getOperand(3), // Attr 5826 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5827 S, // Src2 - holds two f16 values selected by high 5828 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5829 Op.getOperand(4), // high 5830 DAG.getConstant(0, DL, MVT::i1), // $clamp 5831 DAG.getConstant(0, DL, MVT::i32) // $omod 5832 }; 5833 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5834 } else { 5835 // 32 bank LDS 5836 SDValue Ops[] = { 5837 Op.getOperand(1), // Src0 5838 Op.getOperand(2), // Attrchan 5839 Op.getOperand(3), // Attr 5840 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5841 Op.getOperand(4), // high 5842 DAG.getConstant(0, DL, MVT::i1), // $clamp 5843 DAG.getConstant(0, DL, MVT::i32), // $omod 5844 Glue 5845 }; 5846 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5847 } 5848 } 5849 case Intrinsic::amdgcn_interp_p2_f16: { 5850 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6)); 5851 SDValue Glue = SDValue(M0.getNode(), 1); 5852 SDValue Ops[] = { 5853 Op.getOperand(2), // Src0 5854 Op.getOperand(3), // Attrchan 5855 Op.getOperand(4), // Attr 5856 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5857 Op.getOperand(1), // Src2 5858 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5859 Op.getOperand(5), // high 5860 DAG.getConstant(0, DL, MVT::i1), // $clamp 5861 Glue 5862 }; 5863 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5864 } 5865 case Intrinsic::amdgcn_sin: 5866 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5867 5868 case Intrinsic::amdgcn_cos: 5869 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5870 5871 case Intrinsic::amdgcn_mul_u24: 5872 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5873 case Intrinsic::amdgcn_mul_i24: 5874 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5875 5876 case Intrinsic::amdgcn_log_clamp: { 5877 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5878 return SDValue(); 5879 5880 DiagnosticInfoUnsupported BadIntrin( 5881 MF.getFunction(), "intrinsic not supported on subtarget", 5882 DL.getDebugLoc()); 5883 DAG.getContext()->diagnose(BadIntrin); 5884 return DAG.getUNDEF(VT); 5885 } 5886 case Intrinsic::amdgcn_ldexp: 5887 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5888 Op.getOperand(1), Op.getOperand(2)); 5889 5890 case Intrinsic::amdgcn_fract: 5891 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5892 5893 case Intrinsic::amdgcn_class: 5894 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5895 Op.getOperand(1), Op.getOperand(2)); 5896 case Intrinsic::amdgcn_div_fmas: 5897 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5898 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5899 Op.getOperand(4)); 5900 5901 case Intrinsic::amdgcn_div_fixup: 5902 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5903 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5904 5905 case Intrinsic::amdgcn_trig_preop: 5906 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5907 Op.getOperand(1), Op.getOperand(2)); 5908 case Intrinsic::amdgcn_div_scale: { 5909 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5910 5911 // Translate to the operands expected by the machine instruction. The 5912 // first parameter must be the same as the first instruction. 5913 SDValue Numerator = Op.getOperand(1); 5914 SDValue Denominator = Op.getOperand(2); 5915 5916 // Note this order is opposite of the machine instruction's operations, 5917 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5918 // intrinsic has the numerator as the first operand to match a normal 5919 // division operation. 5920 5921 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5922 5923 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5924 Denominator, Numerator); 5925 } 5926 case Intrinsic::amdgcn_icmp: { 5927 // There is a Pat that handles this variant, so return it as-is. 5928 if (Op.getOperand(1).getValueType() == MVT::i1 && 5929 Op.getConstantOperandVal(2) == 0 && 5930 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5931 return Op; 5932 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5933 } 5934 case Intrinsic::amdgcn_fcmp: { 5935 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5936 } 5937 case Intrinsic::amdgcn_fmed3: 5938 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5939 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5940 case Intrinsic::amdgcn_fdot2: 5941 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5942 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5943 Op.getOperand(4)); 5944 case Intrinsic::amdgcn_fmul_legacy: 5945 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5946 Op.getOperand(1), Op.getOperand(2)); 5947 case Intrinsic::amdgcn_sffbh: 5948 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5949 case Intrinsic::amdgcn_sbfe: 5950 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5951 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5952 case Intrinsic::amdgcn_ubfe: 5953 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5954 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5955 case Intrinsic::amdgcn_cvt_pkrtz: 5956 case Intrinsic::amdgcn_cvt_pknorm_i16: 5957 case Intrinsic::amdgcn_cvt_pknorm_u16: 5958 case Intrinsic::amdgcn_cvt_pk_i16: 5959 case Intrinsic::amdgcn_cvt_pk_u16: { 5960 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5961 EVT VT = Op.getValueType(); 5962 unsigned Opcode; 5963 5964 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5965 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5966 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5967 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5968 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5969 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5970 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5971 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5972 else 5973 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5974 5975 if (isTypeLegal(VT)) 5976 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5977 5978 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5979 Op.getOperand(1), Op.getOperand(2)); 5980 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5981 } 5982 case Intrinsic::amdgcn_wqm: { 5983 SDValue Src = Op.getOperand(1); 5984 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 5985 0); 5986 } 5987 case Intrinsic::amdgcn_wwm: { 5988 SDValue Src = Op.getOperand(1); 5989 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 5990 0); 5991 } 5992 case Intrinsic::amdgcn_fmad_ftz: 5993 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5994 Op.getOperand(2), Op.getOperand(3)); 5995 5996 case Intrinsic::amdgcn_if_break: 5997 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5998 Op->getOperand(1), Op->getOperand(2)), 0); 5999 6000 case Intrinsic::amdgcn_groupstaticsize: { 6001 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6002 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6003 return Op; 6004 6005 const Module *M = MF.getFunction().getParent(); 6006 const GlobalValue *GV = 6007 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6008 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6009 SIInstrInfo::MO_ABS32_LO); 6010 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6011 } 6012 default: 6013 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6014 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6015 return lowerImage(Op, ImageDimIntr, DAG); 6016 6017 return Op; 6018 } 6019 } 6020 6021 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6022 SelectionDAG &DAG) const { 6023 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6024 SDLoc DL(Op); 6025 6026 switch (IntrID) { 6027 case Intrinsic::amdgcn_ds_ordered_add: 6028 case Intrinsic::amdgcn_ds_ordered_swap: { 6029 MemSDNode *M = cast<MemSDNode>(Op); 6030 SDValue Chain = M->getOperand(0); 6031 SDValue M0 = M->getOperand(2); 6032 SDValue Value = M->getOperand(3); 6033 unsigned IndexOperand = M->getConstantOperandVal(7); 6034 unsigned WaveRelease = M->getConstantOperandVal(8); 6035 unsigned WaveDone = M->getConstantOperandVal(9); 6036 unsigned ShaderType; 6037 unsigned Instruction; 6038 6039 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6040 IndexOperand &= ~0x3f; 6041 unsigned CountDw = 0; 6042 6043 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6044 CountDw = (IndexOperand >> 24) & 0xf; 6045 IndexOperand &= ~(0xf << 24); 6046 6047 if (CountDw < 1 || CountDw > 4) { 6048 report_fatal_error( 6049 "ds_ordered_count: dword count must be between 1 and 4"); 6050 } 6051 } 6052 6053 if (IndexOperand) 6054 report_fatal_error("ds_ordered_count: bad index operand"); 6055 6056 switch (IntrID) { 6057 case Intrinsic::amdgcn_ds_ordered_add: 6058 Instruction = 0; 6059 break; 6060 case Intrinsic::amdgcn_ds_ordered_swap: 6061 Instruction = 1; 6062 break; 6063 } 6064 6065 if (WaveDone && !WaveRelease) 6066 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6067 6068 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6069 case CallingConv::AMDGPU_CS: 6070 case CallingConv::AMDGPU_KERNEL: 6071 ShaderType = 0; 6072 break; 6073 case CallingConv::AMDGPU_PS: 6074 ShaderType = 1; 6075 break; 6076 case CallingConv::AMDGPU_VS: 6077 ShaderType = 2; 6078 break; 6079 case CallingConv::AMDGPU_GS: 6080 ShaderType = 3; 6081 break; 6082 default: 6083 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6084 } 6085 6086 unsigned Offset0 = OrderedCountIndex << 2; 6087 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6088 (Instruction << 4); 6089 6090 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6091 Offset1 |= (CountDw - 1) << 6; 6092 6093 unsigned Offset = Offset0 | (Offset1 << 8); 6094 6095 SDValue Ops[] = { 6096 Chain, 6097 Value, 6098 DAG.getTargetConstant(Offset, DL, MVT::i16), 6099 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6100 }; 6101 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6102 M->getVTList(), Ops, M->getMemoryVT(), 6103 M->getMemOperand()); 6104 } 6105 case Intrinsic::amdgcn_ds_fadd: { 6106 MemSDNode *M = cast<MemSDNode>(Op); 6107 unsigned Opc; 6108 switch (IntrID) { 6109 case Intrinsic::amdgcn_ds_fadd: 6110 Opc = ISD::ATOMIC_LOAD_FADD; 6111 break; 6112 } 6113 6114 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6115 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6116 M->getMemOperand()); 6117 } 6118 case Intrinsic::amdgcn_atomic_inc: 6119 case Intrinsic::amdgcn_atomic_dec: 6120 case Intrinsic::amdgcn_ds_fmin: 6121 case Intrinsic::amdgcn_ds_fmax: { 6122 MemSDNode *M = cast<MemSDNode>(Op); 6123 unsigned Opc; 6124 switch (IntrID) { 6125 case Intrinsic::amdgcn_atomic_inc: 6126 Opc = AMDGPUISD::ATOMIC_INC; 6127 break; 6128 case Intrinsic::amdgcn_atomic_dec: 6129 Opc = AMDGPUISD::ATOMIC_DEC; 6130 break; 6131 case Intrinsic::amdgcn_ds_fmin: 6132 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6133 break; 6134 case Intrinsic::amdgcn_ds_fmax: 6135 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6136 break; 6137 default: 6138 llvm_unreachable("Unknown intrinsic!"); 6139 } 6140 SDValue Ops[] = { 6141 M->getOperand(0), // Chain 6142 M->getOperand(2), // Ptr 6143 M->getOperand(3) // Value 6144 }; 6145 6146 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6147 M->getMemoryVT(), M->getMemOperand()); 6148 } 6149 case Intrinsic::amdgcn_buffer_load: 6150 case Intrinsic::amdgcn_buffer_load_format: { 6151 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6152 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6153 unsigned IdxEn = 1; 6154 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6155 IdxEn = Idx->getZExtValue() != 0; 6156 SDValue Ops[] = { 6157 Op.getOperand(0), // Chain 6158 Op.getOperand(2), // rsrc 6159 Op.getOperand(3), // vindex 6160 SDValue(), // voffset -- will be set by setBufferOffsets 6161 SDValue(), // soffset -- will be set by setBufferOffsets 6162 SDValue(), // offset -- will be set by setBufferOffsets 6163 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6164 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6165 }; 6166 6167 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6168 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6169 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6170 6171 EVT VT = Op.getValueType(); 6172 EVT IntVT = VT.changeTypeToInteger(); 6173 auto *M = cast<MemSDNode>(Op); 6174 EVT LoadVT = Op.getValueType(); 6175 6176 if (LoadVT.getScalarType() == MVT::f16) 6177 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6178 M, DAG, Ops); 6179 6180 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6181 if (LoadVT.getScalarType() == MVT::i8 || 6182 LoadVT.getScalarType() == MVT::i16) 6183 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6184 6185 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6186 M->getMemOperand(), DAG); 6187 } 6188 case Intrinsic::amdgcn_raw_buffer_load: 6189 case Intrinsic::amdgcn_raw_buffer_load_format: { 6190 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6191 SDValue Ops[] = { 6192 Op.getOperand(0), // Chain 6193 Op.getOperand(2), // rsrc 6194 DAG.getConstant(0, DL, MVT::i32), // vindex 6195 Offsets.first, // voffset 6196 Op.getOperand(4), // soffset 6197 Offsets.second, // offset 6198 Op.getOperand(5), // cachepolicy 6199 DAG.getConstant(0, DL, MVT::i1), // idxen 6200 }; 6201 6202 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ? 6203 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6204 6205 EVT VT = Op.getValueType(); 6206 EVT IntVT = VT.changeTypeToInteger(); 6207 auto *M = cast<MemSDNode>(Op); 6208 EVT LoadVT = Op.getValueType(); 6209 6210 if (LoadVT.getScalarType() == MVT::f16) 6211 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6212 M, DAG, Ops); 6213 6214 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6215 if (LoadVT.getScalarType() == MVT::i8 || 6216 LoadVT.getScalarType() == MVT::i16) 6217 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6218 6219 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6220 M->getMemOperand(), DAG); 6221 } 6222 case Intrinsic::amdgcn_struct_buffer_load: 6223 case Intrinsic::amdgcn_struct_buffer_load_format: { 6224 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6225 SDValue Ops[] = { 6226 Op.getOperand(0), // Chain 6227 Op.getOperand(2), // rsrc 6228 Op.getOperand(3), // vindex 6229 Offsets.first, // voffset 6230 Op.getOperand(5), // soffset 6231 Offsets.second, // offset 6232 Op.getOperand(6), // cachepolicy 6233 DAG.getConstant(1, DL, MVT::i1), // idxen 6234 }; 6235 6236 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ? 6237 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6238 6239 EVT VT = Op.getValueType(); 6240 EVT IntVT = VT.changeTypeToInteger(); 6241 auto *M = cast<MemSDNode>(Op); 6242 EVT LoadVT = Op.getValueType(); 6243 6244 if (LoadVT.getScalarType() == MVT::f16) 6245 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6246 M, DAG, Ops); 6247 6248 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6249 if (LoadVT.getScalarType() == MVT::i8 || 6250 LoadVT.getScalarType() == MVT::i16) 6251 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6252 6253 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6254 M->getMemOperand(), DAG); 6255 } 6256 case Intrinsic::amdgcn_tbuffer_load: { 6257 MemSDNode *M = cast<MemSDNode>(Op); 6258 EVT LoadVT = Op.getValueType(); 6259 6260 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6261 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6262 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6263 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6264 unsigned IdxEn = 1; 6265 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6266 IdxEn = Idx->getZExtValue() != 0; 6267 SDValue Ops[] = { 6268 Op.getOperand(0), // Chain 6269 Op.getOperand(2), // rsrc 6270 Op.getOperand(3), // vindex 6271 Op.getOperand(4), // voffset 6272 Op.getOperand(5), // soffset 6273 Op.getOperand(6), // offset 6274 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6275 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6276 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6277 }; 6278 6279 if (LoadVT.getScalarType() == MVT::f16) 6280 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6281 M, DAG, Ops); 6282 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6283 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6284 DAG); 6285 } 6286 case Intrinsic::amdgcn_raw_tbuffer_load: { 6287 MemSDNode *M = cast<MemSDNode>(Op); 6288 EVT LoadVT = Op.getValueType(); 6289 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6290 6291 SDValue Ops[] = { 6292 Op.getOperand(0), // Chain 6293 Op.getOperand(2), // rsrc 6294 DAG.getConstant(0, DL, MVT::i32), // vindex 6295 Offsets.first, // voffset 6296 Op.getOperand(4), // soffset 6297 Offsets.second, // offset 6298 Op.getOperand(5), // format 6299 Op.getOperand(6), // cachepolicy 6300 DAG.getConstant(0, DL, MVT::i1), // idxen 6301 }; 6302 6303 if (LoadVT.getScalarType() == MVT::f16) 6304 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6305 M, DAG, Ops); 6306 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6307 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6308 DAG); 6309 } 6310 case Intrinsic::amdgcn_struct_tbuffer_load: { 6311 MemSDNode *M = cast<MemSDNode>(Op); 6312 EVT LoadVT = Op.getValueType(); 6313 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6314 6315 SDValue Ops[] = { 6316 Op.getOperand(0), // Chain 6317 Op.getOperand(2), // rsrc 6318 Op.getOperand(3), // vindex 6319 Offsets.first, // voffset 6320 Op.getOperand(5), // soffset 6321 Offsets.second, // offset 6322 Op.getOperand(6), // format 6323 Op.getOperand(7), // cachepolicy 6324 DAG.getConstant(1, DL, MVT::i1), // idxen 6325 }; 6326 6327 if (LoadVT.getScalarType() == MVT::f16) 6328 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6329 M, DAG, Ops); 6330 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6331 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6332 DAG); 6333 } 6334 case Intrinsic::amdgcn_buffer_atomic_swap: 6335 case Intrinsic::amdgcn_buffer_atomic_add: 6336 case Intrinsic::amdgcn_buffer_atomic_sub: 6337 case Intrinsic::amdgcn_buffer_atomic_smin: 6338 case Intrinsic::amdgcn_buffer_atomic_umin: 6339 case Intrinsic::amdgcn_buffer_atomic_smax: 6340 case Intrinsic::amdgcn_buffer_atomic_umax: 6341 case Intrinsic::amdgcn_buffer_atomic_and: 6342 case Intrinsic::amdgcn_buffer_atomic_or: 6343 case Intrinsic::amdgcn_buffer_atomic_xor: { 6344 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6345 unsigned IdxEn = 1; 6346 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6347 IdxEn = Idx->getZExtValue() != 0; 6348 SDValue Ops[] = { 6349 Op.getOperand(0), // Chain 6350 Op.getOperand(2), // vdata 6351 Op.getOperand(3), // rsrc 6352 Op.getOperand(4), // vindex 6353 SDValue(), // voffset -- will be set by setBufferOffsets 6354 SDValue(), // soffset -- will be set by setBufferOffsets 6355 SDValue(), // offset -- will be set by setBufferOffsets 6356 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6357 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6358 }; 6359 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6360 EVT VT = Op.getValueType(); 6361 6362 auto *M = cast<MemSDNode>(Op); 6363 unsigned Opcode = 0; 6364 6365 switch (IntrID) { 6366 case Intrinsic::amdgcn_buffer_atomic_swap: 6367 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6368 break; 6369 case Intrinsic::amdgcn_buffer_atomic_add: 6370 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6371 break; 6372 case Intrinsic::amdgcn_buffer_atomic_sub: 6373 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6374 break; 6375 case Intrinsic::amdgcn_buffer_atomic_smin: 6376 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6377 break; 6378 case Intrinsic::amdgcn_buffer_atomic_umin: 6379 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6380 break; 6381 case Intrinsic::amdgcn_buffer_atomic_smax: 6382 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6383 break; 6384 case Intrinsic::amdgcn_buffer_atomic_umax: 6385 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6386 break; 6387 case Intrinsic::amdgcn_buffer_atomic_and: 6388 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6389 break; 6390 case Intrinsic::amdgcn_buffer_atomic_or: 6391 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6392 break; 6393 case Intrinsic::amdgcn_buffer_atomic_xor: 6394 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6395 break; 6396 default: 6397 llvm_unreachable("unhandled atomic opcode"); 6398 } 6399 6400 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6401 M->getMemOperand()); 6402 } 6403 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6404 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6405 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6406 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6407 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6408 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6409 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6410 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6411 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6412 case Intrinsic::amdgcn_raw_buffer_atomic_xor: { 6413 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6414 SDValue Ops[] = { 6415 Op.getOperand(0), // Chain 6416 Op.getOperand(2), // vdata 6417 Op.getOperand(3), // rsrc 6418 DAG.getConstant(0, DL, MVT::i32), // vindex 6419 Offsets.first, // voffset 6420 Op.getOperand(5), // soffset 6421 Offsets.second, // offset 6422 Op.getOperand(6), // cachepolicy 6423 DAG.getConstant(0, DL, MVT::i1), // idxen 6424 }; 6425 EVT VT = Op.getValueType(); 6426 6427 auto *M = cast<MemSDNode>(Op); 6428 unsigned Opcode = 0; 6429 6430 switch (IntrID) { 6431 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6432 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6433 break; 6434 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6435 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6436 break; 6437 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6438 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6439 break; 6440 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6441 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6442 break; 6443 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6444 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6445 break; 6446 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6447 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6448 break; 6449 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6450 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6451 break; 6452 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6453 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6454 break; 6455 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6456 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6457 break; 6458 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6459 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6460 break; 6461 default: 6462 llvm_unreachable("unhandled atomic opcode"); 6463 } 6464 6465 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6466 M->getMemOperand()); 6467 } 6468 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6469 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6470 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6471 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6472 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6473 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6474 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6475 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6476 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6477 case Intrinsic::amdgcn_struct_buffer_atomic_xor: { 6478 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6479 SDValue Ops[] = { 6480 Op.getOperand(0), // Chain 6481 Op.getOperand(2), // vdata 6482 Op.getOperand(3), // rsrc 6483 Op.getOperand(4), // vindex 6484 Offsets.first, // voffset 6485 Op.getOperand(6), // soffset 6486 Offsets.second, // offset 6487 Op.getOperand(7), // cachepolicy 6488 DAG.getConstant(1, DL, MVT::i1), // idxen 6489 }; 6490 EVT VT = Op.getValueType(); 6491 6492 auto *M = cast<MemSDNode>(Op); 6493 unsigned Opcode = 0; 6494 6495 switch (IntrID) { 6496 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6497 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6498 break; 6499 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6500 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6501 break; 6502 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6503 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6504 break; 6505 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6506 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6507 break; 6508 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6509 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6510 break; 6511 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6512 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6513 break; 6514 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6515 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6516 break; 6517 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6518 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6519 break; 6520 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6521 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6522 break; 6523 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6524 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6525 break; 6526 default: 6527 llvm_unreachable("unhandled atomic opcode"); 6528 } 6529 6530 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6531 M->getMemOperand()); 6532 } 6533 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6534 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6535 unsigned IdxEn = 1; 6536 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6537 IdxEn = Idx->getZExtValue() != 0; 6538 SDValue Ops[] = { 6539 Op.getOperand(0), // Chain 6540 Op.getOperand(2), // src 6541 Op.getOperand(3), // cmp 6542 Op.getOperand(4), // rsrc 6543 Op.getOperand(5), // vindex 6544 SDValue(), // voffset -- will be set by setBufferOffsets 6545 SDValue(), // soffset -- will be set by setBufferOffsets 6546 SDValue(), // offset -- will be set by setBufferOffsets 6547 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6548 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6549 }; 6550 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6551 EVT VT = Op.getValueType(); 6552 auto *M = cast<MemSDNode>(Op); 6553 6554 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6555 Op->getVTList(), Ops, VT, M->getMemOperand()); 6556 } 6557 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6558 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6559 SDValue Ops[] = { 6560 Op.getOperand(0), // Chain 6561 Op.getOperand(2), // src 6562 Op.getOperand(3), // cmp 6563 Op.getOperand(4), // rsrc 6564 DAG.getConstant(0, DL, MVT::i32), // vindex 6565 Offsets.first, // voffset 6566 Op.getOperand(6), // soffset 6567 Offsets.second, // offset 6568 Op.getOperand(7), // cachepolicy 6569 DAG.getConstant(0, DL, MVT::i1), // idxen 6570 }; 6571 EVT VT = Op.getValueType(); 6572 auto *M = cast<MemSDNode>(Op); 6573 6574 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6575 Op->getVTList(), Ops, VT, M->getMemOperand()); 6576 } 6577 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6578 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6579 SDValue Ops[] = { 6580 Op.getOperand(0), // Chain 6581 Op.getOperand(2), // src 6582 Op.getOperand(3), // cmp 6583 Op.getOperand(4), // rsrc 6584 Op.getOperand(5), // vindex 6585 Offsets.first, // voffset 6586 Op.getOperand(7), // soffset 6587 Offsets.second, // offset 6588 Op.getOperand(8), // cachepolicy 6589 DAG.getConstant(1, DL, MVT::i1), // idxen 6590 }; 6591 EVT VT = Op.getValueType(); 6592 auto *M = cast<MemSDNode>(Op); 6593 6594 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6595 Op->getVTList(), Ops, VT, M->getMemOperand()); 6596 } 6597 6598 default: 6599 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6600 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6601 return lowerImage(Op, ImageDimIntr, DAG); 6602 6603 return SDValue(); 6604 } 6605 } 6606 6607 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6608 // dwordx4 if on SI. 6609 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6610 SDVTList VTList, 6611 ArrayRef<SDValue> Ops, EVT MemVT, 6612 MachineMemOperand *MMO, 6613 SelectionDAG &DAG) const { 6614 EVT VT = VTList.VTs[0]; 6615 EVT WidenedVT = VT; 6616 EVT WidenedMemVT = MemVT; 6617 if (!Subtarget->hasDwordx3LoadStores() && 6618 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6619 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6620 WidenedVT.getVectorElementType(), 4); 6621 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6622 WidenedMemVT.getVectorElementType(), 4); 6623 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6624 } 6625 6626 assert(VTList.NumVTs == 2); 6627 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6628 6629 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6630 WidenedMemVT, MMO); 6631 if (WidenedVT != VT) { 6632 auto Extract = DAG.getNode( 6633 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6634 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6635 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6636 } 6637 return NewOp; 6638 } 6639 6640 SDValue SITargetLowering::handleD16VData(SDValue VData, 6641 SelectionDAG &DAG) const { 6642 EVT StoreVT = VData.getValueType(); 6643 6644 // No change for f16 and legal vector D16 types. 6645 if (!StoreVT.isVector()) 6646 return VData; 6647 6648 SDLoc DL(VData); 6649 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6650 6651 if (Subtarget->hasUnpackedD16VMem()) { 6652 // We need to unpack the packed data to store. 6653 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6654 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6655 6656 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6657 StoreVT.getVectorNumElements()); 6658 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6659 return DAG.UnrollVectorOp(ZExt.getNode()); 6660 } 6661 6662 assert(isTypeLegal(StoreVT)); 6663 return VData; 6664 } 6665 6666 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6667 SelectionDAG &DAG) const { 6668 SDLoc DL(Op); 6669 SDValue Chain = Op.getOperand(0); 6670 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6671 MachineFunction &MF = DAG.getMachineFunction(); 6672 6673 switch (IntrinsicID) { 6674 case Intrinsic::amdgcn_exp: { 6675 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6676 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6677 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6678 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6679 6680 const SDValue Ops[] = { 6681 Chain, 6682 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6683 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6684 Op.getOperand(4), // src0 6685 Op.getOperand(5), // src1 6686 Op.getOperand(6), // src2 6687 Op.getOperand(7), // src3 6688 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6689 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6690 }; 6691 6692 unsigned Opc = Done->isNullValue() ? 6693 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6694 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6695 } 6696 case Intrinsic::amdgcn_exp_compr: { 6697 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6698 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6699 SDValue Src0 = Op.getOperand(4); 6700 SDValue Src1 = Op.getOperand(5); 6701 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6702 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6703 6704 SDValue Undef = DAG.getUNDEF(MVT::f32); 6705 const SDValue Ops[] = { 6706 Chain, 6707 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6708 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6709 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6710 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6711 Undef, // src2 6712 Undef, // src3 6713 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6714 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6715 }; 6716 6717 unsigned Opc = Done->isNullValue() ? 6718 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6719 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6720 } 6721 case Intrinsic::amdgcn_s_sendmsg: 6722 case Intrinsic::amdgcn_s_sendmsghalt: { 6723 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 6724 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 6725 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 6726 SDValue Glue = Chain.getValue(1); 6727 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 6728 Op.getOperand(2), Glue); 6729 } 6730 case Intrinsic::amdgcn_init_exec: { 6731 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 6732 Op.getOperand(2)); 6733 } 6734 case Intrinsic::amdgcn_init_exec_from_input: { 6735 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 6736 Op.getOperand(2), Op.getOperand(3)); 6737 } 6738 case Intrinsic::amdgcn_s_barrier: { 6739 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6740 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6741 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6742 if (WGSize <= ST.getWavefrontSize()) 6743 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6744 Op.getOperand(0)), 0); 6745 } 6746 return SDValue(); 6747 }; 6748 case Intrinsic::amdgcn_tbuffer_store: { 6749 SDValue VData = Op.getOperand(2); 6750 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6751 if (IsD16) 6752 VData = handleD16VData(VData, DAG); 6753 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6754 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6755 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6756 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6757 unsigned IdxEn = 1; 6758 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6759 IdxEn = Idx->getZExtValue() != 0; 6760 SDValue Ops[] = { 6761 Chain, 6762 VData, // vdata 6763 Op.getOperand(3), // rsrc 6764 Op.getOperand(4), // vindex 6765 Op.getOperand(5), // voffset 6766 Op.getOperand(6), // soffset 6767 Op.getOperand(7), // offset 6768 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6769 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6770 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen 6771 }; 6772 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6773 AMDGPUISD::TBUFFER_STORE_FORMAT; 6774 MemSDNode *M = cast<MemSDNode>(Op); 6775 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6776 M->getMemoryVT(), M->getMemOperand()); 6777 } 6778 6779 case Intrinsic::amdgcn_struct_tbuffer_store: { 6780 SDValue VData = Op.getOperand(2); 6781 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6782 if (IsD16) 6783 VData = handleD16VData(VData, DAG); 6784 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6785 SDValue Ops[] = { 6786 Chain, 6787 VData, // vdata 6788 Op.getOperand(3), // rsrc 6789 Op.getOperand(4), // vindex 6790 Offsets.first, // voffset 6791 Op.getOperand(6), // soffset 6792 Offsets.second, // offset 6793 Op.getOperand(7), // format 6794 Op.getOperand(8), // cachepolicy 6795 DAG.getConstant(1, DL, MVT::i1), // idexen 6796 }; 6797 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6798 AMDGPUISD::TBUFFER_STORE_FORMAT; 6799 MemSDNode *M = cast<MemSDNode>(Op); 6800 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6801 M->getMemoryVT(), M->getMemOperand()); 6802 } 6803 6804 case Intrinsic::amdgcn_raw_tbuffer_store: { 6805 SDValue VData = Op.getOperand(2); 6806 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6807 if (IsD16) 6808 VData = handleD16VData(VData, DAG); 6809 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6810 SDValue Ops[] = { 6811 Chain, 6812 VData, // vdata 6813 Op.getOperand(3), // rsrc 6814 DAG.getConstant(0, DL, MVT::i32), // vindex 6815 Offsets.first, // voffset 6816 Op.getOperand(5), // soffset 6817 Offsets.second, // offset 6818 Op.getOperand(6), // format 6819 Op.getOperand(7), // cachepolicy 6820 DAG.getConstant(0, DL, MVT::i1), // idexen 6821 }; 6822 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6823 AMDGPUISD::TBUFFER_STORE_FORMAT; 6824 MemSDNode *M = cast<MemSDNode>(Op); 6825 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6826 M->getMemoryVT(), M->getMemOperand()); 6827 } 6828 6829 case Intrinsic::amdgcn_buffer_store: 6830 case Intrinsic::amdgcn_buffer_store_format: { 6831 SDValue VData = Op.getOperand(2); 6832 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6833 if (IsD16) 6834 VData = handleD16VData(VData, DAG); 6835 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6836 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6837 unsigned IdxEn = 1; 6838 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6839 IdxEn = Idx->getZExtValue() != 0; 6840 SDValue Ops[] = { 6841 Chain, 6842 VData, 6843 Op.getOperand(3), // rsrc 6844 Op.getOperand(4), // vindex 6845 SDValue(), // voffset -- will be set by setBufferOffsets 6846 SDValue(), // soffset -- will be set by setBufferOffsets 6847 SDValue(), // offset -- will be set by setBufferOffsets 6848 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6849 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6850 }; 6851 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6852 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6853 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6854 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6855 MemSDNode *M = cast<MemSDNode>(Op); 6856 6857 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6858 EVT VDataType = VData.getValueType().getScalarType(); 6859 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6860 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6861 6862 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6863 M->getMemoryVT(), M->getMemOperand()); 6864 } 6865 6866 case Intrinsic::amdgcn_raw_buffer_store: 6867 case Intrinsic::amdgcn_raw_buffer_store_format: { 6868 SDValue VData = Op.getOperand(2); 6869 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6870 if (IsD16) 6871 VData = handleD16VData(VData, DAG); 6872 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6873 SDValue Ops[] = { 6874 Chain, 6875 VData, 6876 Op.getOperand(3), // rsrc 6877 DAG.getConstant(0, DL, MVT::i32), // vindex 6878 Offsets.first, // voffset 6879 Op.getOperand(5), // soffset 6880 Offsets.second, // offset 6881 Op.getOperand(6), // cachepolicy 6882 DAG.getConstant(0, DL, MVT::i1), // idxen 6883 }; 6884 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ? 6885 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6886 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6887 MemSDNode *M = cast<MemSDNode>(Op); 6888 6889 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6890 EVT VDataType = VData.getValueType().getScalarType(); 6891 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6892 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6893 6894 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6895 M->getMemoryVT(), M->getMemOperand()); 6896 } 6897 6898 case Intrinsic::amdgcn_struct_buffer_store: 6899 case Intrinsic::amdgcn_struct_buffer_store_format: { 6900 SDValue VData = Op.getOperand(2); 6901 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6902 if (IsD16) 6903 VData = handleD16VData(VData, DAG); 6904 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6905 SDValue Ops[] = { 6906 Chain, 6907 VData, 6908 Op.getOperand(3), // rsrc 6909 Op.getOperand(4), // vindex 6910 Offsets.first, // voffset 6911 Op.getOperand(6), // soffset 6912 Offsets.second, // offset 6913 Op.getOperand(7), // cachepolicy 6914 DAG.getConstant(1, DL, MVT::i1), // idxen 6915 }; 6916 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6917 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6918 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6919 MemSDNode *M = cast<MemSDNode>(Op); 6920 6921 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6922 EVT VDataType = VData.getValueType().getScalarType(); 6923 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6924 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6925 6926 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6927 M->getMemoryVT(), M->getMemOperand()); 6928 } 6929 6930 case Intrinsic::amdgcn_buffer_atomic_fadd: { 6931 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6932 unsigned IdxEn = 1; 6933 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6934 IdxEn = Idx->getZExtValue() != 0; 6935 SDValue Ops[] = { 6936 Chain, 6937 Op.getOperand(2), // vdata 6938 Op.getOperand(3), // rsrc 6939 Op.getOperand(4), // vindex 6940 SDValue(), // voffset -- will be set by setBufferOffsets 6941 SDValue(), // soffset -- will be set by setBufferOffsets 6942 SDValue(), // offset -- will be set by setBufferOffsets 6943 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6944 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6945 }; 6946 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6947 EVT VT = Op.getOperand(2).getValueType(); 6948 6949 auto *M = cast<MemSDNode>(Op); 6950 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 6951 : AMDGPUISD::BUFFER_ATOMIC_FADD; 6952 6953 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6954 M->getMemOperand()); 6955 } 6956 6957 case Intrinsic::amdgcn_global_atomic_fadd: { 6958 SDValue Ops[] = { 6959 Chain, 6960 Op.getOperand(2), // ptr 6961 Op.getOperand(3) // vdata 6962 }; 6963 EVT VT = Op.getOperand(3).getValueType(); 6964 6965 auto *M = cast<MemSDNode>(Op); 6966 unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD 6967 : AMDGPUISD::ATOMIC_FADD; 6968 6969 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6970 M->getMemOperand()); 6971 } 6972 6973 case Intrinsic::amdgcn_end_cf: 6974 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 6975 Op->getOperand(2), Chain), 0); 6976 6977 default: { 6978 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6979 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6980 return lowerImage(Op, ImageDimIntr, DAG); 6981 6982 return Op; 6983 } 6984 } 6985 } 6986 6987 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 6988 // offset (the offset that is included in bounds checking and swizzling, to be 6989 // split between the instruction's voffset and immoffset fields) and soffset 6990 // (the offset that is excluded from bounds checking and swizzling, to go in 6991 // the instruction's soffset field). This function takes the first kind of 6992 // offset and figures out how to split it between voffset and immoffset. 6993 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 6994 SDValue Offset, SelectionDAG &DAG) const { 6995 SDLoc DL(Offset); 6996 const unsigned MaxImm = 4095; 6997 SDValue N0 = Offset; 6998 ConstantSDNode *C1 = nullptr; 6999 7000 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7001 N0 = SDValue(); 7002 else if (DAG.isBaseWithConstantOffset(N0)) { 7003 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7004 N0 = N0.getOperand(0); 7005 } 7006 7007 if (C1) { 7008 unsigned ImmOffset = C1->getZExtValue(); 7009 // If the immediate value is too big for the immoffset field, put the value 7010 // and -4096 into the immoffset field so that the value that is copied/added 7011 // for the voffset field is a multiple of 4096, and it stands more chance 7012 // of being CSEd with the copy/add for another similar load/store. 7013 // However, do not do that rounding down to a multiple of 4096 if that is a 7014 // negative number, as it appears to be illegal to have a negative offset 7015 // in the vgpr, even if adding the immediate offset makes it positive. 7016 unsigned Overflow = ImmOffset & ~MaxImm; 7017 ImmOffset -= Overflow; 7018 if ((int32_t)Overflow < 0) { 7019 Overflow += ImmOffset; 7020 ImmOffset = 0; 7021 } 7022 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32)); 7023 if (Overflow) { 7024 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7025 if (!N0) 7026 N0 = OverflowVal; 7027 else { 7028 SDValue Ops[] = { N0, OverflowVal }; 7029 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7030 } 7031 } 7032 } 7033 if (!N0) 7034 N0 = DAG.getConstant(0, DL, MVT::i32); 7035 if (!C1) 7036 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32)); 7037 return {N0, SDValue(C1, 0)}; 7038 } 7039 7040 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7041 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7042 // pointed to by Offsets. 7043 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7044 SelectionDAG &DAG, SDValue *Offsets, 7045 unsigned Align) const { 7046 SDLoc DL(CombinedOffset); 7047 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7048 uint32_t Imm = C->getZExtValue(); 7049 uint32_t SOffset, ImmOffset; 7050 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7051 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7052 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7053 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 7054 return; 7055 } 7056 } 7057 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7058 SDValue N0 = CombinedOffset.getOperand(0); 7059 SDValue N1 = CombinedOffset.getOperand(1); 7060 uint32_t SOffset, ImmOffset; 7061 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7062 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7063 Subtarget, Align)) { 7064 Offsets[0] = N0; 7065 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7066 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 7067 return; 7068 } 7069 } 7070 Offsets[0] = CombinedOffset; 7071 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7072 Offsets[2] = DAG.getConstant(0, DL, MVT::i32); 7073 } 7074 7075 // Handle 8 bit and 16 bit buffer loads 7076 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7077 EVT LoadVT, SDLoc DL, 7078 ArrayRef<SDValue> Ops, 7079 MemSDNode *M) const { 7080 EVT IntVT = LoadVT.changeTypeToInteger(); 7081 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7082 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7083 7084 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7085 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7086 Ops, IntVT, 7087 M->getMemOperand()); 7088 SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL, 7089 LoadVT.getScalarType(), BufferLoad); 7090 return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL); 7091 } 7092 7093 // Handle 8 bit and 16 bit buffer stores 7094 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7095 EVT VDataType, SDLoc DL, 7096 SDValue Ops[], 7097 MemSDNode *M) const { 7098 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7099 Ops[1] = BufferStoreExt; 7100 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7101 AMDGPUISD::BUFFER_STORE_SHORT; 7102 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7103 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7104 M->getMemOperand()); 7105 } 7106 7107 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7108 ISD::LoadExtType ExtType, SDValue Op, 7109 const SDLoc &SL, EVT VT) { 7110 if (VT.bitsLT(Op.getValueType())) 7111 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7112 7113 switch (ExtType) { 7114 case ISD::SEXTLOAD: 7115 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7116 case ISD::ZEXTLOAD: 7117 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7118 case ISD::EXTLOAD: 7119 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7120 case ISD::NON_EXTLOAD: 7121 return Op; 7122 } 7123 7124 llvm_unreachable("invalid ext type"); 7125 } 7126 7127 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7128 SelectionDAG &DAG = DCI.DAG; 7129 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7130 return SDValue(); 7131 7132 // FIXME: Constant loads should all be marked invariant. 7133 unsigned AS = Ld->getAddressSpace(); 7134 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7135 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7136 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7137 return SDValue(); 7138 7139 // Don't do this early, since it may interfere with adjacent load merging for 7140 // illegal types. We can avoid losing alignment information for exotic types 7141 // pre-legalize. 7142 EVT MemVT = Ld->getMemoryVT(); 7143 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7144 MemVT.getSizeInBits() >= 32) 7145 return SDValue(); 7146 7147 SDLoc SL(Ld); 7148 7149 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7150 "unexpected vector extload"); 7151 7152 // TODO: Drop only high part of range. 7153 SDValue Ptr = Ld->getBasePtr(); 7154 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7155 MVT::i32, SL, Ld->getChain(), Ptr, 7156 Ld->getOffset(), 7157 Ld->getPointerInfo(), MVT::i32, 7158 Ld->getAlignment(), 7159 Ld->getMemOperand()->getFlags(), 7160 Ld->getAAInfo(), 7161 nullptr); // Drop ranges 7162 7163 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7164 if (MemVT.isFloatingPoint()) { 7165 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7166 "unexpected fp extload"); 7167 TruncVT = MemVT.changeTypeToInteger(); 7168 } 7169 7170 SDValue Cvt = NewLoad; 7171 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7172 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7173 DAG.getValueType(TruncVT)); 7174 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7175 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7176 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7177 } else { 7178 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7179 } 7180 7181 EVT VT = Ld->getValueType(0); 7182 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7183 7184 DCI.AddToWorklist(Cvt.getNode()); 7185 7186 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7187 // the appropriate extension from the 32-bit load. 7188 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7189 DCI.AddToWorklist(Cvt.getNode()); 7190 7191 // Handle conversion back to floating point if necessary. 7192 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7193 7194 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7195 } 7196 7197 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7198 SDLoc DL(Op); 7199 LoadSDNode *Load = cast<LoadSDNode>(Op); 7200 ISD::LoadExtType ExtType = Load->getExtensionType(); 7201 EVT MemVT = Load->getMemoryVT(); 7202 7203 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7204 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7205 return SDValue(); 7206 7207 // FIXME: Copied from PPC 7208 // First, load into 32 bits, then truncate to 1 bit. 7209 7210 SDValue Chain = Load->getChain(); 7211 SDValue BasePtr = Load->getBasePtr(); 7212 MachineMemOperand *MMO = Load->getMemOperand(); 7213 7214 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7215 7216 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7217 BasePtr, RealMemVT, MMO); 7218 7219 if (!MemVT.isVector()) { 7220 SDValue Ops[] = { 7221 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7222 NewLD.getValue(1) 7223 }; 7224 7225 return DAG.getMergeValues(Ops, DL); 7226 } 7227 7228 SmallVector<SDValue, 3> Elts; 7229 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7230 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7231 DAG.getConstant(I, DL, MVT::i32)); 7232 7233 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7234 } 7235 7236 SDValue Ops[] = { 7237 DAG.getBuildVector(MemVT, DL, Elts), 7238 NewLD.getValue(1) 7239 }; 7240 7241 return DAG.getMergeValues(Ops, DL); 7242 } 7243 7244 if (!MemVT.isVector()) 7245 return SDValue(); 7246 7247 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7248 "Custom lowering for non-i32 vectors hasn't been implemented."); 7249 7250 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 7251 *Load->getMemOperand())) { 7252 SDValue Ops[2]; 7253 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7254 return DAG.getMergeValues(Ops, DL); 7255 } 7256 7257 unsigned Alignment = Load->getAlignment(); 7258 unsigned AS = Load->getAddressSpace(); 7259 if (Subtarget->hasLDSMisalignedBug() && 7260 AS == AMDGPUAS::FLAT_ADDRESS && 7261 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7262 return SplitVectorLoad(Op, DAG); 7263 } 7264 7265 MachineFunction &MF = DAG.getMachineFunction(); 7266 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7267 // If there is a possibilty that flat instruction access scratch memory 7268 // then we need to use the same legalization rules we use for private. 7269 if (AS == AMDGPUAS::FLAT_ADDRESS) 7270 AS = MFI->hasFlatScratchInit() ? 7271 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7272 7273 unsigned NumElements = MemVT.getVectorNumElements(); 7274 7275 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7276 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7277 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7278 if (MemVT.isPow2VectorType()) 7279 return SDValue(); 7280 if (NumElements == 3) 7281 return WidenVectorLoad(Op, DAG); 7282 return SplitVectorLoad(Op, DAG); 7283 } 7284 // Non-uniform loads will be selected to MUBUF instructions, so they 7285 // have the same legalization requirements as global and private 7286 // loads. 7287 // 7288 } 7289 7290 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7291 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7292 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7293 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7294 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7295 Alignment >= 4 && NumElements < 32) { 7296 if (MemVT.isPow2VectorType()) 7297 return SDValue(); 7298 if (NumElements == 3) 7299 return WidenVectorLoad(Op, DAG); 7300 return SplitVectorLoad(Op, DAG); 7301 } 7302 // Non-uniform loads will be selected to MUBUF instructions, so they 7303 // have the same legalization requirements as global and private 7304 // loads. 7305 // 7306 } 7307 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7308 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7309 AS == AMDGPUAS::GLOBAL_ADDRESS || 7310 AS == AMDGPUAS::FLAT_ADDRESS) { 7311 if (NumElements > 4) 7312 return SplitVectorLoad(Op, DAG); 7313 // v3 loads not supported on SI. 7314 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7315 return WidenVectorLoad(Op, DAG); 7316 // v3 and v4 loads are supported for private and global memory. 7317 return SDValue(); 7318 } 7319 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7320 // Depending on the setting of the private_element_size field in the 7321 // resource descriptor, we can only make private accesses up to a certain 7322 // size. 7323 switch (Subtarget->getMaxPrivateElementSize()) { 7324 case 4: 7325 return scalarizeVectorLoad(Load, DAG); 7326 case 8: 7327 if (NumElements > 2) 7328 return SplitVectorLoad(Op, DAG); 7329 return SDValue(); 7330 case 16: 7331 // Same as global/flat 7332 if (NumElements > 4) 7333 return SplitVectorLoad(Op, DAG); 7334 // v3 loads not supported on SI. 7335 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7336 return WidenVectorLoad(Op, DAG); 7337 return SDValue(); 7338 default: 7339 llvm_unreachable("unsupported private_element_size"); 7340 } 7341 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7342 // Use ds_read_b128 if possible. 7343 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7344 MemVT.getStoreSize() == 16) 7345 return SDValue(); 7346 7347 if (NumElements > 2) 7348 return SplitVectorLoad(Op, DAG); 7349 7350 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7351 // address is negative, then the instruction is incorrectly treated as 7352 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7353 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7354 // load later in the SILoadStoreOptimizer. 7355 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7356 NumElements == 2 && MemVT.getStoreSize() == 8 && 7357 Load->getAlignment() < 8) { 7358 return SplitVectorLoad(Op, DAG); 7359 } 7360 } 7361 return SDValue(); 7362 } 7363 7364 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7365 EVT VT = Op.getValueType(); 7366 assert(VT.getSizeInBits() == 64); 7367 7368 SDLoc DL(Op); 7369 SDValue Cond = Op.getOperand(0); 7370 7371 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7372 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7373 7374 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7375 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7376 7377 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7378 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7379 7380 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7381 7382 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7383 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7384 7385 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7386 7387 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7388 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7389 } 7390 7391 // Catch division cases where we can use shortcuts with rcp and rsq 7392 // instructions. 7393 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7394 SelectionDAG &DAG) const { 7395 SDLoc SL(Op); 7396 SDValue LHS = Op.getOperand(0); 7397 SDValue RHS = Op.getOperand(1); 7398 EVT VT = Op.getValueType(); 7399 const SDNodeFlags Flags = Op->getFlags(); 7400 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7401 7402 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 7403 return SDValue(); 7404 7405 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7406 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7407 if (CLHS->isExactlyValue(1.0)) { 7408 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7409 // the CI documentation has a worst case error of 1 ulp. 7410 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7411 // use it as long as we aren't trying to use denormals. 7412 // 7413 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7414 7415 // 1.0 / sqrt(x) -> rsq(x) 7416 7417 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7418 // error seems really high at 2^29 ULP. 7419 if (RHS.getOpcode() == ISD::FSQRT) 7420 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7421 7422 // 1.0 / x -> rcp(x) 7423 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7424 } 7425 7426 // Same as for 1.0, but expand the sign out of the constant. 7427 if (CLHS->isExactlyValue(-1.0)) { 7428 // -1.0 / x -> rcp (fneg x) 7429 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7430 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7431 } 7432 } 7433 } 7434 7435 if (Unsafe) { 7436 // Turn into multiply by the reciprocal. 7437 // x / y -> x * (1.0 / y) 7438 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7439 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7440 } 7441 7442 return SDValue(); 7443 } 7444 7445 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7446 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7447 if (GlueChain->getNumValues() <= 1) { 7448 return DAG.getNode(Opcode, SL, VT, A, B); 7449 } 7450 7451 assert(GlueChain->getNumValues() == 3); 7452 7453 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7454 switch (Opcode) { 7455 default: llvm_unreachable("no chain equivalent for opcode"); 7456 case ISD::FMUL: 7457 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7458 break; 7459 } 7460 7461 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7462 GlueChain.getValue(2)); 7463 } 7464 7465 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7466 EVT VT, SDValue A, SDValue B, SDValue C, 7467 SDValue GlueChain) { 7468 if (GlueChain->getNumValues() <= 1) { 7469 return DAG.getNode(Opcode, SL, VT, A, B, C); 7470 } 7471 7472 assert(GlueChain->getNumValues() == 3); 7473 7474 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7475 switch (Opcode) { 7476 default: llvm_unreachable("no chain equivalent for opcode"); 7477 case ISD::FMA: 7478 Opcode = AMDGPUISD::FMA_W_CHAIN; 7479 break; 7480 } 7481 7482 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7483 GlueChain.getValue(2)); 7484 } 7485 7486 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7487 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7488 return FastLowered; 7489 7490 SDLoc SL(Op); 7491 SDValue Src0 = Op.getOperand(0); 7492 SDValue Src1 = Op.getOperand(1); 7493 7494 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7495 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7496 7497 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7498 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7499 7500 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7501 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7502 7503 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7504 } 7505 7506 // Faster 2.5 ULP division that does not support denormals. 7507 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7508 SDLoc SL(Op); 7509 SDValue LHS = Op.getOperand(1); 7510 SDValue RHS = Op.getOperand(2); 7511 7512 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7513 7514 const APFloat K0Val(BitsToFloat(0x6f800000)); 7515 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7516 7517 const APFloat K1Val(BitsToFloat(0x2f800000)); 7518 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7519 7520 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7521 7522 EVT SetCCVT = 7523 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7524 7525 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7526 7527 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7528 7529 // TODO: Should this propagate fast-math-flags? 7530 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7531 7532 // rcp does not support denormals. 7533 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7534 7535 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7536 7537 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7538 } 7539 7540 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7541 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7542 return FastLowered; 7543 7544 SDLoc SL(Op); 7545 SDValue LHS = Op.getOperand(0); 7546 SDValue RHS = Op.getOperand(1); 7547 7548 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7549 7550 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7551 7552 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7553 RHS, RHS, LHS); 7554 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7555 LHS, RHS, LHS); 7556 7557 // Denominator is scaled to not be denormal, so using rcp is ok. 7558 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7559 DenominatorScaled); 7560 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7561 DenominatorScaled); 7562 7563 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7564 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7565 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7566 7567 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7568 7569 if (!Subtarget->hasFP32Denormals()) { 7570 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7571 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7572 SL, MVT::i32); 7573 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7574 DAG.getEntryNode(), 7575 EnableDenormValue, BitField); 7576 SDValue Ops[3] = { 7577 NegDivScale0, 7578 EnableDenorm.getValue(0), 7579 EnableDenorm.getValue(1) 7580 }; 7581 7582 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7583 } 7584 7585 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7586 ApproxRcp, One, NegDivScale0); 7587 7588 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7589 ApproxRcp, Fma0); 7590 7591 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7592 Fma1, Fma1); 7593 7594 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7595 NumeratorScaled, Mul); 7596 7597 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7598 7599 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7600 NumeratorScaled, Fma3); 7601 7602 if (!Subtarget->hasFP32Denormals()) { 7603 const SDValue DisableDenormValue = 7604 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7605 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7606 Fma4.getValue(1), 7607 DisableDenormValue, 7608 BitField, 7609 Fma4.getValue(2)); 7610 7611 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7612 DisableDenorm, DAG.getRoot()); 7613 DAG.setRoot(OutputChain); 7614 } 7615 7616 SDValue Scale = NumeratorScaled.getValue(1); 7617 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7618 Fma4, Fma1, Fma3, Scale); 7619 7620 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7621 } 7622 7623 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7624 if (DAG.getTarget().Options.UnsafeFPMath) 7625 return lowerFastUnsafeFDIV(Op, DAG); 7626 7627 SDLoc SL(Op); 7628 SDValue X = Op.getOperand(0); 7629 SDValue Y = Op.getOperand(1); 7630 7631 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7632 7633 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7634 7635 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7636 7637 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7638 7639 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7640 7641 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7642 7643 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7644 7645 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7646 7647 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7648 7649 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7650 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7651 7652 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7653 NegDivScale0, Mul, DivScale1); 7654 7655 SDValue Scale; 7656 7657 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7658 // Workaround a hardware bug on SI where the condition output from div_scale 7659 // is not usable. 7660 7661 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7662 7663 // Figure out if the scale to use for div_fmas. 7664 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7665 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7666 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7667 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7668 7669 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7670 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7671 7672 SDValue Scale0Hi 7673 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7674 SDValue Scale1Hi 7675 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7676 7677 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7678 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7679 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7680 } else { 7681 Scale = DivScale1.getValue(1); 7682 } 7683 7684 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7685 Fma4, Fma3, Mul, Scale); 7686 7687 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7688 } 7689 7690 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7691 EVT VT = Op.getValueType(); 7692 7693 if (VT == MVT::f32) 7694 return LowerFDIV32(Op, DAG); 7695 7696 if (VT == MVT::f64) 7697 return LowerFDIV64(Op, DAG); 7698 7699 if (VT == MVT::f16) 7700 return LowerFDIV16(Op, DAG); 7701 7702 llvm_unreachable("Unexpected type for fdiv"); 7703 } 7704 7705 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7706 SDLoc DL(Op); 7707 StoreSDNode *Store = cast<StoreSDNode>(Op); 7708 EVT VT = Store->getMemoryVT(); 7709 7710 if (VT == MVT::i1) { 7711 return DAG.getTruncStore(Store->getChain(), DL, 7712 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7713 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7714 } 7715 7716 assert(VT.isVector() && 7717 Store->getValue().getValueType().getScalarType() == MVT::i32); 7718 7719 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7720 *Store->getMemOperand())) { 7721 return expandUnalignedStore(Store, DAG); 7722 } 7723 7724 unsigned AS = Store->getAddressSpace(); 7725 if (Subtarget->hasLDSMisalignedBug() && 7726 AS == AMDGPUAS::FLAT_ADDRESS && 7727 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7728 return SplitVectorStore(Op, DAG); 7729 } 7730 7731 MachineFunction &MF = DAG.getMachineFunction(); 7732 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7733 // If there is a possibilty that flat instruction access scratch memory 7734 // then we need to use the same legalization rules we use for private. 7735 if (AS == AMDGPUAS::FLAT_ADDRESS) 7736 AS = MFI->hasFlatScratchInit() ? 7737 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7738 7739 unsigned NumElements = VT.getVectorNumElements(); 7740 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7741 AS == AMDGPUAS::FLAT_ADDRESS) { 7742 if (NumElements > 4) 7743 return SplitVectorStore(Op, DAG); 7744 // v3 stores not supported on SI. 7745 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7746 return SplitVectorStore(Op, DAG); 7747 return SDValue(); 7748 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7749 switch (Subtarget->getMaxPrivateElementSize()) { 7750 case 4: 7751 return scalarizeVectorStore(Store, DAG); 7752 case 8: 7753 if (NumElements > 2) 7754 return SplitVectorStore(Op, DAG); 7755 return SDValue(); 7756 case 16: 7757 if (NumElements > 4 || NumElements == 3) 7758 return SplitVectorStore(Op, DAG); 7759 return SDValue(); 7760 default: 7761 llvm_unreachable("unsupported private_element_size"); 7762 } 7763 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7764 // Use ds_write_b128 if possible. 7765 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7766 VT.getStoreSize() == 16 && NumElements != 3) 7767 return SDValue(); 7768 7769 if (NumElements > 2) 7770 return SplitVectorStore(Op, DAG); 7771 7772 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7773 // address is negative, then the instruction is incorrectly treated as 7774 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7775 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7776 // store later in the SILoadStoreOptimizer. 7777 if (!Subtarget->hasUsableDSOffset() && 7778 NumElements == 2 && VT.getStoreSize() == 8 && 7779 Store->getAlignment() < 8) { 7780 return SplitVectorStore(Op, DAG); 7781 } 7782 7783 return SDValue(); 7784 } else { 7785 llvm_unreachable("unhandled address space"); 7786 } 7787 } 7788 7789 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7790 SDLoc DL(Op); 7791 EVT VT = Op.getValueType(); 7792 SDValue Arg = Op.getOperand(0); 7793 SDValue TrigVal; 7794 7795 // TODO: Should this propagate fast-math-flags? 7796 7797 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7798 7799 if (Subtarget->hasTrigReducedRange()) { 7800 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7801 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7802 } else { 7803 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7804 } 7805 7806 switch (Op.getOpcode()) { 7807 case ISD::FCOS: 7808 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7809 case ISD::FSIN: 7810 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7811 default: 7812 llvm_unreachable("Wrong trig opcode"); 7813 } 7814 } 7815 7816 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7817 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7818 assert(AtomicNode->isCompareAndSwap()); 7819 unsigned AS = AtomicNode->getAddressSpace(); 7820 7821 // No custom lowering required for local address space 7822 if (!isFlatGlobalAddrSpace(AS)) 7823 return Op; 7824 7825 // Non-local address space requires custom lowering for atomic compare 7826 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7827 SDLoc DL(Op); 7828 SDValue ChainIn = Op.getOperand(0); 7829 SDValue Addr = Op.getOperand(1); 7830 SDValue Old = Op.getOperand(2); 7831 SDValue New = Op.getOperand(3); 7832 EVT VT = Op.getValueType(); 7833 MVT SimpleVT = VT.getSimpleVT(); 7834 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7835 7836 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7837 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7838 7839 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7840 Ops, VT, AtomicNode->getMemOperand()); 7841 } 7842 7843 //===----------------------------------------------------------------------===// 7844 // Custom DAG optimizations 7845 //===----------------------------------------------------------------------===// 7846 7847 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7848 DAGCombinerInfo &DCI) const { 7849 EVT VT = N->getValueType(0); 7850 EVT ScalarVT = VT.getScalarType(); 7851 if (ScalarVT != MVT::f32) 7852 return SDValue(); 7853 7854 SelectionDAG &DAG = DCI.DAG; 7855 SDLoc DL(N); 7856 7857 SDValue Src = N->getOperand(0); 7858 EVT SrcVT = Src.getValueType(); 7859 7860 // TODO: We could try to match extracting the higher bytes, which would be 7861 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7862 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7863 // about in practice. 7864 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7865 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7866 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7867 DCI.AddToWorklist(Cvt.getNode()); 7868 return Cvt; 7869 } 7870 } 7871 7872 return SDValue(); 7873 } 7874 7875 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7876 7877 // This is a variant of 7878 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7879 // 7880 // The normal DAG combiner will do this, but only if the add has one use since 7881 // that would increase the number of instructions. 7882 // 7883 // This prevents us from seeing a constant offset that can be folded into a 7884 // memory instruction's addressing mode. If we know the resulting add offset of 7885 // a pointer can be folded into an addressing offset, we can replace the pointer 7886 // operand with the add of new constant offset. This eliminates one of the uses, 7887 // and may allow the remaining use to also be simplified. 7888 // 7889 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7890 unsigned AddrSpace, 7891 EVT MemVT, 7892 DAGCombinerInfo &DCI) const { 7893 SDValue N0 = N->getOperand(0); 7894 SDValue N1 = N->getOperand(1); 7895 7896 // We only do this to handle cases where it's profitable when there are 7897 // multiple uses of the add, so defer to the standard combine. 7898 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7899 N0->hasOneUse()) 7900 return SDValue(); 7901 7902 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7903 if (!CN1) 7904 return SDValue(); 7905 7906 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7907 if (!CAdd) 7908 return SDValue(); 7909 7910 // If the resulting offset is too large, we can't fold it into the addressing 7911 // mode offset. 7912 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7913 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7914 7915 AddrMode AM; 7916 AM.HasBaseReg = true; 7917 AM.BaseOffs = Offset.getSExtValue(); 7918 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7919 return SDValue(); 7920 7921 SelectionDAG &DAG = DCI.DAG; 7922 SDLoc SL(N); 7923 EVT VT = N->getValueType(0); 7924 7925 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 7926 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 7927 7928 SDNodeFlags Flags; 7929 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 7930 (N0.getOpcode() == ISD::OR || 7931 N0->getFlags().hasNoUnsignedWrap())); 7932 7933 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 7934 } 7935 7936 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 7937 DAGCombinerInfo &DCI) const { 7938 SDValue Ptr = N->getBasePtr(); 7939 SelectionDAG &DAG = DCI.DAG; 7940 SDLoc SL(N); 7941 7942 // TODO: We could also do this for multiplies. 7943 if (Ptr.getOpcode() == ISD::SHL) { 7944 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 7945 N->getMemoryVT(), DCI); 7946 if (NewPtr) { 7947 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 7948 7949 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 7950 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 7951 } 7952 } 7953 7954 return SDValue(); 7955 } 7956 7957 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 7958 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 7959 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 7960 (Opc == ISD::XOR && Val == 0); 7961 } 7962 7963 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 7964 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 7965 // integer combine opportunities since most 64-bit operations are decomposed 7966 // this way. TODO: We won't want this for SALU especially if it is an inline 7967 // immediate. 7968 SDValue SITargetLowering::splitBinaryBitConstantOp( 7969 DAGCombinerInfo &DCI, 7970 const SDLoc &SL, 7971 unsigned Opc, SDValue LHS, 7972 const ConstantSDNode *CRHS) const { 7973 uint64_t Val = CRHS->getZExtValue(); 7974 uint32_t ValLo = Lo_32(Val); 7975 uint32_t ValHi = Hi_32(Val); 7976 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7977 7978 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 7979 bitOpWithConstantIsReducible(Opc, ValHi)) || 7980 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 7981 // If we need to materialize a 64-bit immediate, it will be split up later 7982 // anyway. Avoid creating the harder to understand 64-bit immediate 7983 // materialization. 7984 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 7985 } 7986 7987 return SDValue(); 7988 } 7989 7990 // Returns true if argument is a boolean value which is not serialized into 7991 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 7992 static bool isBoolSGPR(SDValue V) { 7993 if (V.getValueType() != MVT::i1) 7994 return false; 7995 switch (V.getOpcode()) { 7996 default: break; 7997 case ISD::SETCC: 7998 case ISD::AND: 7999 case ISD::OR: 8000 case ISD::XOR: 8001 case AMDGPUISD::FP_CLASS: 8002 return true; 8003 } 8004 return false; 8005 } 8006 8007 // If a constant has all zeroes or all ones within each byte return it. 8008 // Otherwise return 0. 8009 static uint32_t getConstantPermuteMask(uint32_t C) { 8010 // 0xff for any zero byte in the mask 8011 uint32_t ZeroByteMask = 0; 8012 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8013 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8014 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8015 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8016 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8017 if ((NonZeroByteMask & C) != NonZeroByteMask) 8018 return 0; // Partial bytes selected. 8019 return C; 8020 } 8021 8022 // Check if a node selects whole bytes from its operand 0 starting at a byte 8023 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8024 // or -1 if not succeeded. 8025 // Note byte select encoding: 8026 // value 0-3 selects corresponding source byte; 8027 // value 0xc selects zero; 8028 // value 0xff selects 0xff. 8029 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8030 assert(V.getValueSizeInBits() == 32); 8031 8032 if (V.getNumOperands() != 2) 8033 return ~0; 8034 8035 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8036 if (!N1) 8037 return ~0; 8038 8039 uint32_t C = N1->getZExtValue(); 8040 8041 switch (V.getOpcode()) { 8042 default: 8043 break; 8044 case ISD::AND: 8045 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8046 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8047 } 8048 break; 8049 8050 case ISD::OR: 8051 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8052 return (0x03020100 & ~ConstMask) | ConstMask; 8053 } 8054 break; 8055 8056 case ISD::SHL: 8057 if (C % 8) 8058 return ~0; 8059 8060 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8061 8062 case ISD::SRL: 8063 if (C % 8) 8064 return ~0; 8065 8066 return uint32_t(0x0c0c0c0c03020100ull >> C); 8067 } 8068 8069 return ~0; 8070 } 8071 8072 SDValue SITargetLowering::performAndCombine(SDNode *N, 8073 DAGCombinerInfo &DCI) const { 8074 if (DCI.isBeforeLegalize()) 8075 return SDValue(); 8076 8077 SelectionDAG &DAG = DCI.DAG; 8078 EVT VT = N->getValueType(0); 8079 SDValue LHS = N->getOperand(0); 8080 SDValue RHS = N->getOperand(1); 8081 8082 8083 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8084 if (VT == MVT::i64 && CRHS) { 8085 if (SDValue Split 8086 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8087 return Split; 8088 } 8089 8090 if (CRHS && VT == MVT::i32) { 8091 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8092 // nb = number of trailing zeroes in mask 8093 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8094 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8095 uint64_t Mask = CRHS->getZExtValue(); 8096 unsigned Bits = countPopulation(Mask); 8097 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8098 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8099 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8100 unsigned Shift = CShift->getZExtValue(); 8101 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8102 unsigned Offset = NB + Shift; 8103 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8104 SDLoc SL(N); 8105 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8106 LHS->getOperand(0), 8107 DAG.getConstant(Offset, SL, MVT::i32), 8108 DAG.getConstant(Bits, SL, MVT::i32)); 8109 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8110 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8111 DAG.getValueType(NarrowVT)); 8112 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8113 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8114 return Shl; 8115 } 8116 } 8117 } 8118 8119 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8120 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8121 isa<ConstantSDNode>(LHS.getOperand(2))) { 8122 uint32_t Sel = getConstantPermuteMask(Mask); 8123 if (!Sel) 8124 return SDValue(); 8125 8126 // Select 0xc for all zero bytes 8127 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8128 SDLoc DL(N); 8129 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8130 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8131 } 8132 } 8133 8134 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8135 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8136 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8137 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8138 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8139 8140 SDValue X = LHS.getOperand(0); 8141 SDValue Y = RHS.getOperand(0); 8142 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8143 return SDValue(); 8144 8145 if (LCC == ISD::SETO) { 8146 if (X != LHS.getOperand(1)) 8147 return SDValue(); 8148 8149 if (RCC == ISD::SETUNE) { 8150 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8151 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8152 return SDValue(); 8153 8154 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8155 SIInstrFlags::N_SUBNORMAL | 8156 SIInstrFlags::N_ZERO | 8157 SIInstrFlags::P_ZERO | 8158 SIInstrFlags::P_SUBNORMAL | 8159 SIInstrFlags::P_NORMAL; 8160 8161 static_assert(((~(SIInstrFlags::S_NAN | 8162 SIInstrFlags::Q_NAN | 8163 SIInstrFlags::N_INFINITY | 8164 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8165 "mask not equal"); 8166 8167 SDLoc DL(N); 8168 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8169 X, DAG.getConstant(Mask, DL, MVT::i32)); 8170 } 8171 } 8172 } 8173 8174 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8175 std::swap(LHS, RHS); 8176 8177 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8178 RHS.hasOneUse()) { 8179 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8180 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8181 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8182 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8183 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8184 (RHS.getOperand(0) == LHS.getOperand(0) && 8185 LHS.getOperand(0) == LHS.getOperand(1))) { 8186 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8187 unsigned NewMask = LCC == ISD::SETO ? 8188 Mask->getZExtValue() & ~OrdMask : 8189 Mask->getZExtValue() & OrdMask; 8190 8191 SDLoc DL(N); 8192 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8193 DAG.getConstant(NewMask, DL, MVT::i32)); 8194 } 8195 } 8196 8197 if (VT == MVT::i32 && 8198 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8199 // and x, (sext cc from i1) => select cc, x, 0 8200 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8201 std::swap(LHS, RHS); 8202 if (isBoolSGPR(RHS.getOperand(0))) 8203 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8204 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8205 } 8206 8207 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8208 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8209 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8210 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8211 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8212 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8213 if (LHSMask != ~0u && RHSMask != ~0u) { 8214 // Canonicalize the expression in an attempt to have fewer unique masks 8215 // and therefore fewer registers used to hold the masks. 8216 if (LHSMask > RHSMask) { 8217 std::swap(LHSMask, RHSMask); 8218 std::swap(LHS, RHS); 8219 } 8220 8221 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8222 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8223 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8224 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8225 8226 // Check of we need to combine values from two sources within a byte. 8227 if (!(LHSUsedLanes & RHSUsedLanes) && 8228 // If we select high and lower word keep it for SDWA. 8229 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8230 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8231 // Each byte in each mask is either selector mask 0-3, or has higher 8232 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8233 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8234 // mask which is not 0xff wins. By anding both masks we have a correct 8235 // result except that 0x0c shall be corrected to give 0x0c only. 8236 uint32_t Mask = LHSMask & RHSMask; 8237 for (unsigned I = 0; I < 32; I += 8) { 8238 uint32_t ByteSel = 0xff << I; 8239 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8240 Mask &= (0x0c << I) & 0xffffffff; 8241 } 8242 8243 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8244 // or 0x0c. 8245 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8246 SDLoc DL(N); 8247 8248 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8249 LHS.getOperand(0), RHS.getOperand(0), 8250 DAG.getConstant(Sel, DL, MVT::i32)); 8251 } 8252 } 8253 } 8254 8255 return SDValue(); 8256 } 8257 8258 SDValue SITargetLowering::performOrCombine(SDNode *N, 8259 DAGCombinerInfo &DCI) const { 8260 SelectionDAG &DAG = DCI.DAG; 8261 SDValue LHS = N->getOperand(0); 8262 SDValue RHS = N->getOperand(1); 8263 8264 EVT VT = N->getValueType(0); 8265 if (VT == MVT::i1) { 8266 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8267 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8268 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8269 SDValue Src = LHS.getOperand(0); 8270 if (Src != RHS.getOperand(0)) 8271 return SDValue(); 8272 8273 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8274 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8275 if (!CLHS || !CRHS) 8276 return SDValue(); 8277 8278 // Only 10 bits are used. 8279 static const uint32_t MaxMask = 0x3ff; 8280 8281 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8282 SDLoc DL(N); 8283 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8284 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8285 } 8286 8287 return SDValue(); 8288 } 8289 8290 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8291 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8292 LHS.getOpcode() == AMDGPUISD::PERM && 8293 isa<ConstantSDNode>(LHS.getOperand(2))) { 8294 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8295 if (!Sel) 8296 return SDValue(); 8297 8298 Sel |= LHS.getConstantOperandVal(2); 8299 SDLoc DL(N); 8300 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8301 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8302 } 8303 8304 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8305 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8306 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8307 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8308 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8309 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8310 if (LHSMask != ~0u && RHSMask != ~0u) { 8311 // Canonicalize the expression in an attempt to have fewer unique masks 8312 // and therefore fewer registers used to hold the masks. 8313 if (LHSMask > RHSMask) { 8314 std::swap(LHSMask, RHSMask); 8315 std::swap(LHS, RHS); 8316 } 8317 8318 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8319 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8320 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8321 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8322 8323 // Check of we need to combine values from two sources within a byte. 8324 if (!(LHSUsedLanes & RHSUsedLanes) && 8325 // If we select high and lower word keep it for SDWA. 8326 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8327 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8328 // Kill zero bytes selected by other mask. Zero value is 0xc. 8329 LHSMask &= ~RHSUsedLanes; 8330 RHSMask &= ~LHSUsedLanes; 8331 // Add 4 to each active LHS lane 8332 LHSMask |= LHSUsedLanes & 0x04040404; 8333 // Combine masks 8334 uint32_t Sel = LHSMask | RHSMask; 8335 SDLoc DL(N); 8336 8337 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8338 LHS.getOperand(0), RHS.getOperand(0), 8339 DAG.getConstant(Sel, DL, MVT::i32)); 8340 } 8341 } 8342 } 8343 8344 if (VT != MVT::i64) 8345 return SDValue(); 8346 8347 // TODO: This could be a generic combine with a predicate for extracting the 8348 // high half of an integer being free. 8349 8350 // (or i64:x, (zero_extend i32:y)) -> 8351 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8352 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8353 RHS.getOpcode() != ISD::ZERO_EXTEND) 8354 std::swap(LHS, RHS); 8355 8356 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8357 SDValue ExtSrc = RHS.getOperand(0); 8358 EVT SrcVT = ExtSrc.getValueType(); 8359 if (SrcVT == MVT::i32) { 8360 SDLoc SL(N); 8361 SDValue LowLHS, HiBits; 8362 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8363 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8364 8365 DCI.AddToWorklist(LowOr.getNode()); 8366 DCI.AddToWorklist(HiBits.getNode()); 8367 8368 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8369 LowOr, HiBits); 8370 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8371 } 8372 } 8373 8374 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8375 if (CRHS) { 8376 if (SDValue Split 8377 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8378 return Split; 8379 } 8380 8381 return SDValue(); 8382 } 8383 8384 SDValue SITargetLowering::performXorCombine(SDNode *N, 8385 DAGCombinerInfo &DCI) const { 8386 EVT VT = N->getValueType(0); 8387 if (VT != MVT::i64) 8388 return SDValue(); 8389 8390 SDValue LHS = N->getOperand(0); 8391 SDValue RHS = N->getOperand(1); 8392 8393 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8394 if (CRHS) { 8395 if (SDValue Split 8396 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8397 return Split; 8398 } 8399 8400 return SDValue(); 8401 } 8402 8403 // Instructions that will be lowered with a final instruction that zeros the 8404 // high result bits. 8405 // XXX - probably only need to list legal operations. 8406 static bool fp16SrcZerosHighBits(unsigned Opc) { 8407 switch (Opc) { 8408 case ISD::FADD: 8409 case ISD::FSUB: 8410 case ISD::FMUL: 8411 case ISD::FDIV: 8412 case ISD::FREM: 8413 case ISD::FMA: 8414 case ISD::FMAD: 8415 case ISD::FCANONICALIZE: 8416 case ISD::FP_ROUND: 8417 case ISD::UINT_TO_FP: 8418 case ISD::SINT_TO_FP: 8419 case ISD::FABS: 8420 // Fabs is lowered to a bit operation, but it's an and which will clear the 8421 // high bits anyway. 8422 case ISD::FSQRT: 8423 case ISD::FSIN: 8424 case ISD::FCOS: 8425 case ISD::FPOWI: 8426 case ISD::FPOW: 8427 case ISD::FLOG: 8428 case ISD::FLOG2: 8429 case ISD::FLOG10: 8430 case ISD::FEXP: 8431 case ISD::FEXP2: 8432 case ISD::FCEIL: 8433 case ISD::FTRUNC: 8434 case ISD::FRINT: 8435 case ISD::FNEARBYINT: 8436 case ISD::FROUND: 8437 case ISD::FFLOOR: 8438 case ISD::FMINNUM: 8439 case ISD::FMAXNUM: 8440 case AMDGPUISD::FRACT: 8441 case AMDGPUISD::CLAMP: 8442 case AMDGPUISD::COS_HW: 8443 case AMDGPUISD::SIN_HW: 8444 case AMDGPUISD::FMIN3: 8445 case AMDGPUISD::FMAX3: 8446 case AMDGPUISD::FMED3: 8447 case AMDGPUISD::FMAD_FTZ: 8448 case AMDGPUISD::RCP: 8449 case AMDGPUISD::RSQ: 8450 case AMDGPUISD::RCP_IFLAG: 8451 case AMDGPUISD::LDEXP: 8452 return true; 8453 default: 8454 // fcopysign, select and others may be lowered to 32-bit bit operations 8455 // which don't zero the high bits. 8456 return false; 8457 } 8458 } 8459 8460 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8461 DAGCombinerInfo &DCI) const { 8462 if (!Subtarget->has16BitInsts() || 8463 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8464 return SDValue(); 8465 8466 EVT VT = N->getValueType(0); 8467 if (VT != MVT::i32) 8468 return SDValue(); 8469 8470 SDValue Src = N->getOperand(0); 8471 if (Src.getValueType() != MVT::i16) 8472 return SDValue(); 8473 8474 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8475 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8476 if (Src.getOpcode() == ISD::BITCAST) { 8477 SDValue BCSrc = Src.getOperand(0); 8478 if (BCSrc.getValueType() == MVT::f16 && 8479 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8480 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8481 } 8482 8483 return SDValue(); 8484 } 8485 8486 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8487 DAGCombinerInfo &DCI) 8488 const { 8489 SDValue Src = N->getOperand(0); 8490 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8491 8492 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8493 VTSign->getVT() == MVT::i8) || 8494 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8495 VTSign->getVT() == MVT::i16)) && 8496 Src.hasOneUse()) { 8497 auto *M = cast<MemSDNode>(Src); 8498 SDValue Ops[] = { 8499 Src.getOperand(0), // Chain 8500 Src.getOperand(1), // rsrc 8501 Src.getOperand(2), // vindex 8502 Src.getOperand(3), // voffset 8503 Src.getOperand(4), // soffset 8504 Src.getOperand(5), // offset 8505 Src.getOperand(6), 8506 Src.getOperand(7) 8507 }; 8508 // replace with BUFFER_LOAD_BYTE/SHORT 8509 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8510 Src.getOperand(0).getValueType()); 8511 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8512 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8513 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8514 ResList, 8515 Ops, M->getMemoryVT(), 8516 M->getMemOperand()); 8517 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8518 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8519 } 8520 return SDValue(); 8521 } 8522 8523 SDValue SITargetLowering::performClassCombine(SDNode *N, 8524 DAGCombinerInfo &DCI) const { 8525 SelectionDAG &DAG = DCI.DAG; 8526 SDValue Mask = N->getOperand(1); 8527 8528 // fp_class x, 0 -> false 8529 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8530 if (CMask->isNullValue()) 8531 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8532 } 8533 8534 if (N->getOperand(0).isUndef()) 8535 return DAG.getUNDEF(MVT::i1); 8536 8537 return SDValue(); 8538 } 8539 8540 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8541 DAGCombinerInfo &DCI) const { 8542 EVT VT = N->getValueType(0); 8543 SDValue N0 = N->getOperand(0); 8544 8545 if (N0.isUndef()) 8546 return N0; 8547 8548 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8549 N0.getOpcode() == ISD::SINT_TO_FP)) { 8550 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8551 N->getFlags()); 8552 } 8553 8554 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8555 } 8556 8557 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8558 unsigned MaxDepth) const { 8559 unsigned Opcode = Op.getOpcode(); 8560 if (Opcode == ISD::FCANONICALIZE) 8561 return true; 8562 8563 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8564 auto F = CFP->getValueAPF(); 8565 if (F.isNaN() && F.isSignaling()) 8566 return false; 8567 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 8568 } 8569 8570 // If source is a result of another standard FP operation it is already in 8571 // canonical form. 8572 if (MaxDepth == 0) 8573 return false; 8574 8575 switch (Opcode) { 8576 // These will flush denorms if required. 8577 case ISD::FADD: 8578 case ISD::FSUB: 8579 case ISD::FMUL: 8580 case ISD::FCEIL: 8581 case ISD::FFLOOR: 8582 case ISD::FMA: 8583 case ISD::FMAD: 8584 case ISD::FSQRT: 8585 case ISD::FDIV: 8586 case ISD::FREM: 8587 case ISD::FP_ROUND: 8588 case ISD::FP_EXTEND: 8589 case AMDGPUISD::FMUL_LEGACY: 8590 case AMDGPUISD::FMAD_FTZ: 8591 case AMDGPUISD::RCP: 8592 case AMDGPUISD::RSQ: 8593 case AMDGPUISD::RSQ_CLAMP: 8594 case AMDGPUISD::RCP_LEGACY: 8595 case AMDGPUISD::RSQ_LEGACY: 8596 case AMDGPUISD::RCP_IFLAG: 8597 case AMDGPUISD::TRIG_PREOP: 8598 case AMDGPUISD::DIV_SCALE: 8599 case AMDGPUISD::DIV_FMAS: 8600 case AMDGPUISD::DIV_FIXUP: 8601 case AMDGPUISD::FRACT: 8602 case AMDGPUISD::LDEXP: 8603 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8604 case AMDGPUISD::CVT_F32_UBYTE0: 8605 case AMDGPUISD::CVT_F32_UBYTE1: 8606 case AMDGPUISD::CVT_F32_UBYTE2: 8607 case AMDGPUISD::CVT_F32_UBYTE3: 8608 return true; 8609 8610 // It can/will be lowered or combined as a bit operation. 8611 // Need to check their input recursively to handle. 8612 case ISD::FNEG: 8613 case ISD::FABS: 8614 case ISD::FCOPYSIGN: 8615 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8616 8617 case ISD::FSIN: 8618 case ISD::FCOS: 8619 case ISD::FSINCOS: 8620 return Op.getValueType().getScalarType() != MVT::f16; 8621 8622 case ISD::FMINNUM: 8623 case ISD::FMAXNUM: 8624 case ISD::FMINNUM_IEEE: 8625 case ISD::FMAXNUM_IEEE: 8626 case AMDGPUISD::CLAMP: 8627 case AMDGPUISD::FMED3: 8628 case AMDGPUISD::FMAX3: 8629 case AMDGPUISD::FMIN3: { 8630 // FIXME: Shouldn't treat the generic operations different based these. 8631 // However, we aren't really required to flush the result from 8632 // minnum/maxnum.. 8633 8634 // snans will be quieted, so we only need to worry about denormals. 8635 if (Subtarget->supportsMinMaxDenormModes() || 8636 denormalsEnabledForType(Op.getValueType())) 8637 return true; 8638 8639 // Flushing may be required. 8640 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8641 // targets need to check their input recursively. 8642 8643 // FIXME: Does this apply with clamp? It's implemented with max. 8644 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8645 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8646 return false; 8647 } 8648 8649 return true; 8650 } 8651 case ISD::SELECT: { 8652 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8653 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8654 } 8655 case ISD::BUILD_VECTOR: { 8656 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8657 SDValue SrcOp = Op.getOperand(i); 8658 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8659 return false; 8660 } 8661 8662 return true; 8663 } 8664 case ISD::EXTRACT_VECTOR_ELT: 8665 case ISD::EXTRACT_SUBVECTOR: { 8666 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8667 } 8668 case ISD::INSERT_VECTOR_ELT: { 8669 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8670 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8671 } 8672 case ISD::UNDEF: 8673 // Could be anything. 8674 return false; 8675 8676 case ISD::BITCAST: { 8677 // Hack round the mess we make when legalizing extract_vector_elt 8678 SDValue Src = Op.getOperand(0); 8679 if (Src.getValueType() == MVT::i16 && 8680 Src.getOpcode() == ISD::TRUNCATE) { 8681 SDValue TruncSrc = Src.getOperand(0); 8682 if (TruncSrc.getValueType() == MVT::i32 && 8683 TruncSrc.getOpcode() == ISD::BITCAST && 8684 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8685 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8686 } 8687 } 8688 8689 return false; 8690 } 8691 case ISD::INTRINSIC_WO_CHAIN: { 8692 unsigned IntrinsicID 8693 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8694 // TODO: Handle more intrinsics 8695 switch (IntrinsicID) { 8696 case Intrinsic::amdgcn_cvt_pkrtz: 8697 case Intrinsic::amdgcn_cubeid: 8698 case Intrinsic::amdgcn_frexp_mant: 8699 case Intrinsic::amdgcn_fdot2: 8700 return true; 8701 default: 8702 break; 8703 } 8704 8705 LLVM_FALLTHROUGH; 8706 } 8707 default: 8708 return denormalsEnabledForType(Op.getValueType()) && 8709 DAG.isKnownNeverSNaN(Op); 8710 } 8711 8712 llvm_unreachable("invalid operation"); 8713 } 8714 8715 // Constant fold canonicalize. 8716 SDValue SITargetLowering::getCanonicalConstantFP( 8717 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8718 // Flush denormals to 0 if not enabled. 8719 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8720 return DAG.getConstantFP(0.0, SL, VT); 8721 8722 if (C.isNaN()) { 8723 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8724 if (C.isSignaling()) { 8725 // Quiet a signaling NaN. 8726 // FIXME: Is this supposed to preserve payload bits? 8727 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8728 } 8729 8730 // Make sure it is the canonical NaN bitpattern. 8731 // 8732 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8733 // immediate? 8734 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8735 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8736 } 8737 8738 // Already canonical. 8739 return DAG.getConstantFP(C, SL, VT); 8740 } 8741 8742 static bool vectorEltWillFoldAway(SDValue Op) { 8743 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8744 } 8745 8746 SDValue SITargetLowering::performFCanonicalizeCombine( 8747 SDNode *N, 8748 DAGCombinerInfo &DCI) const { 8749 SelectionDAG &DAG = DCI.DAG; 8750 SDValue N0 = N->getOperand(0); 8751 EVT VT = N->getValueType(0); 8752 8753 // fcanonicalize undef -> qnan 8754 if (N0.isUndef()) { 8755 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8756 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8757 } 8758 8759 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8760 EVT VT = N->getValueType(0); 8761 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8762 } 8763 8764 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8765 // (fcanonicalize k) 8766 // 8767 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8768 8769 // TODO: This could be better with wider vectors that will be split to v2f16, 8770 // and to consider uses since there aren't that many packed operations. 8771 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8772 isTypeLegal(MVT::v2f16)) { 8773 SDLoc SL(N); 8774 SDValue NewElts[2]; 8775 SDValue Lo = N0.getOperand(0); 8776 SDValue Hi = N0.getOperand(1); 8777 EVT EltVT = Lo.getValueType(); 8778 8779 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8780 for (unsigned I = 0; I != 2; ++I) { 8781 SDValue Op = N0.getOperand(I); 8782 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8783 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8784 CFP->getValueAPF()); 8785 } else if (Op.isUndef()) { 8786 // Handled below based on what the other operand is. 8787 NewElts[I] = Op; 8788 } else { 8789 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8790 } 8791 } 8792 8793 // If one half is undef, and one is constant, perfer a splat vector rather 8794 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8795 // cheaper to use and may be free with a packed operation. 8796 if (NewElts[0].isUndef()) { 8797 if (isa<ConstantFPSDNode>(NewElts[1])) 8798 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8799 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8800 } 8801 8802 if (NewElts[1].isUndef()) { 8803 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8804 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8805 } 8806 8807 return DAG.getBuildVector(VT, SL, NewElts); 8808 } 8809 } 8810 8811 unsigned SrcOpc = N0.getOpcode(); 8812 8813 // If it's free to do so, push canonicalizes further up the source, which may 8814 // find a canonical source. 8815 // 8816 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8817 // sNaNs. 8818 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8819 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8820 if (CRHS && N0.hasOneUse()) { 8821 SDLoc SL(N); 8822 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8823 N0.getOperand(0)); 8824 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8825 DCI.AddToWorklist(Canon0.getNode()); 8826 8827 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8828 } 8829 } 8830 8831 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8832 } 8833 8834 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8835 switch (Opc) { 8836 case ISD::FMAXNUM: 8837 case ISD::FMAXNUM_IEEE: 8838 return AMDGPUISD::FMAX3; 8839 case ISD::SMAX: 8840 return AMDGPUISD::SMAX3; 8841 case ISD::UMAX: 8842 return AMDGPUISD::UMAX3; 8843 case ISD::FMINNUM: 8844 case ISD::FMINNUM_IEEE: 8845 return AMDGPUISD::FMIN3; 8846 case ISD::SMIN: 8847 return AMDGPUISD::SMIN3; 8848 case ISD::UMIN: 8849 return AMDGPUISD::UMIN3; 8850 default: 8851 llvm_unreachable("Not a min/max opcode"); 8852 } 8853 } 8854 8855 SDValue SITargetLowering::performIntMed3ImmCombine( 8856 SelectionDAG &DAG, const SDLoc &SL, 8857 SDValue Op0, SDValue Op1, bool Signed) const { 8858 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8859 if (!K1) 8860 return SDValue(); 8861 8862 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8863 if (!K0) 8864 return SDValue(); 8865 8866 if (Signed) { 8867 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8868 return SDValue(); 8869 } else { 8870 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8871 return SDValue(); 8872 } 8873 8874 EVT VT = K0->getValueType(0); 8875 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8876 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8877 return DAG.getNode(Med3Opc, SL, VT, 8878 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8879 } 8880 8881 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8882 MVT NVT = MVT::i32; 8883 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8884 8885 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8886 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8887 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8888 8889 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8890 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8891 } 8892 8893 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8894 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8895 return C; 8896 8897 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8898 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8899 return C; 8900 } 8901 8902 return nullptr; 8903 } 8904 8905 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8906 const SDLoc &SL, 8907 SDValue Op0, 8908 SDValue Op1) const { 8909 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8910 if (!K1) 8911 return SDValue(); 8912 8913 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8914 if (!K0) 8915 return SDValue(); 8916 8917 // Ordered >= (although NaN inputs should have folded away by now). 8918 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 8919 if (Cmp == APFloat::cmpGreaterThan) 8920 return SDValue(); 8921 8922 const MachineFunction &MF = DAG.getMachineFunction(); 8923 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8924 8925 // TODO: Check IEEE bit enabled? 8926 EVT VT = Op0.getValueType(); 8927 if (Info->getMode().DX10Clamp) { 8928 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 8929 // hardware fmed3 behavior converting to a min. 8930 // FIXME: Should this be allowing -0.0? 8931 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 8932 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 8933 } 8934 8935 // med3 for f16 is only available on gfx9+, and not available for v2f16. 8936 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 8937 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 8938 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 8939 // then give the other result, which is different from med3 with a NaN 8940 // input. 8941 SDValue Var = Op0.getOperand(0); 8942 if (!DAG.isKnownNeverSNaN(Var)) 8943 return SDValue(); 8944 8945 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8946 8947 if ((!K0->hasOneUse() || 8948 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 8949 (!K1->hasOneUse() || 8950 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 8951 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 8952 Var, SDValue(K0, 0), SDValue(K1, 0)); 8953 } 8954 } 8955 8956 return SDValue(); 8957 } 8958 8959 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 8960 DAGCombinerInfo &DCI) const { 8961 SelectionDAG &DAG = DCI.DAG; 8962 8963 EVT VT = N->getValueType(0); 8964 unsigned Opc = N->getOpcode(); 8965 SDValue Op0 = N->getOperand(0); 8966 SDValue Op1 = N->getOperand(1); 8967 8968 // Only do this if the inner op has one use since this will just increases 8969 // register pressure for no benefit. 8970 8971 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 8972 !VT.isVector() && 8973 (VT == MVT::i32 || VT == MVT::f32 || 8974 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 8975 // max(max(a, b), c) -> max3(a, b, c) 8976 // min(min(a, b), c) -> min3(a, b, c) 8977 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 8978 SDLoc DL(N); 8979 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8980 DL, 8981 N->getValueType(0), 8982 Op0.getOperand(0), 8983 Op0.getOperand(1), 8984 Op1); 8985 } 8986 8987 // Try commuted. 8988 // max(a, max(b, c)) -> max3(a, b, c) 8989 // min(a, min(b, c)) -> min3(a, b, c) 8990 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 8991 SDLoc DL(N); 8992 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8993 DL, 8994 N->getValueType(0), 8995 Op0, 8996 Op1.getOperand(0), 8997 Op1.getOperand(1)); 8998 } 8999 } 9000 9001 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9002 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9003 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9004 return Med3; 9005 } 9006 9007 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9008 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9009 return Med3; 9010 } 9011 9012 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9013 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9014 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9015 (Opc == AMDGPUISD::FMIN_LEGACY && 9016 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9017 (VT == MVT::f32 || VT == MVT::f64 || 9018 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9019 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9020 Op0.hasOneUse()) { 9021 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9022 return Res; 9023 } 9024 9025 return SDValue(); 9026 } 9027 9028 static bool isClampZeroToOne(SDValue A, SDValue B) { 9029 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9030 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9031 // FIXME: Should this be allowing -0.0? 9032 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9033 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9034 } 9035 } 9036 9037 return false; 9038 } 9039 9040 // FIXME: Should only worry about snans for version with chain. 9041 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9042 DAGCombinerInfo &DCI) const { 9043 EVT VT = N->getValueType(0); 9044 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9045 // NaNs. With a NaN input, the order of the operands may change the result. 9046 9047 SelectionDAG &DAG = DCI.DAG; 9048 SDLoc SL(N); 9049 9050 SDValue Src0 = N->getOperand(0); 9051 SDValue Src1 = N->getOperand(1); 9052 SDValue Src2 = N->getOperand(2); 9053 9054 if (isClampZeroToOne(Src0, Src1)) { 9055 // const_a, const_b, x -> clamp is safe in all cases including signaling 9056 // nans. 9057 // FIXME: Should this be allowing -0.0? 9058 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9059 } 9060 9061 const MachineFunction &MF = DAG.getMachineFunction(); 9062 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9063 9064 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9065 // handling no dx10-clamp? 9066 if (Info->getMode().DX10Clamp) { 9067 // If NaNs is clamped to 0, we are free to reorder the inputs. 9068 9069 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9070 std::swap(Src0, Src1); 9071 9072 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9073 std::swap(Src1, Src2); 9074 9075 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9076 std::swap(Src0, Src1); 9077 9078 if (isClampZeroToOne(Src1, Src2)) 9079 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9080 } 9081 9082 return SDValue(); 9083 } 9084 9085 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9086 DAGCombinerInfo &DCI) const { 9087 SDValue Src0 = N->getOperand(0); 9088 SDValue Src1 = N->getOperand(1); 9089 if (Src0.isUndef() && Src1.isUndef()) 9090 return DCI.DAG.getUNDEF(N->getValueType(0)); 9091 return SDValue(); 9092 } 9093 9094 SDValue SITargetLowering::performExtractVectorEltCombine( 9095 SDNode *N, DAGCombinerInfo &DCI) const { 9096 SDValue Vec = N->getOperand(0); 9097 SelectionDAG &DAG = DCI.DAG; 9098 9099 EVT VecVT = Vec.getValueType(); 9100 EVT EltVT = VecVT.getVectorElementType(); 9101 9102 if ((Vec.getOpcode() == ISD::FNEG || 9103 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9104 SDLoc SL(N); 9105 EVT EltVT = N->getValueType(0); 9106 SDValue Idx = N->getOperand(1); 9107 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9108 Vec.getOperand(0), Idx); 9109 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9110 } 9111 9112 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9113 // => 9114 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9115 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9116 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9117 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9118 SDLoc SL(N); 9119 EVT EltVT = N->getValueType(0); 9120 SDValue Idx = N->getOperand(1); 9121 unsigned Opc = Vec.getOpcode(); 9122 9123 switch(Opc) { 9124 default: 9125 break; 9126 // TODO: Support other binary operations. 9127 case ISD::FADD: 9128 case ISD::FSUB: 9129 case ISD::FMUL: 9130 case ISD::ADD: 9131 case ISD::UMIN: 9132 case ISD::UMAX: 9133 case ISD::SMIN: 9134 case ISD::SMAX: 9135 case ISD::FMAXNUM: 9136 case ISD::FMINNUM: 9137 case ISD::FMAXNUM_IEEE: 9138 case ISD::FMINNUM_IEEE: { 9139 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9140 Vec.getOperand(0), Idx); 9141 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9142 Vec.getOperand(1), Idx); 9143 9144 DCI.AddToWorklist(Elt0.getNode()); 9145 DCI.AddToWorklist(Elt1.getNode()); 9146 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9147 } 9148 } 9149 } 9150 9151 unsigned VecSize = VecVT.getSizeInBits(); 9152 unsigned EltSize = EltVT.getSizeInBits(); 9153 9154 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9155 // This elminates non-constant index and subsequent movrel or scratch access. 9156 // Sub-dword vectors of size 2 dword or less have better implementation. 9157 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9158 // instructions. 9159 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9160 !isa<ConstantSDNode>(N->getOperand(1))) { 9161 SDLoc SL(N); 9162 SDValue Idx = N->getOperand(1); 9163 EVT IdxVT = Idx.getValueType(); 9164 SDValue V; 9165 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9166 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9167 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9168 if (I == 0) 9169 V = Elt; 9170 else 9171 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9172 } 9173 return V; 9174 } 9175 9176 if (!DCI.isBeforeLegalize()) 9177 return SDValue(); 9178 9179 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9180 // elements. This exposes more load reduction opportunities by replacing 9181 // multiple small extract_vector_elements with a single 32-bit extract. 9182 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9183 if (isa<MemSDNode>(Vec) && 9184 EltSize <= 16 && 9185 EltVT.isByteSized() && 9186 VecSize > 32 && 9187 VecSize % 32 == 0 && 9188 Idx) { 9189 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9190 9191 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9192 unsigned EltIdx = BitIndex / 32; 9193 unsigned LeftoverBitIdx = BitIndex % 32; 9194 SDLoc SL(N); 9195 9196 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9197 DCI.AddToWorklist(Cast.getNode()); 9198 9199 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9200 DAG.getConstant(EltIdx, SL, MVT::i32)); 9201 DCI.AddToWorklist(Elt.getNode()); 9202 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9203 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9204 DCI.AddToWorklist(Srl.getNode()); 9205 9206 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9207 DCI.AddToWorklist(Trunc.getNode()); 9208 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9209 } 9210 9211 return SDValue(); 9212 } 9213 9214 SDValue 9215 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9216 DAGCombinerInfo &DCI) const { 9217 SDValue Vec = N->getOperand(0); 9218 SDValue Idx = N->getOperand(2); 9219 EVT VecVT = Vec.getValueType(); 9220 EVT EltVT = VecVT.getVectorElementType(); 9221 unsigned VecSize = VecVT.getSizeInBits(); 9222 unsigned EltSize = EltVT.getSizeInBits(); 9223 9224 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9225 // => BUILD_VECTOR n x select (e, const-idx) 9226 // This elminates non-constant index and subsequent movrel or scratch access. 9227 // Sub-dword vectors of size 2 dword or less have better implementation. 9228 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9229 // instructions. 9230 if (isa<ConstantSDNode>(Idx) || 9231 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9232 return SDValue(); 9233 9234 SelectionDAG &DAG = DCI.DAG; 9235 SDLoc SL(N); 9236 SDValue Ins = N->getOperand(1); 9237 EVT IdxVT = Idx.getValueType(); 9238 9239 SmallVector<SDValue, 16> Ops; 9240 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9241 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9242 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9243 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9244 Ops.push_back(V); 9245 } 9246 9247 return DAG.getBuildVector(VecVT, SL, Ops); 9248 } 9249 9250 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9251 const SDNode *N0, 9252 const SDNode *N1) const { 9253 EVT VT = N0->getValueType(0); 9254 9255 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9256 // support denormals ever. 9257 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 9258 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() && 9259 getSubtarget()->hasMadF16())) && 9260 isOperationLegal(ISD::FMAD, VT)) 9261 return ISD::FMAD; 9262 9263 const TargetOptions &Options = DAG.getTarget().Options; 9264 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9265 (N0->getFlags().hasAllowContract() && 9266 N1->getFlags().hasAllowContract())) && 9267 isFMAFasterThanFMulAndFAdd(VT)) { 9268 return ISD::FMA; 9269 } 9270 9271 return 0; 9272 } 9273 9274 // For a reassociatable opcode perform: 9275 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9276 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9277 SelectionDAG &DAG) const { 9278 EVT VT = N->getValueType(0); 9279 if (VT != MVT::i32 && VT != MVT::i64) 9280 return SDValue(); 9281 9282 unsigned Opc = N->getOpcode(); 9283 SDValue Op0 = N->getOperand(0); 9284 SDValue Op1 = N->getOperand(1); 9285 9286 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9287 return SDValue(); 9288 9289 if (Op0->isDivergent()) 9290 std::swap(Op0, Op1); 9291 9292 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9293 return SDValue(); 9294 9295 SDValue Op2 = Op1.getOperand(1); 9296 Op1 = Op1.getOperand(0); 9297 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9298 return SDValue(); 9299 9300 if (Op1->isDivergent()) 9301 std::swap(Op1, Op2); 9302 9303 // If either operand is constant this will conflict with 9304 // DAGCombiner::ReassociateOps(). 9305 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9306 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9307 return SDValue(); 9308 9309 SDLoc SL(N); 9310 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9311 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9312 } 9313 9314 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9315 EVT VT, 9316 SDValue N0, SDValue N1, SDValue N2, 9317 bool Signed) { 9318 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9319 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9320 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9321 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9322 } 9323 9324 SDValue SITargetLowering::performAddCombine(SDNode *N, 9325 DAGCombinerInfo &DCI) const { 9326 SelectionDAG &DAG = DCI.DAG; 9327 EVT VT = N->getValueType(0); 9328 SDLoc SL(N); 9329 SDValue LHS = N->getOperand(0); 9330 SDValue RHS = N->getOperand(1); 9331 9332 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9333 && Subtarget->hasMad64_32() && 9334 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9335 VT.getScalarSizeInBits() <= 64) { 9336 if (LHS.getOpcode() != ISD::MUL) 9337 std::swap(LHS, RHS); 9338 9339 SDValue MulLHS = LHS.getOperand(0); 9340 SDValue MulRHS = LHS.getOperand(1); 9341 SDValue AddRHS = RHS; 9342 9343 // TODO: Maybe restrict if SGPR inputs. 9344 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9345 numBitsUnsigned(MulRHS, DAG) <= 32) { 9346 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9347 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9348 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9349 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9350 } 9351 9352 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9353 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9354 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9355 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9356 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9357 } 9358 9359 return SDValue(); 9360 } 9361 9362 if (SDValue V = reassociateScalarOps(N, DAG)) { 9363 return V; 9364 } 9365 9366 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9367 return SDValue(); 9368 9369 // add x, zext (setcc) => addcarry x, 0, setcc 9370 // add x, sext (setcc) => subcarry x, 0, setcc 9371 unsigned Opc = LHS.getOpcode(); 9372 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9373 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9374 std::swap(RHS, LHS); 9375 9376 Opc = RHS.getOpcode(); 9377 switch (Opc) { 9378 default: break; 9379 case ISD::ZERO_EXTEND: 9380 case ISD::SIGN_EXTEND: 9381 case ISD::ANY_EXTEND: { 9382 auto Cond = RHS.getOperand(0); 9383 if (!isBoolSGPR(Cond)) 9384 break; 9385 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9386 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9387 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9388 return DAG.getNode(Opc, SL, VTList, Args); 9389 } 9390 case ISD::ADDCARRY: { 9391 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9392 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9393 if (!C || C->getZExtValue() != 0) break; 9394 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9395 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9396 } 9397 } 9398 return SDValue(); 9399 } 9400 9401 SDValue SITargetLowering::performSubCombine(SDNode *N, 9402 DAGCombinerInfo &DCI) const { 9403 SelectionDAG &DAG = DCI.DAG; 9404 EVT VT = N->getValueType(0); 9405 9406 if (VT != MVT::i32) 9407 return SDValue(); 9408 9409 SDLoc SL(N); 9410 SDValue LHS = N->getOperand(0); 9411 SDValue RHS = N->getOperand(1); 9412 9413 if (LHS.getOpcode() == ISD::SUBCARRY) { 9414 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9415 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9416 if (!C || !C->isNullValue()) 9417 return SDValue(); 9418 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9419 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9420 } 9421 return SDValue(); 9422 } 9423 9424 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9425 DAGCombinerInfo &DCI) const { 9426 9427 if (N->getValueType(0) != MVT::i32) 9428 return SDValue(); 9429 9430 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9431 if (!C || C->getZExtValue() != 0) 9432 return SDValue(); 9433 9434 SelectionDAG &DAG = DCI.DAG; 9435 SDValue LHS = N->getOperand(0); 9436 9437 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9438 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9439 unsigned LHSOpc = LHS.getOpcode(); 9440 unsigned Opc = N->getOpcode(); 9441 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9442 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9443 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9444 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9445 } 9446 return SDValue(); 9447 } 9448 9449 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9450 DAGCombinerInfo &DCI) const { 9451 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9452 return SDValue(); 9453 9454 SelectionDAG &DAG = DCI.DAG; 9455 EVT VT = N->getValueType(0); 9456 9457 SDLoc SL(N); 9458 SDValue LHS = N->getOperand(0); 9459 SDValue RHS = N->getOperand(1); 9460 9461 // These should really be instruction patterns, but writing patterns with 9462 // source modiifiers is a pain. 9463 9464 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9465 if (LHS.getOpcode() == ISD::FADD) { 9466 SDValue A = LHS.getOperand(0); 9467 if (A == LHS.getOperand(1)) { 9468 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9469 if (FusedOp != 0) { 9470 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9471 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9472 } 9473 } 9474 } 9475 9476 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9477 if (RHS.getOpcode() == ISD::FADD) { 9478 SDValue A = RHS.getOperand(0); 9479 if (A == RHS.getOperand(1)) { 9480 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9481 if (FusedOp != 0) { 9482 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9483 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9484 } 9485 } 9486 } 9487 9488 return SDValue(); 9489 } 9490 9491 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9492 DAGCombinerInfo &DCI) const { 9493 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9494 return SDValue(); 9495 9496 SelectionDAG &DAG = DCI.DAG; 9497 SDLoc SL(N); 9498 EVT VT = N->getValueType(0); 9499 assert(!VT.isVector()); 9500 9501 // Try to get the fneg to fold into the source modifier. This undoes generic 9502 // DAG combines and folds them into the mad. 9503 // 9504 // Only do this if we are not trying to support denormals. v_mad_f32 does 9505 // not support denormals ever. 9506 SDValue LHS = N->getOperand(0); 9507 SDValue RHS = N->getOperand(1); 9508 if (LHS.getOpcode() == ISD::FADD) { 9509 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9510 SDValue A = LHS.getOperand(0); 9511 if (A == LHS.getOperand(1)) { 9512 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9513 if (FusedOp != 0){ 9514 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9515 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9516 9517 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9518 } 9519 } 9520 } 9521 9522 if (RHS.getOpcode() == ISD::FADD) { 9523 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9524 9525 SDValue A = RHS.getOperand(0); 9526 if (A == RHS.getOperand(1)) { 9527 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9528 if (FusedOp != 0){ 9529 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9530 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9531 } 9532 } 9533 } 9534 9535 return SDValue(); 9536 } 9537 9538 SDValue SITargetLowering::performFMACombine(SDNode *N, 9539 DAGCombinerInfo &DCI) const { 9540 SelectionDAG &DAG = DCI.DAG; 9541 EVT VT = N->getValueType(0); 9542 SDLoc SL(N); 9543 9544 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9545 return SDValue(); 9546 9547 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9548 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9549 SDValue Op1 = N->getOperand(0); 9550 SDValue Op2 = N->getOperand(1); 9551 SDValue FMA = N->getOperand(2); 9552 9553 if (FMA.getOpcode() != ISD::FMA || 9554 Op1.getOpcode() != ISD::FP_EXTEND || 9555 Op2.getOpcode() != ISD::FP_EXTEND) 9556 return SDValue(); 9557 9558 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9559 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9560 // is sufficient to allow generaing fdot2. 9561 const TargetOptions &Options = DAG.getTarget().Options; 9562 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9563 (N->getFlags().hasAllowContract() && 9564 FMA->getFlags().hasAllowContract())) { 9565 Op1 = Op1.getOperand(0); 9566 Op2 = Op2.getOperand(0); 9567 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9568 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9569 return SDValue(); 9570 9571 SDValue Vec1 = Op1.getOperand(0); 9572 SDValue Idx1 = Op1.getOperand(1); 9573 SDValue Vec2 = Op2.getOperand(0); 9574 9575 SDValue FMAOp1 = FMA.getOperand(0); 9576 SDValue FMAOp2 = FMA.getOperand(1); 9577 SDValue FMAAcc = FMA.getOperand(2); 9578 9579 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9580 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9581 return SDValue(); 9582 9583 FMAOp1 = FMAOp1.getOperand(0); 9584 FMAOp2 = FMAOp2.getOperand(0); 9585 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9586 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9587 return SDValue(); 9588 9589 SDValue Vec3 = FMAOp1.getOperand(0); 9590 SDValue Vec4 = FMAOp2.getOperand(0); 9591 SDValue Idx2 = FMAOp1.getOperand(1); 9592 9593 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9594 // Idx1 and Idx2 cannot be the same. 9595 Idx1 == Idx2) 9596 return SDValue(); 9597 9598 if (Vec1 == Vec2 || Vec3 == Vec4) 9599 return SDValue(); 9600 9601 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9602 return SDValue(); 9603 9604 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9605 (Vec1 == Vec4 && Vec2 == Vec3)) { 9606 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9607 DAG.getTargetConstant(0, SL, MVT::i1)); 9608 } 9609 } 9610 return SDValue(); 9611 } 9612 9613 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9614 DAGCombinerInfo &DCI) const { 9615 SelectionDAG &DAG = DCI.DAG; 9616 SDLoc SL(N); 9617 9618 SDValue LHS = N->getOperand(0); 9619 SDValue RHS = N->getOperand(1); 9620 EVT VT = LHS.getValueType(); 9621 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9622 9623 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9624 if (!CRHS) { 9625 CRHS = dyn_cast<ConstantSDNode>(LHS); 9626 if (CRHS) { 9627 std::swap(LHS, RHS); 9628 CC = getSetCCSwappedOperands(CC); 9629 } 9630 } 9631 9632 if (CRHS) { 9633 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9634 isBoolSGPR(LHS.getOperand(0))) { 9635 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9636 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9637 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9638 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9639 if ((CRHS->isAllOnesValue() && 9640 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9641 (CRHS->isNullValue() && 9642 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9643 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9644 DAG.getConstant(-1, SL, MVT::i1)); 9645 if ((CRHS->isAllOnesValue() && 9646 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9647 (CRHS->isNullValue() && 9648 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9649 return LHS.getOperand(0); 9650 } 9651 9652 uint64_t CRHSVal = CRHS->getZExtValue(); 9653 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9654 LHS.getOpcode() == ISD::SELECT && 9655 isa<ConstantSDNode>(LHS.getOperand(1)) && 9656 isa<ConstantSDNode>(LHS.getOperand(2)) && 9657 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9658 isBoolSGPR(LHS.getOperand(0))) { 9659 // Given CT != FT: 9660 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9661 // setcc (select cc, CT, CF), CF, ne => cc 9662 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9663 // setcc (select cc, CT, CF), CT, eq => cc 9664 uint64_t CT = LHS.getConstantOperandVal(1); 9665 uint64_t CF = LHS.getConstantOperandVal(2); 9666 9667 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9668 (CT == CRHSVal && CC == ISD::SETNE)) 9669 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9670 DAG.getConstant(-1, SL, MVT::i1)); 9671 if ((CF == CRHSVal && CC == ISD::SETNE) || 9672 (CT == CRHSVal && CC == ISD::SETEQ)) 9673 return LHS.getOperand(0); 9674 } 9675 } 9676 9677 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9678 VT != MVT::f16)) 9679 return SDValue(); 9680 9681 // Match isinf/isfinite pattern 9682 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9683 // (fcmp one (fabs x), inf) -> (fp_class x, 9684 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9685 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9686 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9687 if (!CRHS) 9688 return SDValue(); 9689 9690 const APFloat &APF = CRHS->getValueAPF(); 9691 if (APF.isInfinity() && !APF.isNegative()) { 9692 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9693 SIInstrFlags::N_INFINITY; 9694 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9695 SIInstrFlags::P_ZERO | 9696 SIInstrFlags::N_NORMAL | 9697 SIInstrFlags::P_NORMAL | 9698 SIInstrFlags::N_SUBNORMAL | 9699 SIInstrFlags::P_SUBNORMAL; 9700 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9701 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9702 DAG.getConstant(Mask, SL, MVT::i32)); 9703 } 9704 } 9705 9706 return SDValue(); 9707 } 9708 9709 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9710 DAGCombinerInfo &DCI) const { 9711 SelectionDAG &DAG = DCI.DAG; 9712 SDLoc SL(N); 9713 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9714 9715 SDValue Src = N->getOperand(0); 9716 SDValue Srl = N->getOperand(0); 9717 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9718 Srl = Srl.getOperand(0); 9719 9720 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9721 if (Srl.getOpcode() == ISD::SRL) { 9722 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9723 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9724 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9725 9726 if (const ConstantSDNode *C = 9727 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9728 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9729 EVT(MVT::i32)); 9730 9731 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9732 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9733 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9734 MVT::f32, Srl); 9735 } 9736 } 9737 } 9738 9739 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9740 9741 KnownBits Known; 9742 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9743 !DCI.isBeforeLegalizeOps()); 9744 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9745 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9746 DCI.CommitTargetLoweringOpt(TLO); 9747 } 9748 9749 return SDValue(); 9750 } 9751 9752 SDValue SITargetLowering::performClampCombine(SDNode *N, 9753 DAGCombinerInfo &DCI) const { 9754 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9755 if (!CSrc) 9756 return SDValue(); 9757 9758 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9759 const APFloat &F = CSrc->getValueAPF(); 9760 APFloat Zero = APFloat::getZero(F.getSemantics()); 9761 APFloat::cmpResult Cmp0 = F.compare(Zero); 9762 if (Cmp0 == APFloat::cmpLessThan || 9763 (Cmp0 == APFloat::cmpUnordered && 9764 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9765 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9766 } 9767 9768 APFloat One(F.getSemantics(), "1.0"); 9769 APFloat::cmpResult Cmp1 = F.compare(One); 9770 if (Cmp1 == APFloat::cmpGreaterThan) 9771 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9772 9773 return SDValue(CSrc, 0); 9774 } 9775 9776 9777 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9778 DAGCombinerInfo &DCI) const { 9779 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9780 return SDValue(); 9781 switch (N->getOpcode()) { 9782 default: 9783 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9784 case ISD::ADD: 9785 return performAddCombine(N, DCI); 9786 case ISD::SUB: 9787 return performSubCombine(N, DCI); 9788 case ISD::ADDCARRY: 9789 case ISD::SUBCARRY: 9790 return performAddCarrySubCarryCombine(N, DCI); 9791 case ISD::FADD: 9792 return performFAddCombine(N, DCI); 9793 case ISD::FSUB: 9794 return performFSubCombine(N, DCI); 9795 case ISD::SETCC: 9796 return performSetCCCombine(N, DCI); 9797 case ISD::FMAXNUM: 9798 case ISD::FMINNUM: 9799 case ISD::FMAXNUM_IEEE: 9800 case ISD::FMINNUM_IEEE: 9801 case ISD::SMAX: 9802 case ISD::SMIN: 9803 case ISD::UMAX: 9804 case ISD::UMIN: 9805 case AMDGPUISD::FMIN_LEGACY: 9806 case AMDGPUISD::FMAX_LEGACY: 9807 return performMinMaxCombine(N, DCI); 9808 case ISD::FMA: 9809 return performFMACombine(N, DCI); 9810 case ISD::LOAD: { 9811 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9812 return Widended; 9813 LLVM_FALLTHROUGH; 9814 } 9815 case ISD::STORE: 9816 case ISD::ATOMIC_LOAD: 9817 case ISD::ATOMIC_STORE: 9818 case ISD::ATOMIC_CMP_SWAP: 9819 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9820 case ISD::ATOMIC_SWAP: 9821 case ISD::ATOMIC_LOAD_ADD: 9822 case ISD::ATOMIC_LOAD_SUB: 9823 case ISD::ATOMIC_LOAD_AND: 9824 case ISD::ATOMIC_LOAD_OR: 9825 case ISD::ATOMIC_LOAD_XOR: 9826 case ISD::ATOMIC_LOAD_NAND: 9827 case ISD::ATOMIC_LOAD_MIN: 9828 case ISD::ATOMIC_LOAD_MAX: 9829 case ISD::ATOMIC_LOAD_UMIN: 9830 case ISD::ATOMIC_LOAD_UMAX: 9831 case ISD::ATOMIC_LOAD_FADD: 9832 case AMDGPUISD::ATOMIC_INC: 9833 case AMDGPUISD::ATOMIC_DEC: 9834 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9835 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9836 if (DCI.isBeforeLegalize()) 9837 break; 9838 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9839 case ISD::AND: 9840 return performAndCombine(N, DCI); 9841 case ISD::OR: 9842 return performOrCombine(N, DCI); 9843 case ISD::XOR: 9844 return performXorCombine(N, DCI); 9845 case ISD::ZERO_EXTEND: 9846 return performZeroExtendCombine(N, DCI); 9847 case ISD::SIGN_EXTEND_INREG: 9848 return performSignExtendInRegCombine(N , DCI); 9849 case AMDGPUISD::FP_CLASS: 9850 return performClassCombine(N, DCI); 9851 case ISD::FCANONICALIZE: 9852 return performFCanonicalizeCombine(N, DCI); 9853 case AMDGPUISD::RCP: 9854 return performRcpCombine(N, DCI); 9855 case AMDGPUISD::FRACT: 9856 case AMDGPUISD::RSQ: 9857 case AMDGPUISD::RCP_LEGACY: 9858 case AMDGPUISD::RSQ_LEGACY: 9859 case AMDGPUISD::RCP_IFLAG: 9860 case AMDGPUISD::RSQ_CLAMP: 9861 case AMDGPUISD::LDEXP: { 9862 SDValue Src = N->getOperand(0); 9863 if (Src.isUndef()) 9864 return Src; 9865 break; 9866 } 9867 case ISD::SINT_TO_FP: 9868 case ISD::UINT_TO_FP: 9869 return performUCharToFloatCombine(N, DCI); 9870 case AMDGPUISD::CVT_F32_UBYTE0: 9871 case AMDGPUISD::CVT_F32_UBYTE1: 9872 case AMDGPUISD::CVT_F32_UBYTE2: 9873 case AMDGPUISD::CVT_F32_UBYTE3: 9874 return performCvtF32UByteNCombine(N, DCI); 9875 case AMDGPUISD::FMED3: 9876 return performFMed3Combine(N, DCI); 9877 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9878 return performCvtPkRTZCombine(N, DCI); 9879 case AMDGPUISD::CLAMP: 9880 return performClampCombine(N, DCI); 9881 case ISD::SCALAR_TO_VECTOR: { 9882 SelectionDAG &DAG = DCI.DAG; 9883 EVT VT = N->getValueType(0); 9884 9885 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9886 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9887 SDLoc SL(N); 9888 SDValue Src = N->getOperand(0); 9889 EVT EltVT = Src.getValueType(); 9890 if (EltVT == MVT::f16) 9891 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 9892 9893 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 9894 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 9895 } 9896 9897 break; 9898 } 9899 case ISD::EXTRACT_VECTOR_ELT: 9900 return performExtractVectorEltCombine(N, DCI); 9901 case ISD::INSERT_VECTOR_ELT: 9902 return performInsertVectorEltCombine(N, DCI); 9903 } 9904 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9905 } 9906 9907 /// Helper function for adjustWritemask 9908 static unsigned SubIdx2Lane(unsigned Idx) { 9909 switch (Idx) { 9910 default: return 0; 9911 case AMDGPU::sub0: return 0; 9912 case AMDGPU::sub1: return 1; 9913 case AMDGPU::sub2: return 2; 9914 case AMDGPU::sub3: return 3; 9915 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 9916 } 9917 } 9918 9919 /// Adjust the writemask of MIMG instructions 9920 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 9921 SelectionDAG &DAG) const { 9922 unsigned Opcode = Node->getMachineOpcode(); 9923 9924 // Subtract 1 because the vdata output is not a MachineSDNode operand. 9925 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 9926 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 9927 return Node; // not implemented for D16 9928 9929 SDNode *Users[5] = { nullptr }; 9930 unsigned Lane = 0; 9931 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 9932 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 9933 unsigned NewDmask = 0; 9934 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 9935 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 9936 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 9937 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 9938 unsigned TFCLane = 0; 9939 bool HasChain = Node->getNumValues() > 1; 9940 9941 if (OldDmask == 0) { 9942 // These are folded out, but on the chance it happens don't assert. 9943 return Node; 9944 } 9945 9946 unsigned OldBitsSet = countPopulation(OldDmask); 9947 // Work out which is the TFE/LWE lane if that is enabled. 9948 if (UsesTFC) { 9949 TFCLane = OldBitsSet; 9950 } 9951 9952 // Try to figure out the used register components 9953 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 9954 I != E; ++I) { 9955 9956 // Don't look at users of the chain. 9957 if (I.getUse().getResNo() != 0) 9958 continue; 9959 9960 // Abort if we can't understand the usage 9961 if (!I->isMachineOpcode() || 9962 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 9963 return Node; 9964 9965 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 9966 // Note that subregs are packed, i.e. Lane==0 is the first bit set 9967 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 9968 // set, etc. 9969 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 9970 9971 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 9972 if (UsesTFC && Lane == TFCLane) { 9973 Users[Lane] = *I; 9974 } else { 9975 // Set which texture component corresponds to the lane. 9976 unsigned Comp; 9977 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 9978 Comp = countTrailingZeros(Dmask); 9979 Dmask &= ~(1 << Comp); 9980 } 9981 9982 // Abort if we have more than one user per component. 9983 if (Users[Lane]) 9984 return Node; 9985 9986 Users[Lane] = *I; 9987 NewDmask |= 1 << Comp; 9988 } 9989 } 9990 9991 // Don't allow 0 dmask, as hardware assumes one channel enabled. 9992 bool NoChannels = !NewDmask; 9993 if (NoChannels) { 9994 if (!UsesTFC) { 9995 // No uses of the result and not using TFC. Then do nothing. 9996 return Node; 9997 } 9998 // If the original dmask has one channel - then nothing to do 9999 if (OldBitsSet == 1) 10000 return Node; 10001 // Use an arbitrary dmask - required for the instruction to work 10002 NewDmask = 1; 10003 } 10004 // Abort if there's no change 10005 if (NewDmask == OldDmask) 10006 return Node; 10007 10008 unsigned BitsSet = countPopulation(NewDmask); 10009 10010 // Check for TFE or LWE - increase the number of channels by one to account 10011 // for the extra return value 10012 // This will need adjustment for D16 if this is also included in 10013 // adjustWriteMask (this function) but at present D16 are excluded. 10014 unsigned NewChannels = BitsSet + UsesTFC; 10015 10016 int NewOpcode = 10017 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10018 assert(NewOpcode != -1 && 10019 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10020 "failed to find equivalent MIMG op"); 10021 10022 // Adjust the writemask in the node 10023 SmallVector<SDValue, 12> Ops; 10024 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10025 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10026 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10027 10028 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10029 10030 MVT ResultVT = NewChannels == 1 ? 10031 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10032 NewChannels == 5 ? 8 : NewChannels); 10033 SDVTList NewVTList = HasChain ? 10034 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10035 10036 10037 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10038 NewVTList, Ops); 10039 10040 if (HasChain) { 10041 // Update chain. 10042 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10043 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10044 } 10045 10046 if (NewChannels == 1) { 10047 assert(Node->hasNUsesOfValue(1, 0)); 10048 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10049 SDLoc(Node), Users[Lane]->getValueType(0), 10050 SDValue(NewNode, 0)); 10051 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10052 return nullptr; 10053 } 10054 10055 // Update the users of the node with the new indices 10056 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10057 SDNode *User = Users[i]; 10058 if (!User) { 10059 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10060 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10061 if (i || !NoChannels) 10062 continue; 10063 } else { 10064 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10065 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10066 } 10067 10068 switch (Idx) { 10069 default: break; 10070 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10071 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10072 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10073 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10074 } 10075 } 10076 10077 DAG.RemoveDeadNode(Node); 10078 return nullptr; 10079 } 10080 10081 static bool isFrameIndexOp(SDValue Op) { 10082 if (Op.getOpcode() == ISD::AssertZext) 10083 Op = Op.getOperand(0); 10084 10085 return isa<FrameIndexSDNode>(Op); 10086 } 10087 10088 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10089 /// with frame index operands. 10090 /// LLVM assumes that inputs are to these instructions are registers. 10091 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10092 SelectionDAG &DAG) const { 10093 if (Node->getOpcode() == ISD::CopyToReg) { 10094 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10095 SDValue SrcVal = Node->getOperand(2); 10096 10097 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10098 // to try understanding copies to physical registers. 10099 if (SrcVal.getValueType() == MVT::i1 && 10100 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 10101 SDLoc SL(Node); 10102 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10103 SDValue VReg = DAG.getRegister( 10104 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10105 10106 SDNode *Glued = Node->getGluedNode(); 10107 SDValue ToVReg 10108 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10109 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10110 SDValue ToResultReg 10111 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10112 VReg, ToVReg.getValue(1)); 10113 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10114 DAG.RemoveDeadNode(Node); 10115 return ToResultReg.getNode(); 10116 } 10117 } 10118 10119 SmallVector<SDValue, 8> Ops; 10120 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10121 if (!isFrameIndexOp(Node->getOperand(i))) { 10122 Ops.push_back(Node->getOperand(i)); 10123 continue; 10124 } 10125 10126 SDLoc DL(Node); 10127 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10128 Node->getOperand(i).getValueType(), 10129 Node->getOperand(i)), 0)); 10130 } 10131 10132 return DAG.UpdateNodeOperands(Node, Ops); 10133 } 10134 10135 /// Fold the instructions after selecting them. 10136 /// Returns null if users were already updated. 10137 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10138 SelectionDAG &DAG) const { 10139 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10140 unsigned Opcode = Node->getMachineOpcode(); 10141 10142 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10143 !TII->isGather4(Opcode)) { 10144 return adjustWritemask(Node, DAG); 10145 } 10146 10147 if (Opcode == AMDGPU::INSERT_SUBREG || 10148 Opcode == AMDGPU::REG_SEQUENCE) { 10149 legalizeTargetIndependentNode(Node, DAG); 10150 return Node; 10151 } 10152 10153 switch (Opcode) { 10154 case AMDGPU::V_DIV_SCALE_F32: 10155 case AMDGPU::V_DIV_SCALE_F64: { 10156 // Satisfy the operand register constraint when one of the inputs is 10157 // undefined. Ordinarily each undef value will have its own implicit_def of 10158 // a vreg, so force these to use a single register. 10159 SDValue Src0 = Node->getOperand(0); 10160 SDValue Src1 = Node->getOperand(1); 10161 SDValue Src2 = Node->getOperand(2); 10162 10163 if ((Src0.isMachineOpcode() && 10164 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10165 (Src0 == Src1 || Src0 == Src2)) 10166 break; 10167 10168 MVT VT = Src0.getValueType().getSimpleVT(); 10169 const TargetRegisterClass *RC = 10170 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10171 10172 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10173 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10174 10175 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10176 UndefReg, Src0, SDValue()); 10177 10178 // src0 must be the same register as src1 or src2, even if the value is 10179 // undefined, so make sure we don't violate this constraint. 10180 if (Src0.isMachineOpcode() && 10181 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10182 if (Src1.isMachineOpcode() && 10183 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10184 Src0 = Src1; 10185 else if (Src2.isMachineOpcode() && 10186 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10187 Src0 = Src2; 10188 else { 10189 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10190 Src0 = UndefReg; 10191 Src1 = UndefReg; 10192 } 10193 } else 10194 break; 10195 10196 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10197 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10198 Ops.push_back(Node->getOperand(I)); 10199 10200 Ops.push_back(ImpDef.getValue(1)); 10201 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10202 } 10203 case AMDGPU::V_PERMLANE16_B32: 10204 case AMDGPU::V_PERMLANEX16_B32: { 10205 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10206 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10207 if (!FI->getZExtValue() && !BC->getZExtValue()) 10208 break; 10209 SDValue VDstIn = Node->getOperand(6); 10210 if (VDstIn.isMachineOpcode() 10211 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10212 break; 10213 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10214 SDLoc(Node), MVT::i32); 10215 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10216 SDValue(BC, 0), Node->getOperand(3), 10217 Node->getOperand(4), Node->getOperand(5), 10218 SDValue(ImpDef, 0), Node->getOperand(7) }; 10219 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10220 } 10221 default: 10222 break; 10223 } 10224 10225 return Node; 10226 } 10227 10228 /// Assign the register class depending on the number of 10229 /// bits set in the writemask 10230 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10231 SDNode *Node) const { 10232 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10233 10234 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10235 10236 if (TII->isVOP3(MI.getOpcode())) { 10237 // Make sure constant bus requirements are respected. 10238 TII->legalizeOperandsVOP3(MRI, MI); 10239 10240 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10241 // This saves a chain-copy of registers and better ballance register 10242 // use between vgpr and agpr as agpr tuples tend to be big. 10243 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10244 unsigned Opc = MI.getOpcode(); 10245 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10246 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10247 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10248 if (I == -1) 10249 break; 10250 MachineOperand &Op = MI.getOperand(I); 10251 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10252 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10253 !TargetRegisterInfo::isVirtualRegister(Op.getReg()) || 10254 !TRI->isAGPR(MRI, Op.getReg())) 10255 continue; 10256 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10257 if (!Src || !Src->isCopy() || 10258 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10259 continue; 10260 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10261 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10262 // All uses of agpr64 and agpr32 can also accept vgpr except for 10263 // v_accvgpr_read, but we do not produce agpr reads during selection, 10264 // so no use checks are needed. 10265 MRI.setRegClass(Op.getReg(), NewRC); 10266 } 10267 } 10268 10269 return; 10270 } 10271 10272 // Replace unused atomics with the no return version. 10273 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10274 if (NoRetAtomicOp != -1) { 10275 if (!Node->hasAnyUseOfValue(0)) { 10276 MI.setDesc(TII->get(NoRetAtomicOp)); 10277 MI.RemoveOperand(0); 10278 return; 10279 } 10280 10281 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10282 // instruction, because the return type of these instructions is a vec2 of 10283 // the memory type, so it can be tied to the input operand. 10284 // This means these instructions always have a use, so we need to add a 10285 // special case to check if the atomic has only one extract_subreg use, 10286 // which itself has no uses. 10287 if ((Node->hasNUsesOfValue(1, 0) && 10288 Node->use_begin()->isMachineOpcode() && 10289 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10290 !Node->use_begin()->hasAnyUseOfValue(0))) { 10291 unsigned Def = MI.getOperand(0).getReg(); 10292 10293 // Change this into a noret atomic. 10294 MI.setDesc(TII->get(NoRetAtomicOp)); 10295 MI.RemoveOperand(0); 10296 10297 // If we only remove the def operand from the atomic instruction, the 10298 // extract_subreg will be left with a use of a vreg without a def. 10299 // So we need to insert an implicit_def to avoid machine verifier 10300 // errors. 10301 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10302 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10303 } 10304 return; 10305 } 10306 } 10307 10308 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10309 uint64_t Val) { 10310 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10311 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10312 } 10313 10314 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10315 const SDLoc &DL, 10316 SDValue Ptr) const { 10317 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10318 10319 // Build the half of the subregister with the constants before building the 10320 // full 128-bit register. If we are building multiple resource descriptors, 10321 // this will allow CSEing of the 2-component register. 10322 const SDValue Ops0[] = { 10323 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10324 buildSMovImm32(DAG, DL, 0), 10325 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10326 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10327 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10328 }; 10329 10330 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10331 MVT::v2i32, Ops0), 0); 10332 10333 // Combine the constants and the pointer. 10334 const SDValue Ops1[] = { 10335 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10336 Ptr, 10337 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10338 SubRegHi, 10339 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10340 }; 10341 10342 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10343 } 10344 10345 /// Return a resource descriptor with the 'Add TID' bit enabled 10346 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10347 /// of the resource descriptor) to create an offset, which is added to 10348 /// the resource pointer. 10349 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10350 SDValue Ptr, uint32_t RsrcDword1, 10351 uint64_t RsrcDword2And3) const { 10352 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10353 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10354 if (RsrcDword1) { 10355 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10356 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10357 0); 10358 } 10359 10360 SDValue DataLo = buildSMovImm32(DAG, DL, 10361 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10362 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10363 10364 const SDValue Ops[] = { 10365 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10366 PtrLo, 10367 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10368 PtrHi, 10369 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10370 DataLo, 10371 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10372 DataHi, 10373 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10374 }; 10375 10376 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10377 } 10378 10379 //===----------------------------------------------------------------------===// 10380 // SI Inline Assembly Support 10381 //===----------------------------------------------------------------------===// 10382 10383 std::pair<unsigned, const TargetRegisterClass *> 10384 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10385 StringRef Constraint, 10386 MVT VT) const { 10387 const TargetRegisterClass *RC = nullptr; 10388 if (Constraint.size() == 1) { 10389 switch (Constraint[0]) { 10390 default: 10391 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10392 case 's': 10393 case 'r': 10394 switch (VT.getSizeInBits()) { 10395 default: 10396 return std::make_pair(0U, nullptr); 10397 case 32: 10398 case 16: 10399 RC = &AMDGPU::SReg_32_XM0RegClass; 10400 break; 10401 case 64: 10402 RC = &AMDGPU::SGPR_64RegClass; 10403 break; 10404 case 96: 10405 RC = &AMDGPU::SReg_96RegClass; 10406 break; 10407 case 128: 10408 RC = &AMDGPU::SReg_128RegClass; 10409 break; 10410 case 160: 10411 RC = &AMDGPU::SReg_160RegClass; 10412 break; 10413 case 256: 10414 RC = &AMDGPU::SReg_256RegClass; 10415 break; 10416 case 512: 10417 RC = &AMDGPU::SReg_512RegClass; 10418 break; 10419 } 10420 break; 10421 case 'v': 10422 switch (VT.getSizeInBits()) { 10423 default: 10424 return std::make_pair(0U, nullptr); 10425 case 32: 10426 case 16: 10427 RC = &AMDGPU::VGPR_32RegClass; 10428 break; 10429 case 64: 10430 RC = &AMDGPU::VReg_64RegClass; 10431 break; 10432 case 96: 10433 RC = &AMDGPU::VReg_96RegClass; 10434 break; 10435 case 128: 10436 RC = &AMDGPU::VReg_128RegClass; 10437 break; 10438 case 160: 10439 RC = &AMDGPU::VReg_160RegClass; 10440 break; 10441 case 256: 10442 RC = &AMDGPU::VReg_256RegClass; 10443 break; 10444 case 512: 10445 RC = &AMDGPU::VReg_512RegClass; 10446 break; 10447 } 10448 break; 10449 case 'a': 10450 switch (VT.getSizeInBits()) { 10451 default: 10452 return std::make_pair(0U, nullptr); 10453 case 32: 10454 case 16: 10455 RC = &AMDGPU::AGPR_32RegClass; 10456 break; 10457 case 64: 10458 RC = &AMDGPU::AReg_64RegClass; 10459 break; 10460 case 128: 10461 RC = &AMDGPU::AReg_128RegClass; 10462 break; 10463 case 512: 10464 RC = &AMDGPU::AReg_512RegClass; 10465 break; 10466 case 1024: 10467 RC = &AMDGPU::AReg_1024RegClass; 10468 // v32 types are not legal but we support them here. 10469 return std::make_pair(0U, RC); 10470 } 10471 break; 10472 } 10473 // We actually support i128, i16 and f16 as inline parameters 10474 // even if they are not reported as legal 10475 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10476 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10477 return std::make_pair(0U, RC); 10478 } 10479 10480 if (Constraint.size() > 1) { 10481 if (Constraint[1] == 'v') { 10482 RC = &AMDGPU::VGPR_32RegClass; 10483 } else if (Constraint[1] == 's') { 10484 RC = &AMDGPU::SGPR_32RegClass; 10485 } else if (Constraint[1] == 'a') { 10486 RC = &AMDGPU::AGPR_32RegClass; 10487 } 10488 10489 if (RC) { 10490 uint32_t Idx; 10491 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10492 if (!Failed && Idx < RC->getNumRegs()) 10493 return std::make_pair(RC->getRegister(Idx), RC); 10494 } 10495 } 10496 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10497 } 10498 10499 SITargetLowering::ConstraintType 10500 SITargetLowering::getConstraintType(StringRef Constraint) const { 10501 if (Constraint.size() == 1) { 10502 switch (Constraint[0]) { 10503 default: break; 10504 case 's': 10505 case 'v': 10506 case 'a': 10507 return C_RegisterClass; 10508 } 10509 } 10510 return TargetLowering::getConstraintType(Constraint); 10511 } 10512 10513 // Figure out which registers should be reserved for stack access. Only after 10514 // the function is legalized do we know all of the non-spill stack objects or if 10515 // calls are present. 10516 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10517 MachineRegisterInfo &MRI = MF.getRegInfo(); 10518 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10519 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10520 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10521 10522 if (Info->isEntryFunction()) { 10523 // Callable functions have fixed registers used for stack access. 10524 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10525 } 10526 10527 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10528 Info->getStackPtrOffsetReg())); 10529 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10530 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10531 10532 // We need to worry about replacing the default register with itself in case 10533 // of MIR testcases missing the MFI. 10534 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10535 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10536 10537 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10538 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10539 10540 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10541 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10542 Info->getScratchWaveOffsetReg()); 10543 } 10544 10545 Info->limitOccupancy(MF); 10546 10547 if (ST.isWave32() && !MF.empty()) { 10548 // Add VCC_HI def because many instructions marked as imp-use VCC where 10549 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10550 // having a use of undef. 10551 10552 const SIInstrInfo *TII = ST.getInstrInfo(); 10553 DebugLoc DL; 10554 10555 MachineBasicBlock &MBB = MF.front(); 10556 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10557 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10558 10559 for (auto &MBB : MF) { 10560 for (auto &MI : MBB) { 10561 TII->fixImplicitOperands(MI); 10562 } 10563 } 10564 } 10565 10566 TargetLoweringBase::finalizeLowering(MF); 10567 } 10568 10569 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10570 KnownBits &Known, 10571 const APInt &DemandedElts, 10572 const SelectionDAG &DAG, 10573 unsigned Depth) const { 10574 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10575 DAG, Depth); 10576 10577 // Set the high bits to zero based on the maximum allowed scratch size per 10578 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10579 // calculation won't overflow, so assume the sign bit is never set. 10580 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10581 } 10582 10583 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10584 const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10585 const unsigned CacheLineAlign = 6; // log2(64) 10586 10587 // Pre-GFX10 target did not benefit from loop alignment 10588 if (!ML || DisableLoopAlignment || 10589 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10590 getSubtarget()->hasInstFwdPrefetchBug()) 10591 return PrefAlign; 10592 10593 // On GFX10 I$ is 4 x 64 bytes cache lines. 10594 // By default prefetcher keeps one cache line behind and reads two ahead. 10595 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10596 // behind and one ahead. 10597 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10598 // If loop fits 64 bytes it always spans no more than two cache lines and 10599 // does not need an alignment. 10600 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10601 // Else if loop is less or equal 192 bytes we need two lines behind. 10602 10603 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10604 const MachineBasicBlock *Header = ML->getHeader(); 10605 if (Header->getAlignment() != PrefAlign) 10606 return Header->getAlignment(); // Already processed. 10607 10608 unsigned LoopSize = 0; 10609 for (const MachineBasicBlock *MBB : ML->blocks()) { 10610 // If inner loop block is aligned assume in average half of the alignment 10611 // size to be added as nops. 10612 if (MBB != Header) 10613 LoopSize += (1 << MBB->getAlignment()) / 2; 10614 10615 for (const MachineInstr &MI : *MBB) { 10616 LoopSize += TII->getInstSizeInBytes(MI); 10617 if (LoopSize > 192) 10618 return PrefAlign; 10619 } 10620 } 10621 10622 if (LoopSize <= 64) 10623 return PrefAlign; 10624 10625 if (LoopSize <= 128) 10626 return CacheLineAlign; 10627 10628 // If any of parent loops is surrounded by prefetch instructions do not 10629 // insert new for inner loop, which would reset parent's settings. 10630 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10631 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10632 auto I = Exit->getFirstNonDebugInstr(); 10633 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10634 return CacheLineAlign; 10635 } 10636 } 10637 10638 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10639 MachineBasicBlock *Exit = ML->getExitBlock(); 10640 10641 if (Pre && Exit) { 10642 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10643 TII->get(AMDGPU::S_INST_PREFETCH)) 10644 .addImm(1); // prefetch 2 lines behind PC 10645 10646 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10647 TII->get(AMDGPU::S_INST_PREFETCH)) 10648 .addImm(2); // prefetch 1 line behind PC 10649 } 10650 10651 return CacheLineAlign; 10652 } 10653 10654 LLVM_ATTRIBUTE_UNUSED 10655 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10656 assert(N->getOpcode() == ISD::CopyFromReg); 10657 do { 10658 // Follow the chain until we find an INLINEASM node. 10659 N = N->getOperand(0).getNode(); 10660 if (N->getOpcode() == ISD::INLINEASM || 10661 N->getOpcode() == ISD::INLINEASM_BR) 10662 return true; 10663 } while (N->getOpcode() == ISD::CopyFromReg); 10664 return false; 10665 } 10666 10667 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10668 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10669 { 10670 switch (N->getOpcode()) { 10671 case ISD::CopyFromReg: 10672 { 10673 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10674 const MachineFunction * MF = FLI->MF; 10675 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10676 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10677 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10678 unsigned Reg = R->getReg(); 10679 if (TRI.isPhysicalRegister(Reg)) 10680 return !TRI.isSGPRReg(MRI, Reg); 10681 10682 if (MRI.isLiveIn(Reg)) { 10683 // workitem.id.x workitem.id.y workitem.id.z 10684 // Any VGPR formal argument is also considered divergent 10685 if (!TRI.isSGPRReg(MRI, Reg)) 10686 return true; 10687 // Formal arguments of non-entry functions 10688 // are conservatively considered divergent 10689 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10690 return true; 10691 return false; 10692 } 10693 const Value *V = FLI->getValueFromVirtualReg(Reg); 10694 if (V) 10695 return KDA->isDivergent(V); 10696 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10697 return !TRI.isSGPRReg(MRI, Reg); 10698 } 10699 break; 10700 case ISD::LOAD: { 10701 const LoadSDNode *L = cast<LoadSDNode>(N); 10702 unsigned AS = L->getAddressSpace(); 10703 // A flat load may access private memory. 10704 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10705 } break; 10706 case ISD::CALLSEQ_END: 10707 return true; 10708 break; 10709 case ISD::INTRINSIC_WO_CHAIN: 10710 { 10711 10712 } 10713 return AMDGPU::isIntrinsicSourceOfDivergence( 10714 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10715 case ISD::INTRINSIC_W_CHAIN: 10716 return AMDGPU::isIntrinsicSourceOfDivergence( 10717 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10718 // In some cases intrinsics that are a source of divergence have been 10719 // lowered to AMDGPUISD so we also need to check those too. 10720 case AMDGPUISD::INTERP_MOV: 10721 case AMDGPUISD::INTERP_P1: 10722 case AMDGPUISD::INTERP_P2: 10723 return true; 10724 } 10725 return false; 10726 } 10727 10728 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 10729 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10730 case MVT::f32: 10731 return Subtarget->hasFP32Denormals(); 10732 case MVT::f64: 10733 return Subtarget->hasFP64Denormals(); 10734 case MVT::f16: 10735 return Subtarget->hasFP16Denormals(); 10736 default: 10737 return false; 10738 } 10739 } 10740 10741 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10742 const SelectionDAG &DAG, 10743 bool SNaN, 10744 unsigned Depth) const { 10745 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10746 const MachineFunction &MF = DAG.getMachineFunction(); 10747 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10748 10749 if (Info->getMode().DX10Clamp) 10750 return true; // Clamped to 0. 10751 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10752 } 10753 10754 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10755 SNaN, Depth); 10756 } 10757 10758 TargetLowering::AtomicExpansionKind 10759 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10760 switch (RMW->getOperation()) { 10761 case AtomicRMWInst::FAdd: { 10762 Type *Ty = RMW->getType(); 10763 10764 // We don't have a way to support 16-bit atomics now, so just leave them 10765 // as-is. 10766 if (Ty->isHalfTy()) 10767 return AtomicExpansionKind::None; 10768 10769 if (!Ty->isFloatTy()) 10770 return AtomicExpansionKind::CmpXChg; 10771 10772 // TODO: Do have these for flat. Older targets also had them for buffers. 10773 unsigned AS = RMW->getPointerAddressSpace(); 10774 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10775 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10776 } 10777 default: 10778 break; 10779 } 10780 10781 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10782 } 10783