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_fmad_ftz: 5983 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5984 Op.getOperand(2), Op.getOperand(3)); 5985 5986 case Intrinsic::amdgcn_if_break: 5987 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5988 Op->getOperand(1), Op->getOperand(2)), 0); 5989 5990 case Intrinsic::amdgcn_groupstaticsize: { 5991 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 5992 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 5993 return Op; 5994 5995 const Module *M = MF.getFunction().getParent(); 5996 const GlobalValue *GV = 5997 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 5998 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 5999 SIInstrInfo::MO_ABS32_LO); 6000 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6001 } 6002 default: 6003 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6004 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6005 return lowerImage(Op, ImageDimIntr, DAG); 6006 6007 return Op; 6008 } 6009 } 6010 6011 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6012 SelectionDAG &DAG) const { 6013 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6014 SDLoc DL(Op); 6015 6016 switch (IntrID) { 6017 case Intrinsic::amdgcn_ds_ordered_add: 6018 case Intrinsic::amdgcn_ds_ordered_swap: { 6019 MemSDNode *M = cast<MemSDNode>(Op); 6020 SDValue Chain = M->getOperand(0); 6021 SDValue M0 = M->getOperand(2); 6022 SDValue Value = M->getOperand(3); 6023 unsigned IndexOperand = M->getConstantOperandVal(7); 6024 unsigned WaveRelease = M->getConstantOperandVal(8); 6025 unsigned WaveDone = M->getConstantOperandVal(9); 6026 unsigned ShaderType; 6027 unsigned Instruction; 6028 6029 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6030 IndexOperand &= ~0x3f; 6031 unsigned CountDw = 0; 6032 6033 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6034 CountDw = (IndexOperand >> 24) & 0xf; 6035 IndexOperand &= ~(0xf << 24); 6036 6037 if (CountDw < 1 || CountDw > 4) { 6038 report_fatal_error( 6039 "ds_ordered_count: dword count must be between 1 and 4"); 6040 } 6041 } 6042 6043 if (IndexOperand) 6044 report_fatal_error("ds_ordered_count: bad index operand"); 6045 6046 switch (IntrID) { 6047 case Intrinsic::amdgcn_ds_ordered_add: 6048 Instruction = 0; 6049 break; 6050 case Intrinsic::amdgcn_ds_ordered_swap: 6051 Instruction = 1; 6052 break; 6053 } 6054 6055 if (WaveDone && !WaveRelease) 6056 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6057 6058 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6059 case CallingConv::AMDGPU_CS: 6060 case CallingConv::AMDGPU_KERNEL: 6061 ShaderType = 0; 6062 break; 6063 case CallingConv::AMDGPU_PS: 6064 ShaderType = 1; 6065 break; 6066 case CallingConv::AMDGPU_VS: 6067 ShaderType = 2; 6068 break; 6069 case CallingConv::AMDGPU_GS: 6070 ShaderType = 3; 6071 break; 6072 default: 6073 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6074 } 6075 6076 unsigned Offset0 = OrderedCountIndex << 2; 6077 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6078 (Instruction << 4); 6079 6080 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6081 Offset1 |= (CountDw - 1) << 6; 6082 6083 unsigned Offset = Offset0 | (Offset1 << 8); 6084 6085 SDValue Ops[] = { 6086 Chain, 6087 Value, 6088 DAG.getTargetConstant(Offset, DL, MVT::i16), 6089 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6090 }; 6091 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6092 M->getVTList(), Ops, M->getMemoryVT(), 6093 M->getMemOperand()); 6094 } 6095 case Intrinsic::amdgcn_ds_fadd: { 6096 MemSDNode *M = cast<MemSDNode>(Op); 6097 unsigned Opc; 6098 switch (IntrID) { 6099 case Intrinsic::amdgcn_ds_fadd: 6100 Opc = ISD::ATOMIC_LOAD_FADD; 6101 break; 6102 } 6103 6104 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6105 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6106 M->getMemOperand()); 6107 } 6108 case Intrinsic::amdgcn_atomic_inc: 6109 case Intrinsic::amdgcn_atomic_dec: 6110 case Intrinsic::amdgcn_ds_fmin: 6111 case Intrinsic::amdgcn_ds_fmax: { 6112 MemSDNode *M = cast<MemSDNode>(Op); 6113 unsigned Opc; 6114 switch (IntrID) { 6115 case Intrinsic::amdgcn_atomic_inc: 6116 Opc = AMDGPUISD::ATOMIC_INC; 6117 break; 6118 case Intrinsic::amdgcn_atomic_dec: 6119 Opc = AMDGPUISD::ATOMIC_DEC; 6120 break; 6121 case Intrinsic::amdgcn_ds_fmin: 6122 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6123 break; 6124 case Intrinsic::amdgcn_ds_fmax: 6125 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6126 break; 6127 default: 6128 llvm_unreachable("Unknown intrinsic!"); 6129 } 6130 SDValue Ops[] = { 6131 M->getOperand(0), // Chain 6132 M->getOperand(2), // Ptr 6133 M->getOperand(3) // Value 6134 }; 6135 6136 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6137 M->getMemoryVT(), M->getMemOperand()); 6138 } 6139 case Intrinsic::amdgcn_buffer_load: 6140 case Intrinsic::amdgcn_buffer_load_format: { 6141 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6142 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6143 unsigned IdxEn = 1; 6144 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6145 IdxEn = Idx->getZExtValue() != 0; 6146 SDValue Ops[] = { 6147 Op.getOperand(0), // Chain 6148 Op.getOperand(2), // rsrc 6149 Op.getOperand(3), // vindex 6150 SDValue(), // voffset -- will be set by setBufferOffsets 6151 SDValue(), // soffset -- will be set by setBufferOffsets 6152 SDValue(), // offset -- will be set by setBufferOffsets 6153 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6154 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6155 }; 6156 6157 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6158 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6159 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6160 6161 EVT VT = Op.getValueType(); 6162 EVT IntVT = VT.changeTypeToInteger(); 6163 auto *M = cast<MemSDNode>(Op); 6164 EVT LoadVT = Op.getValueType(); 6165 6166 if (LoadVT.getScalarType() == MVT::f16) 6167 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6168 M, DAG, Ops); 6169 6170 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6171 if (LoadVT.getScalarType() == MVT::i8 || 6172 LoadVT.getScalarType() == MVT::i16) 6173 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6174 6175 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6176 M->getMemOperand(), DAG); 6177 } 6178 case Intrinsic::amdgcn_raw_buffer_load: 6179 case Intrinsic::amdgcn_raw_buffer_load_format: { 6180 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6181 SDValue Ops[] = { 6182 Op.getOperand(0), // Chain 6183 Op.getOperand(2), // rsrc 6184 DAG.getConstant(0, DL, MVT::i32), // vindex 6185 Offsets.first, // voffset 6186 Op.getOperand(4), // soffset 6187 Offsets.second, // offset 6188 Op.getOperand(5), // cachepolicy 6189 DAG.getConstant(0, DL, MVT::i1), // idxen 6190 }; 6191 6192 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ? 6193 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6194 6195 EVT VT = Op.getValueType(); 6196 EVT IntVT = VT.changeTypeToInteger(); 6197 auto *M = cast<MemSDNode>(Op); 6198 EVT LoadVT = Op.getValueType(); 6199 6200 if (LoadVT.getScalarType() == MVT::f16) 6201 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6202 M, DAG, Ops); 6203 6204 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6205 if (LoadVT.getScalarType() == MVT::i8 || 6206 LoadVT.getScalarType() == MVT::i16) 6207 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6208 6209 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6210 M->getMemOperand(), DAG); 6211 } 6212 case Intrinsic::amdgcn_struct_buffer_load: 6213 case Intrinsic::amdgcn_struct_buffer_load_format: { 6214 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6215 SDValue Ops[] = { 6216 Op.getOperand(0), // Chain 6217 Op.getOperand(2), // rsrc 6218 Op.getOperand(3), // vindex 6219 Offsets.first, // voffset 6220 Op.getOperand(5), // soffset 6221 Offsets.second, // offset 6222 Op.getOperand(6), // cachepolicy 6223 DAG.getConstant(1, DL, MVT::i1), // idxen 6224 }; 6225 6226 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ? 6227 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6228 6229 EVT VT = Op.getValueType(); 6230 EVT IntVT = VT.changeTypeToInteger(); 6231 auto *M = cast<MemSDNode>(Op); 6232 EVT LoadVT = Op.getValueType(); 6233 6234 if (LoadVT.getScalarType() == MVT::f16) 6235 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6236 M, DAG, Ops); 6237 6238 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6239 if (LoadVT.getScalarType() == MVT::i8 || 6240 LoadVT.getScalarType() == MVT::i16) 6241 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6242 6243 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6244 M->getMemOperand(), DAG); 6245 } 6246 case Intrinsic::amdgcn_tbuffer_load: { 6247 MemSDNode *M = cast<MemSDNode>(Op); 6248 EVT LoadVT = Op.getValueType(); 6249 6250 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6251 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6252 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6253 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6254 unsigned IdxEn = 1; 6255 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6256 IdxEn = Idx->getZExtValue() != 0; 6257 SDValue Ops[] = { 6258 Op.getOperand(0), // Chain 6259 Op.getOperand(2), // rsrc 6260 Op.getOperand(3), // vindex 6261 Op.getOperand(4), // voffset 6262 Op.getOperand(5), // soffset 6263 Op.getOperand(6), // offset 6264 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6265 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6266 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6267 }; 6268 6269 if (LoadVT.getScalarType() == MVT::f16) 6270 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6271 M, DAG, Ops); 6272 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6273 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6274 DAG); 6275 } 6276 case Intrinsic::amdgcn_raw_tbuffer_load: { 6277 MemSDNode *M = cast<MemSDNode>(Op); 6278 EVT LoadVT = Op.getValueType(); 6279 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6280 6281 SDValue Ops[] = { 6282 Op.getOperand(0), // Chain 6283 Op.getOperand(2), // rsrc 6284 DAG.getConstant(0, DL, MVT::i32), // vindex 6285 Offsets.first, // voffset 6286 Op.getOperand(4), // soffset 6287 Offsets.second, // offset 6288 Op.getOperand(5), // format 6289 Op.getOperand(6), // cachepolicy 6290 DAG.getConstant(0, DL, MVT::i1), // idxen 6291 }; 6292 6293 if (LoadVT.getScalarType() == MVT::f16) 6294 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6295 M, DAG, Ops); 6296 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6297 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6298 DAG); 6299 } 6300 case Intrinsic::amdgcn_struct_tbuffer_load: { 6301 MemSDNode *M = cast<MemSDNode>(Op); 6302 EVT LoadVT = Op.getValueType(); 6303 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6304 6305 SDValue Ops[] = { 6306 Op.getOperand(0), // Chain 6307 Op.getOperand(2), // rsrc 6308 Op.getOperand(3), // vindex 6309 Offsets.first, // voffset 6310 Op.getOperand(5), // soffset 6311 Offsets.second, // offset 6312 Op.getOperand(6), // format 6313 Op.getOperand(7), // cachepolicy 6314 DAG.getConstant(1, DL, MVT::i1), // idxen 6315 }; 6316 6317 if (LoadVT.getScalarType() == MVT::f16) 6318 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6319 M, DAG, Ops); 6320 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6321 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6322 DAG); 6323 } 6324 case Intrinsic::amdgcn_buffer_atomic_swap: 6325 case Intrinsic::amdgcn_buffer_atomic_add: 6326 case Intrinsic::amdgcn_buffer_atomic_sub: 6327 case Intrinsic::amdgcn_buffer_atomic_smin: 6328 case Intrinsic::amdgcn_buffer_atomic_umin: 6329 case Intrinsic::amdgcn_buffer_atomic_smax: 6330 case Intrinsic::amdgcn_buffer_atomic_umax: 6331 case Intrinsic::amdgcn_buffer_atomic_and: 6332 case Intrinsic::amdgcn_buffer_atomic_or: 6333 case Intrinsic::amdgcn_buffer_atomic_xor: { 6334 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6335 unsigned IdxEn = 1; 6336 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6337 IdxEn = Idx->getZExtValue() != 0; 6338 SDValue Ops[] = { 6339 Op.getOperand(0), // Chain 6340 Op.getOperand(2), // vdata 6341 Op.getOperand(3), // rsrc 6342 Op.getOperand(4), // vindex 6343 SDValue(), // voffset -- will be set by setBufferOffsets 6344 SDValue(), // soffset -- will be set by setBufferOffsets 6345 SDValue(), // offset -- will be set by setBufferOffsets 6346 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6347 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6348 }; 6349 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6350 EVT VT = Op.getValueType(); 6351 6352 auto *M = cast<MemSDNode>(Op); 6353 unsigned Opcode = 0; 6354 6355 switch (IntrID) { 6356 case Intrinsic::amdgcn_buffer_atomic_swap: 6357 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6358 break; 6359 case Intrinsic::amdgcn_buffer_atomic_add: 6360 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6361 break; 6362 case Intrinsic::amdgcn_buffer_atomic_sub: 6363 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6364 break; 6365 case Intrinsic::amdgcn_buffer_atomic_smin: 6366 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6367 break; 6368 case Intrinsic::amdgcn_buffer_atomic_umin: 6369 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6370 break; 6371 case Intrinsic::amdgcn_buffer_atomic_smax: 6372 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6373 break; 6374 case Intrinsic::amdgcn_buffer_atomic_umax: 6375 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6376 break; 6377 case Intrinsic::amdgcn_buffer_atomic_and: 6378 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6379 break; 6380 case Intrinsic::amdgcn_buffer_atomic_or: 6381 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6382 break; 6383 case Intrinsic::amdgcn_buffer_atomic_xor: 6384 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6385 break; 6386 default: 6387 llvm_unreachable("unhandled atomic opcode"); 6388 } 6389 6390 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6391 M->getMemOperand()); 6392 } 6393 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6394 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6395 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6396 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6397 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6398 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6399 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6400 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6401 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6402 case Intrinsic::amdgcn_raw_buffer_atomic_xor: { 6403 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6404 SDValue Ops[] = { 6405 Op.getOperand(0), // Chain 6406 Op.getOperand(2), // vdata 6407 Op.getOperand(3), // rsrc 6408 DAG.getConstant(0, DL, MVT::i32), // vindex 6409 Offsets.first, // voffset 6410 Op.getOperand(5), // soffset 6411 Offsets.second, // offset 6412 Op.getOperand(6), // cachepolicy 6413 DAG.getConstant(0, DL, MVT::i1), // idxen 6414 }; 6415 EVT VT = Op.getValueType(); 6416 6417 auto *M = cast<MemSDNode>(Op); 6418 unsigned Opcode = 0; 6419 6420 switch (IntrID) { 6421 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6422 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6423 break; 6424 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6425 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6426 break; 6427 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6428 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6429 break; 6430 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6431 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6432 break; 6433 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6434 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6435 break; 6436 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6437 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6438 break; 6439 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6440 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6441 break; 6442 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6443 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6444 break; 6445 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6446 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6447 break; 6448 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6449 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6450 break; 6451 default: 6452 llvm_unreachable("unhandled atomic opcode"); 6453 } 6454 6455 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6456 M->getMemOperand()); 6457 } 6458 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6459 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6460 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6461 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6462 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6463 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6464 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6465 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6466 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6467 case Intrinsic::amdgcn_struct_buffer_atomic_xor: { 6468 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6469 SDValue Ops[] = { 6470 Op.getOperand(0), // Chain 6471 Op.getOperand(2), // vdata 6472 Op.getOperand(3), // rsrc 6473 Op.getOperand(4), // vindex 6474 Offsets.first, // voffset 6475 Op.getOperand(6), // soffset 6476 Offsets.second, // offset 6477 Op.getOperand(7), // cachepolicy 6478 DAG.getConstant(1, DL, MVT::i1), // idxen 6479 }; 6480 EVT VT = Op.getValueType(); 6481 6482 auto *M = cast<MemSDNode>(Op); 6483 unsigned Opcode = 0; 6484 6485 switch (IntrID) { 6486 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6487 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6488 break; 6489 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6490 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6491 break; 6492 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6493 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6494 break; 6495 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6496 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6497 break; 6498 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6499 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6500 break; 6501 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6502 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6503 break; 6504 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6505 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6506 break; 6507 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6508 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6509 break; 6510 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6511 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6512 break; 6513 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6514 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6515 break; 6516 default: 6517 llvm_unreachable("unhandled atomic opcode"); 6518 } 6519 6520 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6521 M->getMemOperand()); 6522 } 6523 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6524 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6525 unsigned IdxEn = 1; 6526 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6527 IdxEn = Idx->getZExtValue() != 0; 6528 SDValue Ops[] = { 6529 Op.getOperand(0), // Chain 6530 Op.getOperand(2), // src 6531 Op.getOperand(3), // cmp 6532 Op.getOperand(4), // rsrc 6533 Op.getOperand(5), // vindex 6534 SDValue(), // voffset -- will be set by setBufferOffsets 6535 SDValue(), // soffset -- will be set by setBufferOffsets 6536 SDValue(), // offset -- will be set by setBufferOffsets 6537 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6538 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6539 }; 6540 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6541 EVT VT = Op.getValueType(); 6542 auto *M = cast<MemSDNode>(Op); 6543 6544 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6545 Op->getVTList(), Ops, VT, M->getMemOperand()); 6546 } 6547 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6548 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6549 SDValue Ops[] = { 6550 Op.getOperand(0), // Chain 6551 Op.getOperand(2), // src 6552 Op.getOperand(3), // cmp 6553 Op.getOperand(4), // rsrc 6554 DAG.getConstant(0, DL, MVT::i32), // vindex 6555 Offsets.first, // voffset 6556 Op.getOperand(6), // soffset 6557 Offsets.second, // offset 6558 Op.getOperand(7), // cachepolicy 6559 DAG.getConstant(0, DL, MVT::i1), // idxen 6560 }; 6561 EVT VT = Op.getValueType(); 6562 auto *M = cast<MemSDNode>(Op); 6563 6564 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6565 Op->getVTList(), Ops, VT, M->getMemOperand()); 6566 } 6567 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6568 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6569 SDValue Ops[] = { 6570 Op.getOperand(0), // Chain 6571 Op.getOperand(2), // src 6572 Op.getOperand(3), // cmp 6573 Op.getOperand(4), // rsrc 6574 Op.getOperand(5), // vindex 6575 Offsets.first, // voffset 6576 Op.getOperand(7), // soffset 6577 Offsets.second, // offset 6578 Op.getOperand(8), // cachepolicy 6579 DAG.getConstant(1, DL, MVT::i1), // idxen 6580 }; 6581 EVT VT = Op.getValueType(); 6582 auto *M = cast<MemSDNode>(Op); 6583 6584 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6585 Op->getVTList(), Ops, VT, M->getMemOperand()); 6586 } 6587 6588 default: 6589 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6590 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6591 return lowerImage(Op, ImageDimIntr, DAG); 6592 6593 return SDValue(); 6594 } 6595 } 6596 6597 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6598 // dwordx4 if on SI. 6599 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6600 SDVTList VTList, 6601 ArrayRef<SDValue> Ops, EVT MemVT, 6602 MachineMemOperand *MMO, 6603 SelectionDAG &DAG) const { 6604 EVT VT = VTList.VTs[0]; 6605 EVT WidenedVT = VT; 6606 EVT WidenedMemVT = MemVT; 6607 if (!Subtarget->hasDwordx3LoadStores() && 6608 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6609 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6610 WidenedVT.getVectorElementType(), 4); 6611 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6612 WidenedMemVT.getVectorElementType(), 4); 6613 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6614 } 6615 6616 assert(VTList.NumVTs == 2); 6617 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6618 6619 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6620 WidenedMemVT, MMO); 6621 if (WidenedVT != VT) { 6622 auto Extract = DAG.getNode( 6623 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6624 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6625 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6626 } 6627 return NewOp; 6628 } 6629 6630 SDValue SITargetLowering::handleD16VData(SDValue VData, 6631 SelectionDAG &DAG) const { 6632 EVT StoreVT = VData.getValueType(); 6633 6634 // No change for f16 and legal vector D16 types. 6635 if (!StoreVT.isVector()) 6636 return VData; 6637 6638 SDLoc DL(VData); 6639 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6640 6641 if (Subtarget->hasUnpackedD16VMem()) { 6642 // We need to unpack the packed data to store. 6643 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6644 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6645 6646 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6647 StoreVT.getVectorNumElements()); 6648 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6649 return DAG.UnrollVectorOp(ZExt.getNode()); 6650 } 6651 6652 assert(isTypeLegal(StoreVT)); 6653 return VData; 6654 } 6655 6656 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6657 SelectionDAG &DAG) const { 6658 SDLoc DL(Op); 6659 SDValue Chain = Op.getOperand(0); 6660 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6661 MachineFunction &MF = DAG.getMachineFunction(); 6662 6663 switch (IntrinsicID) { 6664 case Intrinsic::amdgcn_exp: { 6665 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6666 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6667 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6668 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6669 6670 const SDValue Ops[] = { 6671 Chain, 6672 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6673 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6674 Op.getOperand(4), // src0 6675 Op.getOperand(5), // src1 6676 Op.getOperand(6), // src2 6677 Op.getOperand(7), // src3 6678 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6679 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6680 }; 6681 6682 unsigned Opc = Done->isNullValue() ? 6683 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6684 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6685 } 6686 case Intrinsic::amdgcn_exp_compr: { 6687 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6688 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6689 SDValue Src0 = Op.getOperand(4); 6690 SDValue Src1 = Op.getOperand(5); 6691 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6692 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6693 6694 SDValue Undef = DAG.getUNDEF(MVT::f32); 6695 const SDValue Ops[] = { 6696 Chain, 6697 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6698 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6699 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6700 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6701 Undef, // src2 6702 Undef, // src3 6703 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6704 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6705 }; 6706 6707 unsigned Opc = Done->isNullValue() ? 6708 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6709 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6710 } 6711 case Intrinsic::amdgcn_s_sendmsg: 6712 case Intrinsic::amdgcn_s_sendmsghalt: { 6713 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 6714 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 6715 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 6716 SDValue Glue = Chain.getValue(1); 6717 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 6718 Op.getOperand(2), Glue); 6719 } 6720 case Intrinsic::amdgcn_init_exec: { 6721 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 6722 Op.getOperand(2)); 6723 } 6724 case Intrinsic::amdgcn_init_exec_from_input: { 6725 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 6726 Op.getOperand(2), Op.getOperand(3)); 6727 } 6728 case Intrinsic::amdgcn_s_barrier: { 6729 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6730 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6731 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6732 if (WGSize <= ST.getWavefrontSize()) 6733 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6734 Op.getOperand(0)), 0); 6735 } 6736 return SDValue(); 6737 }; 6738 case Intrinsic::amdgcn_tbuffer_store: { 6739 SDValue VData = Op.getOperand(2); 6740 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6741 if (IsD16) 6742 VData = handleD16VData(VData, DAG); 6743 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6744 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6745 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6746 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6747 unsigned IdxEn = 1; 6748 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6749 IdxEn = Idx->getZExtValue() != 0; 6750 SDValue Ops[] = { 6751 Chain, 6752 VData, // vdata 6753 Op.getOperand(3), // rsrc 6754 Op.getOperand(4), // vindex 6755 Op.getOperand(5), // voffset 6756 Op.getOperand(6), // soffset 6757 Op.getOperand(7), // offset 6758 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6759 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6760 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen 6761 }; 6762 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6763 AMDGPUISD::TBUFFER_STORE_FORMAT; 6764 MemSDNode *M = cast<MemSDNode>(Op); 6765 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6766 M->getMemoryVT(), M->getMemOperand()); 6767 } 6768 6769 case Intrinsic::amdgcn_struct_tbuffer_store: { 6770 SDValue VData = Op.getOperand(2); 6771 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6772 if (IsD16) 6773 VData = handleD16VData(VData, DAG); 6774 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6775 SDValue Ops[] = { 6776 Chain, 6777 VData, // vdata 6778 Op.getOperand(3), // rsrc 6779 Op.getOperand(4), // vindex 6780 Offsets.first, // voffset 6781 Op.getOperand(6), // soffset 6782 Offsets.second, // offset 6783 Op.getOperand(7), // format 6784 Op.getOperand(8), // cachepolicy 6785 DAG.getConstant(1, DL, MVT::i1), // idexen 6786 }; 6787 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6788 AMDGPUISD::TBUFFER_STORE_FORMAT; 6789 MemSDNode *M = cast<MemSDNode>(Op); 6790 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6791 M->getMemoryVT(), M->getMemOperand()); 6792 } 6793 6794 case Intrinsic::amdgcn_raw_tbuffer_store: { 6795 SDValue VData = Op.getOperand(2); 6796 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6797 if (IsD16) 6798 VData = handleD16VData(VData, DAG); 6799 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6800 SDValue Ops[] = { 6801 Chain, 6802 VData, // vdata 6803 Op.getOperand(3), // rsrc 6804 DAG.getConstant(0, DL, MVT::i32), // vindex 6805 Offsets.first, // voffset 6806 Op.getOperand(5), // soffset 6807 Offsets.second, // offset 6808 Op.getOperand(6), // format 6809 Op.getOperand(7), // cachepolicy 6810 DAG.getConstant(0, DL, MVT::i1), // idexen 6811 }; 6812 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6813 AMDGPUISD::TBUFFER_STORE_FORMAT; 6814 MemSDNode *M = cast<MemSDNode>(Op); 6815 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6816 M->getMemoryVT(), M->getMemOperand()); 6817 } 6818 6819 case Intrinsic::amdgcn_buffer_store: 6820 case Intrinsic::amdgcn_buffer_store_format: { 6821 SDValue VData = Op.getOperand(2); 6822 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6823 if (IsD16) 6824 VData = handleD16VData(VData, DAG); 6825 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6826 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6827 unsigned IdxEn = 1; 6828 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6829 IdxEn = Idx->getZExtValue() != 0; 6830 SDValue Ops[] = { 6831 Chain, 6832 VData, 6833 Op.getOperand(3), // rsrc 6834 Op.getOperand(4), // vindex 6835 SDValue(), // voffset -- will be set by setBufferOffsets 6836 SDValue(), // soffset -- will be set by setBufferOffsets 6837 SDValue(), // offset -- will be set by setBufferOffsets 6838 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6839 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6840 }; 6841 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6842 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6843 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6844 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6845 MemSDNode *M = cast<MemSDNode>(Op); 6846 6847 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6848 EVT VDataType = VData.getValueType().getScalarType(); 6849 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6850 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6851 6852 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6853 M->getMemoryVT(), M->getMemOperand()); 6854 } 6855 6856 case Intrinsic::amdgcn_raw_buffer_store: 6857 case Intrinsic::amdgcn_raw_buffer_store_format: { 6858 SDValue VData = Op.getOperand(2); 6859 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6860 if (IsD16) 6861 VData = handleD16VData(VData, DAG); 6862 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6863 SDValue Ops[] = { 6864 Chain, 6865 VData, 6866 Op.getOperand(3), // rsrc 6867 DAG.getConstant(0, DL, MVT::i32), // vindex 6868 Offsets.first, // voffset 6869 Op.getOperand(5), // soffset 6870 Offsets.second, // offset 6871 Op.getOperand(6), // cachepolicy 6872 DAG.getConstant(0, DL, MVT::i1), // idxen 6873 }; 6874 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ? 6875 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6876 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6877 MemSDNode *M = cast<MemSDNode>(Op); 6878 6879 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6880 EVT VDataType = VData.getValueType().getScalarType(); 6881 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6882 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6883 6884 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6885 M->getMemoryVT(), M->getMemOperand()); 6886 } 6887 6888 case Intrinsic::amdgcn_struct_buffer_store: 6889 case Intrinsic::amdgcn_struct_buffer_store_format: { 6890 SDValue VData = Op.getOperand(2); 6891 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6892 if (IsD16) 6893 VData = handleD16VData(VData, DAG); 6894 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6895 SDValue Ops[] = { 6896 Chain, 6897 VData, 6898 Op.getOperand(3), // rsrc 6899 Op.getOperand(4), // vindex 6900 Offsets.first, // voffset 6901 Op.getOperand(6), // soffset 6902 Offsets.second, // offset 6903 Op.getOperand(7), // cachepolicy 6904 DAG.getConstant(1, DL, MVT::i1), // idxen 6905 }; 6906 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6907 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6908 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6909 MemSDNode *M = cast<MemSDNode>(Op); 6910 6911 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6912 EVT VDataType = VData.getValueType().getScalarType(); 6913 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6914 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6915 6916 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6917 M->getMemoryVT(), M->getMemOperand()); 6918 } 6919 6920 case Intrinsic::amdgcn_buffer_atomic_fadd: { 6921 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6922 unsigned IdxEn = 1; 6923 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6924 IdxEn = Idx->getZExtValue() != 0; 6925 SDValue Ops[] = { 6926 Chain, 6927 Op.getOperand(2), // vdata 6928 Op.getOperand(3), // rsrc 6929 Op.getOperand(4), // vindex 6930 SDValue(), // voffset -- will be set by setBufferOffsets 6931 SDValue(), // soffset -- will be set by setBufferOffsets 6932 SDValue(), // offset -- will be set by setBufferOffsets 6933 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6934 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6935 }; 6936 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6937 EVT VT = Op.getOperand(2).getValueType(); 6938 6939 auto *M = cast<MemSDNode>(Op); 6940 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 6941 : AMDGPUISD::BUFFER_ATOMIC_FADD; 6942 6943 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6944 M->getMemOperand()); 6945 } 6946 6947 case Intrinsic::amdgcn_global_atomic_fadd: { 6948 SDValue Ops[] = { 6949 Chain, 6950 Op.getOperand(2), // ptr 6951 Op.getOperand(3) // vdata 6952 }; 6953 EVT VT = Op.getOperand(3).getValueType(); 6954 6955 auto *M = cast<MemSDNode>(Op); 6956 unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD 6957 : AMDGPUISD::ATOMIC_FADD; 6958 6959 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6960 M->getMemOperand()); 6961 } 6962 6963 case Intrinsic::amdgcn_end_cf: 6964 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 6965 Op->getOperand(2), Chain), 0); 6966 6967 default: { 6968 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6969 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6970 return lowerImage(Op, ImageDimIntr, DAG); 6971 6972 return Op; 6973 } 6974 } 6975 } 6976 6977 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 6978 // offset (the offset that is included in bounds checking and swizzling, to be 6979 // split between the instruction's voffset and immoffset fields) and soffset 6980 // (the offset that is excluded from bounds checking and swizzling, to go in 6981 // the instruction's soffset field). This function takes the first kind of 6982 // offset and figures out how to split it between voffset and immoffset. 6983 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 6984 SDValue Offset, SelectionDAG &DAG) const { 6985 SDLoc DL(Offset); 6986 const unsigned MaxImm = 4095; 6987 SDValue N0 = Offset; 6988 ConstantSDNode *C1 = nullptr; 6989 6990 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 6991 N0 = SDValue(); 6992 else if (DAG.isBaseWithConstantOffset(N0)) { 6993 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 6994 N0 = N0.getOperand(0); 6995 } 6996 6997 if (C1) { 6998 unsigned ImmOffset = C1->getZExtValue(); 6999 // If the immediate value is too big for the immoffset field, put the value 7000 // and -4096 into the immoffset field so that the value that is copied/added 7001 // for the voffset field is a multiple of 4096, and it stands more chance 7002 // of being CSEd with the copy/add for another similar load/store. 7003 // However, do not do that rounding down to a multiple of 4096 if that is a 7004 // negative number, as it appears to be illegal to have a negative offset 7005 // in the vgpr, even if adding the immediate offset makes it positive. 7006 unsigned Overflow = ImmOffset & ~MaxImm; 7007 ImmOffset -= Overflow; 7008 if ((int32_t)Overflow < 0) { 7009 Overflow += ImmOffset; 7010 ImmOffset = 0; 7011 } 7012 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32)); 7013 if (Overflow) { 7014 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7015 if (!N0) 7016 N0 = OverflowVal; 7017 else { 7018 SDValue Ops[] = { N0, OverflowVal }; 7019 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7020 } 7021 } 7022 } 7023 if (!N0) 7024 N0 = DAG.getConstant(0, DL, MVT::i32); 7025 if (!C1) 7026 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32)); 7027 return {N0, SDValue(C1, 0)}; 7028 } 7029 7030 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7031 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7032 // pointed to by Offsets. 7033 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7034 SelectionDAG &DAG, SDValue *Offsets, 7035 unsigned Align) const { 7036 SDLoc DL(CombinedOffset); 7037 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7038 uint32_t Imm = C->getZExtValue(); 7039 uint32_t SOffset, ImmOffset; 7040 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7041 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7042 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7043 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 7044 return; 7045 } 7046 } 7047 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7048 SDValue N0 = CombinedOffset.getOperand(0); 7049 SDValue N1 = CombinedOffset.getOperand(1); 7050 uint32_t SOffset, ImmOffset; 7051 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7052 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7053 Subtarget, Align)) { 7054 Offsets[0] = N0; 7055 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7056 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 7057 return; 7058 } 7059 } 7060 Offsets[0] = CombinedOffset; 7061 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7062 Offsets[2] = DAG.getConstant(0, DL, MVT::i32); 7063 } 7064 7065 // Handle 8 bit and 16 bit buffer loads 7066 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7067 EVT LoadVT, SDLoc DL, 7068 ArrayRef<SDValue> Ops, 7069 MemSDNode *M) const { 7070 EVT IntVT = LoadVT.changeTypeToInteger(); 7071 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7072 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7073 7074 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7075 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7076 Ops, IntVT, 7077 M->getMemOperand()); 7078 SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL, 7079 LoadVT.getScalarType(), BufferLoad); 7080 return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL); 7081 } 7082 7083 // Handle 8 bit and 16 bit buffer stores 7084 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7085 EVT VDataType, SDLoc DL, 7086 SDValue Ops[], 7087 MemSDNode *M) const { 7088 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7089 Ops[1] = BufferStoreExt; 7090 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7091 AMDGPUISD::BUFFER_STORE_SHORT; 7092 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7093 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7094 M->getMemOperand()); 7095 } 7096 7097 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7098 ISD::LoadExtType ExtType, SDValue Op, 7099 const SDLoc &SL, EVT VT) { 7100 if (VT.bitsLT(Op.getValueType())) 7101 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7102 7103 switch (ExtType) { 7104 case ISD::SEXTLOAD: 7105 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7106 case ISD::ZEXTLOAD: 7107 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7108 case ISD::EXTLOAD: 7109 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7110 case ISD::NON_EXTLOAD: 7111 return Op; 7112 } 7113 7114 llvm_unreachable("invalid ext type"); 7115 } 7116 7117 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7118 SelectionDAG &DAG = DCI.DAG; 7119 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7120 return SDValue(); 7121 7122 // FIXME: Constant loads should all be marked invariant. 7123 unsigned AS = Ld->getAddressSpace(); 7124 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7125 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7126 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7127 return SDValue(); 7128 7129 // Don't do this early, since it may interfere with adjacent load merging for 7130 // illegal types. We can avoid losing alignment information for exotic types 7131 // pre-legalize. 7132 EVT MemVT = Ld->getMemoryVT(); 7133 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7134 MemVT.getSizeInBits() >= 32) 7135 return SDValue(); 7136 7137 SDLoc SL(Ld); 7138 7139 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7140 "unexpected vector extload"); 7141 7142 // TODO: Drop only high part of range. 7143 SDValue Ptr = Ld->getBasePtr(); 7144 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7145 MVT::i32, SL, Ld->getChain(), Ptr, 7146 Ld->getOffset(), 7147 Ld->getPointerInfo(), MVT::i32, 7148 Ld->getAlignment(), 7149 Ld->getMemOperand()->getFlags(), 7150 Ld->getAAInfo(), 7151 nullptr); // Drop ranges 7152 7153 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7154 if (MemVT.isFloatingPoint()) { 7155 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7156 "unexpected fp extload"); 7157 TruncVT = MemVT.changeTypeToInteger(); 7158 } 7159 7160 SDValue Cvt = NewLoad; 7161 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7162 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7163 DAG.getValueType(TruncVT)); 7164 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7165 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7166 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7167 } else { 7168 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7169 } 7170 7171 EVT VT = Ld->getValueType(0); 7172 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7173 7174 DCI.AddToWorklist(Cvt.getNode()); 7175 7176 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7177 // the appropriate extension from the 32-bit load. 7178 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7179 DCI.AddToWorklist(Cvt.getNode()); 7180 7181 // Handle conversion back to floating point if necessary. 7182 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7183 7184 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7185 } 7186 7187 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7188 SDLoc DL(Op); 7189 LoadSDNode *Load = cast<LoadSDNode>(Op); 7190 ISD::LoadExtType ExtType = Load->getExtensionType(); 7191 EVT MemVT = Load->getMemoryVT(); 7192 7193 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7194 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7195 return SDValue(); 7196 7197 // FIXME: Copied from PPC 7198 // First, load into 32 bits, then truncate to 1 bit. 7199 7200 SDValue Chain = Load->getChain(); 7201 SDValue BasePtr = Load->getBasePtr(); 7202 MachineMemOperand *MMO = Load->getMemOperand(); 7203 7204 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7205 7206 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7207 BasePtr, RealMemVT, MMO); 7208 7209 if (!MemVT.isVector()) { 7210 SDValue Ops[] = { 7211 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7212 NewLD.getValue(1) 7213 }; 7214 7215 return DAG.getMergeValues(Ops, DL); 7216 } 7217 7218 SmallVector<SDValue, 3> Elts; 7219 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7220 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7221 DAG.getConstant(I, DL, MVT::i32)); 7222 7223 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7224 } 7225 7226 SDValue Ops[] = { 7227 DAG.getBuildVector(MemVT, DL, Elts), 7228 NewLD.getValue(1) 7229 }; 7230 7231 return DAG.getMergeValues(Ops, DL); 7232 } 7233 7234 if (!MemVT.isVector()) 7235 return SDValue(); 7236 7237 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7238 "Custom lowering for non-i32 vectors hasn't been implemented."); 7239 7240 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 7241 *Load->getMemOperand())) { 7242 SDValue Ops[2]; 7243 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7244 return DAG.getMergeValues(Ops, DL); 7245 } 7246 7247 unsigned Alignment = Load->getAlignment(); 7248 unsigned AS = Load->getAddressSpace(); 7249 if (Subtarget->hasLDSMisalignedBug() && 7250 AS == AMDGPUAS::FLAT_ADDRESS && 7251 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7252 return SplitVectorLoad(Op, DAG); 7253 } 7254 7255 MachineFunction &MF = DAG.getMachineFunction(); 7256 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7257 // If there is a possibilty that flat instruction access scratch memory 7258 // then we need to use the same legalization rules we use for private. 7259 if (AS == AMDGPUAS::FLAT_ADDRESS) 7260 AS = MFI->hasFlatScratchInit() ? 7261 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7262 7263 unsigned NumElements = MemVT.getVectorNumElements(); 7264 7265 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7266 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7267 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7268 if (MemVT.isPow2VectorType()) 7269 return SDValue(); 7270 if (NumElements == 3) 7271 return WidenVectorLoad(Op, DAG); 7272 return SplitVectorLoad(Op, DAG); 7273 } 7274 // Non-uniform loads will be selected to MUBUF instructions, so they 7275 // have the same legalization requirements as global and private 7276 // loads. 7277 // 7278 } 7279 7280 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7281 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7282 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7283 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7284 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7285 Alignment >= 4 && NumElements < 32) { 7286 if (MemVT.isPow2VectorType()) 7287 return SDValue(); 7288 if (NumElements == 3) 7289 return WidenVectorLoad(Op, DAG); 7290 return SplitVectorLoad(Op, DAG); 7291 } 7292 // Non-uniform loads will be selected to MUBUF instructions, so they 7293 // have the same legalization requirements as global and private 7294 // loads. 7295 // 7296 } 7297 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7298 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7299 AS == AMDGPUAS::GLOBAL_ADDRESS || 7300 AS == AMDGPUAS::FLAT_ADDRESS) { 7301 if (NumElements > 4) 7302 return SplitVectorLoad(Op, DAG); 7303 // v3 loads not supported on SI. 7304 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7305 return WidenVectorLoad(Op, DAG); 7306 // v3 and v4 loads are supported for private and global memory. 7307 return SDValue(); 7308 } 7309 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7310 // Depending on the setting of the private_element_size field in the 7311 // resource descriptor, we can only make private accesses up to a certain 7312 // size. 7313 switch (Subtarget->getMaxPrivateElementSize()) { 7314 case 4: 7315 return scalarizeVectorLoad(Load, DAG); 7316 case 8: 7317 if (NumElements > 2) 7318 return SplitVectorLoad(Op, DAG); 7319 return SDValue(); 7320 case 16: 7321 // Same as global/flat 7322 if (NumElements > 4) 7323 return SplitVectorLoad(Op, DAG); 7324 // v3 loads not supported on SI. 7325 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7326 return WidenVectorLoad(Op, DAG); 7327 return SDValue(); 7328 default: 7329 llvm_unreachable("unsupported private_element_size"); 7330 } 7331 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7332 // Use ds_read_b128 if possible. 7333 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7334 MemVT.getStoreSize() == 16) 7335 return SDValue(); 7336 7337 if (NumElements > 2) 7338 return SplitVectorLoad(Op, DAG); 7339 7340 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7341 // address is negative, then the instruction is incorrectly treated as 7342 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7343 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7344 // load later in the SILoadStoreOptimizer. 7345 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7346 NumElements == 2 && MemVT.getStoreSize() == 8 && 7347 Load->getAlignment() < 8) { 7348 return SplitVectorLoad(Op, DAG); 7349 } 7350 } 7351 return SDValue(); 7352 } 7353 7354 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7355 EVT VT = Op.getValueType(); 7356 assert(VT.getSizeInBits() == 64); 7357 7358 SDLoc DL(Op); 7359 SDValue Cond = Op.getOperand(0); 7360 7361 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7362 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7363 7364 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7365 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7366 7367 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7368 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7369 7370 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7371 7372 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7373 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7374 7375 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7376 7377 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7378 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7379 } 7380 7381 // Catch division cases where we can use shortcuts with rcp and rsq 7382 // instructions. 7383 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7384 SelectionDAG &DAG) const { 7385 SDLoc SL(Op); 7386 SDValue LHS = Op.getOperand(0); 7387 SDValue RHS = Op.getOperand(1); 7388 EVT VT = Op.getValueType(); 7389 const SDNodeFlags Flags = Op->getFlags(); 7390 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7391 7392 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 7393 return SDValue(); 7394 7395 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7396 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7397 if (CLHS->isExactlyValue(1.0)) { 7398 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7399 // the CI documentation has a worst case error of 1 ulp. 7400 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7401 // use it as long as we aren't trying to use denormals. 7402 // 7403 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7404 7405 // 1.0 / sqrt(x) -> rsq(x) 7406 7407 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7408 // error seems really high at 2^29 ULP. 7409 if (RHS.getOpcode() == ISD::FSQRT) 7410 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7411 7412 // 1.0 / x -> rcp(x) 7413 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7414 } 7415 7416 // Same as for 1.0, but expand the sign out of the constant. 7417 if (CLHS->isExactlyValue(-1.0)) { 7418 // -1.0 / x -> rcp (fneg x) 7419 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7420 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7421 } 7422 } 7423 } 7424 7425 if (Unsafe) { 7426 // Turn into multiply by the reciprocal. 7427 // x / y -> x * (1.0 / y) 7428 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7429 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7430 } 7431 7432 return SDValue(); 7433 } 7434 7435 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7436 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7437 if (GlueChain->getNumValues() <= 1) { 7438 return DAG.getNode(Opcode, SL, VT, A, B); 7439 } 7440 7441 assert(GlueChain->getNumValues() == 3); 7442 7443 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7444 switch (Opcode) { 7445 default: llvm_unreachable("no chain equivalent for opcode"); 7446 case ISD::FMUL: 7447 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7448 break; 7449 } 7450 7451 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7452 GlueChain.getValue(2)); 7453 } 7454 7455 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7456 EVT VT, SDValue A, SDValue B, SDValue C, 7457 SDValue GlueChain) { 7458 if (GlueChain->getNumValues() <= 1) { 7459 return DAG.getNode(Opcode, SL, VT, A, B, C); 7460 } 7461 7462 assert(GlueChain->getNumValues() == 3); 7463 7464 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7465 switch (Opcode) { 7466 default: llvm_unreachable("no chain equivalent for opcode"); 7467 case ISD::FMA: 7468 Opcode = AMDGPUISD::FMA_W_CHAIN; 7469 break; 7470 } 7471 7472 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7473 GlueChain.getValue(2)); 7474 } 7475 7476 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7477 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7478 return FastLowered; 7479 7480 SDLoc SL(Op); 7481 SDValue Src0 = Op.getOperand(0); 7482 SDValue Src1 = Op.getOperand(1); 7483 7484 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7485 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7486 7487 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7488 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7489 7490 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7491 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7492 7493 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7494 } 7495 7496 // Faster 2.5 ULP division that does not support denormals. 7497 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7498 SDLoc SL(Op); 7499 SDValue LHS = Op.getOperand(1); 7500 SDValue RHS = Op.getOperand(2); 7501 7502 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7503 7504 const APFloat K0Val(BitsToFloat(0x6f800000)); 7505 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7506 7507 const APFloat K1Val(BitsToFloat(0x2f800000)); 7508 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7509 7510 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7511 7512 EVT SetCCVT = 7513 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7514 7515 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7516 7517 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7518 7519 // TODO: Should this propagate fast-math-flags? 7520 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7521 7522 // rcp does not support denormals. 7523 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7524 7525 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7526 7527 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7528 } 7529 7530 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7531 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7532 return FastLowered; 7533 7534 SDLoc SL(Op); 7535 SDValue LHS = Op.getOperand(0); 7536 SDValue RHS = Op.getOperand(1); 7537 7538 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7539 7540 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7541 7542 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7543 RHS, RHS, LHS); 7544 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7545 LHS, RHS, LHS); 7546 7547 // Denominator is scaled to not be denormal, so using rcp is ok. 7548 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7549 DenominatorScaled); 7550 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7551 DenominatorScaled); 7552 7553 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7554 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7555 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7556 7557 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7558 7559 if (!Subtarget->hasFP32Denormals()) { 7560 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7561 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7562 SL, MVT::i32); 7563 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7564 DAG.getEntryNode(), 7565 EnableDenormValue, BitField); 7566 SDValue Ops[3] = { 7567 NegDivScale0, 7568 EnableDenorm.getValue(0), 7569 EnableDenorm.getValue(1) 7570 }; 7571 7572 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7573 } 7574 7575 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7576 ApproxRcp, One, NegDivScale0); 7577 7578 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7579 ApproxRcp, Fma0); 7580 7581 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7582 Fma1, Fma1); 7583 7584 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7585 NumeratorScaled, Mul); 7586 7587 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7588 7589 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7590 NumeratorScaled, Fma3); 7591 7592 if (!Subtarget->hasFP32Denormals()) { 7593 const SDValue DisableDenormValue = 7594 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7595 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7596 Fma4.getValue(1), 7597 DisableDenormValue, 7598 BitField, 7599 Fma4.getValue(2)); 7600 7601 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7602 DisableDenorm, DAG.getRoot()); 7603 DAG.setRoot(OutputChain); 7604 } 7605 7606 SDValue Scale = NumeratorScaled.getValue(1); 7607 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7608 Fma4, Fma1, Fma3, Scale); 7609 7610 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7611 } 7612 7613 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7614 if (DAG.getTarget().Options.UnsafeFPMath) 7615 return lowerFastUnsafeFDIV(Op, DAG); 7616 7617 SDLoc SL(Op); 7618 SDValue X = Op.getOperand(0); 7619 SDValue Y = Op.getOperand(1); 7620 7621 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7622 7623 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7624 7625 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7626 7627 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7628 7629 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7630 7631 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7632 7633 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7634 7635 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7636 7637 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7638 7639 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7640 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7641 7642 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7643 NegDivScale0, Mul, DivScale1); 7644 7645 SDValue Scale; 7646 7647 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7648 // Workaround a hardware bug on SI where the condition output from div_scale 7649 // is not usable. 7650 7651 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7652 7653 // Figure out if the scale to use for div_fmas. 7654 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7655 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7656 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7657 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7658 7659 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7660 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7661 7662 SDValue Scale0Hi 7663 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7664 SDValue Scale1Hi 7665 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7666 7667 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7668 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7669 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7670 } else { 7671 Scale = DivScale1.getValue(1); 7672 } 7673 7674 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7675 Fma4, Fma3, Mul, Scale); 7676 7677 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7678 } 7679 7680 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7681 EVT VT = Op.getValueType(); 7682 7683 if (VT == MVT::f32) 7684 return LowerFDIV32(Op, DAG); 7685 7686 if (VT == MVT::f64) 7687 return LowerFDIV64(Op, DAG); 7688 7689 if (VT == MVT::f16) 7690 return LowerFDIV16(Op, DAG); 7691 7692 llvm_unreachable("Unexpected type for fdiv"); 7693 } 7694 7695 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7696 SDLoc DL(Op); 7697 StoreSDNode *Store = cast<StoreSDNode>(Op); 7698 EVT VT = Store->getMemoryVT(); 7699 7700 if (VT == MVT::i1) { 7701 return DAG.getTruncStore(Store->getChain(), DL, 7702 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7703 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7704 } 7705 7706 assert(VT.isVector() && 7707 Store->getValue().getValueType().getScalarType() == MVT::i32); 7708 7709 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7710 *Store->getMemOperand())) { 7711 return expandUnalignedStore(Store, DAG); 7712 } 7713 7714 unsigned AS = Store->getAddressSpace(); 7715 if (Subtarget->hasLDSMisalignedBug() && 7716 AS == AMDGPUAS::FLAT_ADDRESS && 7717 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7718 return SplitVectorStore(Op, DAG); 7719 } 7720 7721 MachineFunction &MF = DAG.getMachineFunction(); 7722 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7723 // If there is a possibilty that flat instruction access scratch memory 7724 // then we need to use the same legalization rules we use for private. 7725 if (AS == AMDGPUAS::FLAT_ADDRESS) 7726 AS = MFI->hasFlatScratchInit() ? 7727 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7728 7729 unsigned NumElements = VT.getVectorNumElements(); 7730 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7731 AS == AMDGPUAS::FLAT_ADDRESS) { 7732 if (NumElements > 4) 7733 return SplitVectorStore(Op, DAG); 7734 // v3 stores not supported on SI. 7735 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7736 return SplitVectorStore(Op, DAG); 7737 return SDValue(); 7738 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7739 switch (Subtarget->getMaxPrivateElementSize()) { 7740 case 4: 7741 return scalarizeVectorStore(Store, DAG); 7742 case 8: 7743 if (NumElements > 2) 7744 return SplitVectorStore(Op, DAG); 7745 return SDValue(); 7746 case 16: 7747 if (NumElements > 4 || NumElements == 3) 7748 return SplitVectorStore(Op, DAG); 7749 return SDValue(); 7750 default: 7751 llvm_unreachable("unsupported private_element_size"); 7752 } 7753 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7754 // Use ds_write_b128 if possible. 7755 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7756 VT.getStoreSize() == 16 && NumElements != 3) 7757 return SDValue(); 7758 7759 if (NumElements > 2) 7760 return SplitVectorStore(Op, DAG); 7761 7762 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7763 // address is negative, then the instruction is incorrectly treated as 7764 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7765 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7766 // store later in the SILoadStoreOptimizer. 7767 if (!Subtarget->hasUsableDSOffset() && 7768 NumElements == 2 && VT.getStoreSize() == 8 && 7769 Store->getAlignment() < 8) { 7770 return SplitVectorStore(Op, DAG); 7771 } 7772 7773 return SDValue(); 7774 } else { 7775 llvm_unreachable("unhandled address space"); 7776 } 7777 } 7778 7779 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7780 SDLoc DL(Op); 7781 EVT VT = Op.getValueType(); 7782 SDValue Arg = Op.getOperand(0); 7783 SDValue TrigVal; 7784 7785 // TODO: Should this propagate fast-math-flags? 7786 7787 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7788 7789 if (Subtarget->hasTrigReducedRange()) { 7790 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7791 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7792 } else { 7793 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7794 } 7795 7796 switch (Op.getOpcode()) { 7797 case ISD::FCOS: 7798 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7799 case ISD::FSIN: 7800 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7801 default: 7802 llvm_unreachable("Wrong trig opcode"); 7803 } 7804 } 7805 7806 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7807 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7808 assert(AtomicNode->isCompareAndSwap()); 7809 unsigned AS = AtomicNode->getAddressSpace(); 7810 7811 // No custom lowering required for local address space 7812 if (!isFlatGlobalAddrSpace(AS)) 7813 return Op; 7814 7815 // Non-local address space requires custom lowering for atomic compare 7816 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7817 SDLoc DL(Op); 7818 SDValue ChainIn = Op.getOperand(0); 7819 SDValue Addr = Op.getOperand(1); 7820 SDValue Old = Op.getOperand(2); 7821 SDValue New = Op.getOperand(3); 7822 EVT VT = Op.getValueType(); 7823 MVT SimpleVT = VT.getSimpleVT(); 7824 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7825 7826 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7827 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7828 7829 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7830 Ops, VT, AtomicNode->getMemOperand()); 7831 } 7832 7833 //===----------------------------------------------------------------------===// 7834 // Custom DAG optimizations 7835 //===----------------------------------------------------------------------===// 7836 7837 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7838 DAGCombinerInfo &DCI) const { 7839 EVT VT = N->getValueType(0); 7840 EVT ScalarVT = VT.getScalarType(); 7841 if (ScalarVT != MVT::f32) 7842 return SDValue(); 7843 7844 SelectionDAG &DAG = DCI.DAG; 7845 SDLoc DL(N); 7846 7847 SDValue Src = N->getOperand(0); 7848 EVT SrcVT = Src.getValueType(); 7849 7850 // TODO: We could try to match extracting the higher bytes, which would be 7851 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7852 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7853 // about in practice. 7854 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7855 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7856 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7857 DCI.AddToWorklist(Cvt.getNode()); 7858 return Cvt; 7859 } 7860 } 7861 7862 return SDValue(); 7863 } 7864 7865 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7866 7867 // This is a variant of 7868 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7869 // 7870 // The normal DAG combiner will do this, but only if the add has one use since 7871 // that would increase the number of instructions. 7872 // 7873 // This prevents us from seeing a constant offset that can be folded into a 7874 // memory instruction's addressing mode. If we know the resulting add offset of 7875 // a pointer can be folded into an addressing offset, we can replace the pointer 7876 // operand with the add of new constant offset. This eliminates one of the uses, 7877 // and may allow the remaining use to also be simplified. 7878 // 7879 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7880 unsigned AddrSpace, 7881 EVT MemVT, 7882 DAGCombinerInfo &DCI) const { 7883 SDValue N0 = N->getOperand(0); 7884 SDValue N1 = N->getOperand(1); 7885 7886 // We only do this to handle cases where it's profitable when there are 7887 // multiple uses of the add, so defer to the standard combine. 7888 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7889 N0->hasOneUse()) 7890 return SDValue(); 7891 7892 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7893 if (!CN1) 7894 return SDValue(); 7895 7896 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7897 if (!CAdd) 7898 return SDValue(); 7899 7900 // If the resulting offset is too large, we can't fold it into the addressing 7901 // mode offset. 7902 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7903 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7904 7905 AddrMode AM; 7906 AM.HasBaseReg = true; 7907 AM.BaseOffs = Offset.getSExtValue(); 7908 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7909 return SDValue(); 7910 7911 SelectionDAG &DAG = DCI.DAG; 7912 SDLoc SL(N); 7913 EVT VT = N->getValueType(0); 7914 7915 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 7916 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 7917 7918 SDNodeFlags Flags; 7919 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 7920 (N0.getOpcode() == ISD::OR || 7921 N0->getFlags().hasNoUnsignedWrap())); 7922 7923 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 7924 } 7925 7926 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 7927 DAGCombinerInfo &DCI) const { 7928 SDValue Ptr = N->getBasePtr(); 7929 SelectionDAG &DAG = DCI.DAG; 7930 SDLoc SL(N); 7931 7932 // TODO: We could also do this for multiplies. 7933 if (Ptr.getOpcode() == ISD::SHL) { 7934 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 7935 N->getMemoryVT(), DCI); 7936 if (NewPtr) { 7937 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 7938 7939 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 7940 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 7941 } 7942 } 7943 7944 return SDValue(); 7945 } 7946 7947 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 7948 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 7949 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 7950 (Opc == ISD::XOR && Val == 0); 7951 } 7952 7953 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 7954 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 7955 // integer combine opportunities since most 64-bit operations are decomposed 7956 // this way. TODO: We won't want this for SALU especially if it is an inline 7957 // immediate. 7958 SDValue SITargetLowering::splitBinaryBitConstantOp( 7959 DAGCombinerInfo &DCI, 7960 const SDLoc &SL, 7961 unsigned Opc, SDValue LHS, 7962 const ConstantSDNode *CRHS) const { 7963 uint64_t Val = CRHS->getZExtValue(); 7964 uint32_t ValLo = Lo_32(Val); 7965 uint32_t ValHi = Hi_32(Val); 7966 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7967 7968 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 7969 bitOpWithConstantIsReducible(Opc, ValHi)) || 7970 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 7971 // If we need to materialize a 64-bit immediate, it will be split up later 7972 // anyway. Avoid creating the harder to understand 64-bit immediate 7973 // materialization. 7974 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 7975 } 7976 7977 return SDValue(); 7978 } 7979 7980 // Returns true if argument is a boolean value which is not serialized into 7981 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 7982 static bool isBoolSGPR(SDValue V) { 7983 if (V.getValueType() != MVT::i1) 7984 return false; 7985 switch (V.getOpcode()) { 7986 default: break; 7987 case ISD::SETCC: 7988 case ISD::AND: 7989 case ISD::OR: 7990 case ISD::XOR: 7991 case AMDGPUISD::FP_CLASS: 7992 return true; 7993 } 7994 return false; 7995 } 7996 7997 // If a constant has all zeroes or all ones within each byte return it. 7998 // Otherwise return 0. 7999 static uint32_t getConstantPermuteMask(uint32_t C) { 8000 // 0xff for any zero byte in the mask 8001 uint32_t ZeroByteMask = 0; 8002 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8003 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8004 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8005 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8006 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8007 if ((NonZeroByteMask & C) != NonZeroByteMask) 8008 return 0; // Partial bytes selected. 8009 return C; 8010 } 8011 8012 // Check if a node selects whole bytes from its operand 0 starting at a byte 8013 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8014 // or -1 if not succeeded. 8015 // Note byte select encoding: 8016 // value 0-3 selects corresponding source byte; 8017 // value 0xc selects zero; 8018 // value 0xff selects 0xff. 8019 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8020 assert(V.getValueSizeInBits() == 32); 8021 8022 if (V.getNumOperands() != 2) 8023 return ~0; 8024 8025 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8026 if (!N1) 8027 return ~0; 8028 8029 uint32_t C = N1->getZExtValue(); 8030 8031 switch (V.getOpcode()) { 8032 default: 8033 break; 8034 case ISD::AND: 8035 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8036 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8037 } 8038 break; 8039 8040 case ISD::OR: 8041 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8042 return (0x03020100 & ~ConstMask) | ConstMask; 8043 } 8044 break; 8045 8046 case ISD::SHL: 8047 if (C % 8) 8048 return ~0; 8049 8050 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8051 8052 case ISD::SRL: 8053 if (C % 8) 8054 return ~0; 8055 8056 return uint32_t(0x0c0c0c0c03020100ull >> C); 8057 } 8058 8059 return ~0; 8060 } 8061 8062 SDValue SITargetLowering::performAndCombine(SDNode *N, 8063 DAGCombinerInfo &DCI) const { 8064 if (DCI.isBeforeLegalize()) 8065 return SDValue(); 8066 8067 SelectionDAG &DAG = DCI.DAG; 8068 EVT VT = N->getValueType(0); 8069 SDValue LHS = N->getOperand(0); 8070 SDValue RHS = N->getOperand(1); 8071 8072 8073 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8074 if (VT == MVT::i64 && CRHS) { 8075 if (SDValue Split 8076 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8077 return Split; 8078 } 8079 8080 if (CRHS && VT == MVT::i32) { 8081 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8082 // nb = number of trailing zeroes in mask 8083 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8084 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8085 uint64_t Mask = CRHS->getZExtValue(); 8086 unsigned Bits = countPopulation(Mask); 8087 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8088 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8089 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8090 unsigned Shift = CShift->getZExtValue(); 8091 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8092 unsigned Offset = NB + Shift; 8093 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8094 SDLoc SL(N); 8095 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8096 LHS->getOperand(0), 8097 DAG.getConstant(Offset, SL, MVT::i32), 8098 DAG.getConstant(Bits, SL, MVT::i32)); 8099 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8100 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8101 DAG.getValueType(NarrowVT)); 8102 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8103 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8104 return Shl; 8105 } 8106 } 8107 } 8108 8109 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8110 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8111 isa<ConstantSDNode>(LHS.getOperand(2))) { 8112 uint32_t Sel = getConstantPermuteMask(Mask); 8113 if (!Sel) 8114 return SDValue(); 8115 8116 // Select 0xc for all zero bytes 8117 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8118 SDLoc DL(N); 8119 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8120 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8121 } 8122 } 8123 8124 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8125 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8126 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8127 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8128 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8129 8130 SDValue X = LHS.getOperand(0); 8131 SDValue Y = RHS.getOperand(0); 8132 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8133 return SDValue(); 8134 8135 if (LCC == ISD::SETO) { 8136 if (X != LHS.getOperand(1)) 8137 return SDValue(); 8138 8139 if (RCC == ISD::SETUNE) { 8140 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8141 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8142 return SDValue(); 8143 8144 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8145 SIInstrFlags::N_SUBNORMAL | 8146 SIInstrFlags::N_ZERO | 8147 SIInstrFlags::P_ZERO | 8148 SIInstrFlags::P_SUBNORMAL | 8149 SIInstrFlags::P_NORMAL; 8150 8151 static_assert(((~(SIInstrFlags::S_NAN | 8152 SIInstrFlags::Q_NAN | 8153 SIInstrFlags::N_INFINITY | 8154 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8155 "mask not equal"); 8156 8157 SDLoc DL(N); 8158 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8159 X, DAG.getConstant(Mask, DL, MVT::i32)); 8160 } 8161 } 8162 } 8163 8164 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8165 std::swap(LHS, RHS); 8166 8167 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8168 RHS.hasOneUse()) { 8169 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8170 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8171 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8172 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8173 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8174 (RHS.getOperand(0) == LHS.getOperand(0) && 8175 LHS.getOperand(0) == LHS.getOperand(1))) { 8176 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8177 unsigned NewMask = LCC == ISD::SETO ? 8178 Mask->getZExtValue() & ~OrdMask : 8179 Mask->getZExtValue() & OrdMask; 8180 8181 SDLoc DL(N); 8182 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8183 DAG.getConstant(NewMask, DL, MVT::i32)); 8184 } 8185 } 8186 8187 if (VT == MVT::i32 && 8188 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8189 // and x, (sext cc from i1) => select cc, x, 0 8190 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8191 std::swap(LHS, RHS); 8192 if (isBoolSGPR(RHS.getOperand(0))) 8193 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8194 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8195 } 8196 8197 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8198 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8199 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8200 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8201 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8202 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8203 if (LHSMask != ~0u && RHSMask != ~0u) { 8204 // Canonicalize the expression in an attempt to have fewer unique masks 8205 // and therefore fewer registers used to hold the masks. 8206 if (LHSMask > RHSMask) { 8207 std::swap(LHSMask, RHSMask); 8208 std::swap(LHS, RHS); 8209 } 8210 8211 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8212 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8213 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8214 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8215 8216 // Check of we need to combine values from two sources within a byte. 8217 if (!(LHSUsedLanes & RHSUsedLanes) && 8218 // If we select high and lower word keep it for SDWA. 8219 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8220 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8221 // Each byte in each mask is either selector mask 0-3, or has higher 8222 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8223 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8224 // mask which is not 0xff wins. By anding both masks we have a correct 8225 // result except that 0x0c shall be corrected to give 0x0c only. 8226 uint32_t Mask = LHSMask & RHSMask; 8227 for (unsigned I = 0; I < 32; I += 8) { 8228 uint32_t ByteSel = 0xff << I; 8229 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8230 Mask &= (0x0c << I) & 0xffffffff; 8231 } 8232 8233 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8234 // or 0x0c. 8235 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8236 SDLoc DL(N); 8237 8238 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8239 LHS.getOperand(0), RHS.getOperand(0), 8240 DAG.getConstant(Sel, DL, MVT::i32)); 8241 } 8242 } 8243 } 8244 8245 return SDValue(); 8246 } 8247 8248 SDValue SITargetLowering::performOrCombine(SDNode *N, 8249 DAGCombinerInfo &DCI) const { 8250 SelectionDAG &DAG = DCI.DAG; 8251 SDValue LHS = N->getOperand(0); 8252 SDValue RHS = N->getOperand(1); 8253 8254 EVT VT = N->getValueType(0); 8255 if (VT == MVT::i1) { 8256 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8257 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8258 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8259 SDValue Src = LHS.getOperand(0); 8260 if (Src != RHS.getOperand(0)) 8261 return SDValue(); 8262 8263 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8264 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8265 if (!CLHS || !CRHS) 8266 return SDValue(); 8267 8268 // Only 10 bits are used. 8269 static const uint32_t MaxMask = 0x3ff; 8270 8271 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8272 SDLoc DL(N); 8273 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8274 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8275 } 8276 8277 return SDValue(); 8278 } 8279 8280 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8281 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8282 LHS.getOpcode() == AMDGPUISD::PERM && 8283 isa<ConstantSDNode>(LHS.getOperand(2))) { 8284 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8285 if (!Sel) 8286 return SDValue(); 8287 8288 Sel |= LHS.getConstantOperandVal(2); 8289 SDLoc DL(N); 8290 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8291 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8292 } 8293 8294 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8295 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8296 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8297 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8298 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8299 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8300 if (LHSMask != ~0u && RHSMask != ~0u) { 8301 // Canonicalize the expression in an attempt to have fewer unique masks 8302 // and therefore fewer registers used to hold the masks. 8303 if (LHSMask > RHSMask) { 8304 std::swap(LHSMask, RHSMask); 8305 std::swap(LHS, RHS); 8306 } 8307 8308 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8309 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8310 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8311 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8312 8313 // Check of we need to combine values from two sources within a byte. 8314 if (!(LHSUsedLanes & RHSUsedLanes) && 8315 // If we select high and lower word keep it for SDWA. 8316 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8317 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8318 // Kill zero bytes selected by other mask. Zero value is 0xc. 8319 LHSMask &= ~RHSUsedLanes; 8320 RHSMask &= ~LHSUsedLanes; 8321 // Add 4 to each active LHS lane 8322 LHSMask |= LHSUsedLanes & 0x04040404; 8323 // Combine masks 8324 uint32_t Sel = LHSMask | RHSMask; 8325 SDLoc DL(N); 8326 8327 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8328 LHS.getOperand(0), RHS.getOperand(0), 8329 DAG.getConstant(Sel, DL, MVT::i32)); 8330 } 8331 } 8332 } 8333 8334 if (VT != MVT::i64) 8335 return SDValue(); 8336 8337 // TODO: This could be a generic combine with a predicate for extracting the 8338 // high half of an integer being free. 8339 8340 // (or i64:x, (zero_extend i32:y)) -> 8341 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8342 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8343 RHS.getOpcode() != ISD::ZERO_EXTEND) 8344 std::swap(LHS, RHS); 8345 8346 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8347 SDValue ExtSrc = RHS.getOperand(0); 8348 EVT SrcVT = ExtSrc.getValueType(); 8349 if (SrcVT == MVT::i32) { 8350 SDLoc SL(N); 8351 SDValue LowLHS, HiBits; 8352 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8353 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8354 8355 DCI.AddToWorklist(LowOr.getNode()); 8356 DCI.AddToWorklist(HiBits.getNode()); 8357 8358 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8359 LowOr, HiBits); 8360 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8361 } 8362 } 8363 8364 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8365 if (CRHS) { 8366 if (SDValue Split 8367 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8368 return Split; 8369 } 8370 8371 return SDValue(); 8372 } 8373 8374 SDValue SITargetLowering::performXorCombine(SDNode *N, 8375 DAGCombinerInfo &DCI) const { 8376 EVT VT = N->getValueType(0); 8377 if (VT != MVT::i64) 8378 return SDValue(); 8379 8380 SDValue LHS = N->getOperand(0); 8381 SDValue RHS = N->getOperand(1); 8382 8383 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8384 if (CRHS) { 8385 if (SDValue Split 8386 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8387 return Split; 8388 } 8389 8390 return SDValue(); 8391 } 8392 8393 // Instructions that will be lowered with a final instruction that zeros the 8394 // high result bits. 8395 // XXX - probably only need to list legal operations. 8396 static bool fp16SrcZerosHighBits(unsigned Opc) { 8397 switch (Opc) { 8398 case ISD::FADD: 8399 case ISD::FSUB: 8400 case ISD::FMUL: 8401 case ISD::FDIV: 8402 case ISD::FREM: 8403 case ISD::FMA: 8404 case ISD::FMAD: 8405 case ISD::FCANONICALIZE: 8406 case ISD::FP_ROUND: 8407 case ISD::UINT_TO_FP: 8408 case ISD::SINT_TO_FP: 8409 case ISD::FABS: 8410 // Fabs is lowered to a bit operation, but it's an and which will clear the 8411 // high bits anyway. 8412 case ISD::FSQRT: 8413 case ISD::FSIN: 8414 case ISD::FCOS: 8415 case ISD::FPOWI: 8416 case ISD::FPOW: 8417 case ISD::FLOG: 8418 case ISD::FLOG2: 8419 case ISD::FLOG10: 8420 case ISD::FEXP: 8421 case ISD::FEXP2: 8422 case ISD::FCEIL: 8423 case ISD::FTRUNC: 8424 case ISD::FRINT: 8425 case ISD::FNEARBYINT: 8426 case ISD::FROUND: 8427 case ISD::FFLOOR: 8428 case ISD::FMINNUM: 8429 case ISD::FMAXNUM: 8430 case AMDGPUISD::FRACT: 8431 case AMDGPUISD::CLAMP: 8432 case AMDGPUISD::COS_HW: 8433 case AMDGPUISD::SIN_HW: 8434 case AMDGPUISD::FMIN3: 8435 case AMDGPUISD::FMAX3: 8436 case AMDGPUISD::FMED3: 8437 case AMDGPUISD::FMAD_FTZ: 8438 case AMDGPUISD::RCP: 8439 case AMDGPUISD::RSQ: 8440 case AMDGPUISD::RCP_IFLAG: 8441 case AMDGPUISD::LDEXP: 8442 return true; 8443 default: 8444 // fcopysign, select and others may be lowered to 32-bit bit operations 8445 // which don't zero the high bits. 8446 return false; 8447 } 8448 } 8449 8450 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8451 DAGCombinerInfo &DCI) const { 8452 if (!Subtarget->has16BitInsts() || 8453 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8454 return SDValue(); 8455 8456 EVT VT = N->getValueType(0); 8457 if (VT != MVT::i32) 8458 return SDValue(); 8459 8460 SDValue Src = N->getOperand(0); 8461 if (Src.getValueType() != MVT::i16) 8462 return SDValue(); 8463 8464 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8465 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8466 if (Src.getOpcode() == ISD::BITCAST) { 8467 SDValue BCSrc = Src.getOperand(0); 8468 if (BCSrc.getValueType() == MVT::f16 && 8469 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8470 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8471 } 8472 8473 return SDValue(); 8474 } 8475 8476 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8477 DAGCombinerInfo &DCI) 8478 const { 8479 SDValue Src = N->getOperand(0); 8480 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8481 8482 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8483 VTSign->getVT() == MVT::i8) || 8484 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8485 VTSign->getVT() == MVT::i16)) && 8486 Src.hasOneUse()) { 8487 auto *M = cast<MemSDNode>(Src); 8488 SDValue Ops[] = { 8489 Src.getOperand(0), // Chain 8490 Src.getOperand(1), // rsrc 8491 Src.getOperand(2), // vindex 8492 Src.getOperand(3), // voffset 8493 Src.getOperand(4), // soffset 8494 Src.getOperand(5), // offset 8495 Src.getOperand(6), 8496 Src.getOperand(7) 8497 }; 8498 // replace with BUFFER_LOAD_BYTE/SHORT 8499 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8500 Src.getOperand(0).getValueType()); 8501 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8502 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8503 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8504 ResList, 8505 Ops, M->getMemoryVT(), 8506 M->getMemOperand()); 8507 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8508 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8509 } 8510 return SDValue(); 8511 } 8512 8513 SDValue SITargetLowering::performClassCombine(SDNode *N, 8514 DAGCombinerInfo &DCI) const { 8515 SelectionDAG &DAG = DCI.DAG; 8516 SDValue Mask = N->getOperand(1); 8517 8518 // fp_class x, 0 -> false 8519 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8520 if (CMask->isNullValue()) 8521 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8522 } 8523 8524 if (N->getOperand(0).isUndef()) 8525 return DAG.getUNDEF(MVT::i1); 8526 8527 return SDValue(); 8528 } 8529 8530 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8531 DAGCombinerInfo &DCI) const { 8532 EVT VT = N->getValueType(0); 8533 SDValue N0 = N->getOperand(0); 8534 8535 if (N0.isUndef()) 8536 return N0; 8537 8538 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8539 N0.getOpcode() == ISD::SINT_TO_FP)) { 8540 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8541 N->getFlags()); 8542 } 8543 8544 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8545 } 8546 8547 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8548 unsigned MaxDepth) const { 8549 unsigned Opcode = Op.getOpcode(); 8550 if (Opcode == ISD::FCANONICALIZE) 8551 return true; 8552 8553 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8554 auto F = CFP->getValueAPF(); 8555 if (F.isNaN() && F.isSignaling()) 8556 return false; 8557 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 8558 } 8559 8560 // If source is a result of another standard FP operation it is already in 8561 // canonical form. 8562 if (MaxDepth == 0) 8563 return false; 8564 8565 switch (Opcode) { 8566 // These will flush denorms if required. 8567 case ISD::FADD: 8568 case ISD::FSUB: 8569 case ISD::FMUL: 8570 case ISD::FCEIL: 8571 case ISD::FFLOOR: 8572 case ISD::FMA: 8573 case ISD::FMAD: 8574 case ISD::FSQRT: 8575 case ISD::FDIV: 8576 case ISD::FREM: 8577 case ISD::FP_ROUND: 8578 case ISD::FP_EXTEND: 8579 case AMDGPUISD::FMUL_LEGACY: 8580 case AMDGPUISD::FMAD_FTZ: 8581 case AMDGPUISD::RCP: 8582 case AMDGPUISD::RSQ: 8583 case AMDGPUISD::RSQ_CLAMP: 8584 case AMDGPUISD::RCP_LEGACY: 8585 case AMDGPUISD::RSQ_LEGACY: 8586 case AMDGPUISD::RCP_IFLAG: 8587 case AMDGPUISD::TRIG_PREOP: 8588 case AMDGPUISD::DIV_SCALE: 8589 case AMDGPUISD::DIV_FMAS: 8590 case AMDGPUISD::DIV_FIXUP: 8591 case AMDGPUISD::FRACT: 8592 case AMDGPUISD::LDEXP: 8593 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8594 case AMDGPUISD::CVT_F32_UBYTE0: 8595 case AMDGPUISD::CVT_F32_UBYTE1: 8596 case AMDGPUISD::CVT_F32_UBYTE2: 8597 case AMDGPUISD::CVT_F32_UBYTE3: 8598 return true; 8599 8600 // It can/will be lowered or combined as a bit operation. 8601 // Need to check their input recursively to handle. 8602 case ISD::FNEG: 8603 case ISD::FABS: 8604 case ISD::FCOPYSIGN: 8605 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8606 8607 case ISD::FSIN: 8608 case ISD::FCOS: 8609 case ISD::FSINCOS: 8610 return Op.getValueType().getScalarType() != MVT::f16; 8611 8612 case ISD::FMINNUM: 8613 case ISD::FMAXNUM: 8614 case ISD::FMINNUM_IEEE: 8615 case ISD::FMAXNUM_IEEE: 8616 case AMDGPUISD::CLAMP: 8617 case AMDGPUISD::FMED3: 8618 case AMDGPUISD::FMAX3: 8619 case AMDGPUISD::FMIN3: { 8620 // FIXME: Shouldn't treat the generic operations different based these. 8621 // However, we aren't really required to flush the result from 8622 // minnum/maxnum.. 8623 8624 // snans will be quieted, so we only need to worry about denormals. 8625 if (Subtarget->supportsMinMaxDenormModes() || 8626 denormalsEnabledForType(Op.getValueType())) 8627 return true; 8628 8629 // Flushing may be required. 8630 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8631 // targets need to check their input recursively. 8632 8633 // FIXME: Does this apply with clamp? It's implemented with max. 8634 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8635 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8636 return false; 8637 } 8638 8639 return true; 8640 } 8641 case ISD::SELECT: { 8642 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8643 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8644 } 8645 case ISD::BUILD_VECTOR: { 8646 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8647 SDValue SrcOp = Op.getOperand(i); 8648 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8649 return false; 8650 } 8651 8652 return true; 8653 } 8654 case ISD::EXTRACT_VECTOR_ELT: 8655 case ISD::EXTRACT_SUBVECTOR: { 8656 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8657 } 8658 case ISD::INSERT_VECTOR_ELT: { 8659 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8660 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8661 } 8662 case ISD::UNDEF: 8663 // Could be anything. 8664 return false; 8665 8666 case ISD::BITCAST: { 8667 // Hack round the mess we make when legalizing extract_vector_elt 8668 SDValue Src = Op.getOperand(0); 8669 if (Src.getValueType() == MVT::i16 && 8670 Src.getOpcode() == ISD::TRUNCATE) { 8671 SDValue TruncSrc = Src.getOperand(0); 8672 if (TruncSrc.getValueType() == MVT::i32 && 8673 TruncSrc.getOpcode() == ISD::BITCAST && 8674 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8675 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8676 } 8677 } 8678 8679 return false; 8680 } 8681 case ISD::INTRINSIC_WO_CHAIN: { 8682 unsigned IntrinsicID 8683 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8684 // TODO: Handle more intrinsics 8685 switch (IntrinsicID) { 8686 case Intrinsic::amdgcn_cvt_pkrtz: 8687 case Intrinsic::amdgcn_cubeid: 8688 case Intrinsic::amdgcn_frexp_mant: 8689 case Intrinsic::amdgcn_fdot2: 8690 return true; 8691 default: 8692 break; 8693 } 8694 8695 LLVM_FALLTHROUGH; 8696 } 8697 default: 8698 return denormalsEnabledForType(Op.getValueType()) && 8699 DAG.isKnownNeverSNaN(Op); 8700 } 8701 8702 llvm_unreachable("invalid operation"); 8703 } 8704 8705 // Constant fold canonicalize. 8706 SDValue SITargetLowering::getCanonicalConstantFP( 8707 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8708 // Flush denormals to 0 if not enabled. 8709 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8710 return DAG.getConstantFP(0.0, SL, VT); 8711 8712 if (C.isNaN()) { 8713 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8714 if (C.isSignaling()) { 8715 // Quiet a signaling NaN. 8716 // FIXME: Is this supposed to preserve payload bits? 8717 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8718 } 8719 8720 // Make sure it is the canonical NaN bitpattern. 8721 // 8722 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8723 // immediate? 8724 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8725 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8726 } 8727 8728 // Already canonical. 8729 return DAG.getConstantFP(C, SL, VT); 8730 } 8731 8732 static bool vectorEltWillFoldAway(SDValue Op) { 8733 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8734 } 8735 8736 SDValue SITargetLowering::performFCanonicalizeCombine( 8737 SDNode *N, 8738 DAGCombinerInfo &DCI) const { 8739 SelectionDAG &DAG = DCI.DAG; 8740 SDValue N0 = N->getOperand(0); 8741 EVT VT = N->getValueType(0); 8742 8743 // fcanonicalize undef -> qnan 8744 if (N0.isUndef()) { 8745 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8746 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8747 } 8748 8749 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8750 EVT VT = N->getValueType(0); 8751 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8752 } 8753 8754 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8755 // (fcanonicalize k) 8756 // 8757 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8758 8759 // TODO: This could be better with wider vectors that will be split to v2f16, 8760 // and to consider uses since there aren't that many packed operations. 8761 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8762 isTypeLegal(MVT::v2f16)) { 8763 SDLoc SL(N); 8764 SDValue NewElts[2]; 8765 SDValue Lo = N0.getOperand(0); 8766 SDValue Hi = N0.getOperand(1); 8767 EVT EltVT = Lo.getValueType(); 8768 8769 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8770 for (unsigned I = 0; I != 2; ++I) { 8771 SDValue Op = N0.getOperand(I); 8772 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8773 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8774 CFP->getValueAPF()); 8775 } else if (Op.isUndef()) { 8776 // Handled below based on what the other operand is. 8777 NewElts[I] = Op; 8778 } else { 8779 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8780 } 8781 } 8782 8783 // If one half is undef, and one is constant, perfer a splat vector rather 8784 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8785 // cheaper to use and may be free with a packed operation. 8786 if (NewElts[0].isUndef()) { 8787 if (isa<ConstantFPSDNode>(NewElts[1])) 8788 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8789 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8790 } 8791 8792 if (NewElts[1].isUndef()) { 8793 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8794 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8795 } 8796 8797 return DAG.getBuildVector(VT, SL, NewElts); 8798 } 8799 } 8800 8801 unsigned SrcOpc = N0.getOpcode(); 8802 8803 // If it's free to do so, push canonicalizes further up the source, which may 8804 // find a canonical source. 8805 // 8806 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8807 // sNaNs. 8808 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8809 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8810 if (CRHS && N0.hasOneUse()) { 8811 SDLoc SL(N); 8812 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8813 N0.getOperand(0)); 8814 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8815 DCI.AddToWorklist(Canon0.getNode()); 8816 8817 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8818 } 8819 } 8820 8821 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8822 } 8823 8824 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8825 switch (Opc) { 8826 case ISD::FMAXNUM: 8827 case ISD::FMAXNUM_IEEE: 8828 return AMDGPUISD::FMAX3; 8829 case ISD::SMAX: 8830 return AMDGPUISD::SMAX3; 8831 case ISD::UMAX: 8832 return AMDGPUISD::UMAX3; 8833 case ISD::FMINNUM: 8834 case ISD::FMINNUM_IEEE: 8835 return AMDGPUISD::FMIN3; 8836 case ISD::SMIN: 8837 return AMDGPUISD::SMIN3; 8838 case ISD::UMIN: 8839 return AMDGPUISD::UMIN3; 8840 default: 8841 llvm_unreachable("Not a min/max opcode"); 8842 } 8843 } 8844 8845 SDValue SITargetLowering::performIntMed3ImmCombine( 8846 SelectionDAG &DAG, const SDLoc &SL, 8847 SDValue Op0, SDValue Op1, bool Signed) const { 8848 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8849 if (!K1) 8850 return SDValue(); 8851 8852 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8853 if (!K0) 8854 return SDValue(); 8855 8856 if (Signed) { 8857 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8858 return SDValue(); 8859 } else { 8860 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8861 return SDValue(); 8862 } 8863 8864 EVT VT = K0->getValueType(0); 8865 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8866 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8867 return DAG.getNode(Med3Opc, SL, VT, 8868 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8869 } 8870 8871 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8872 MVT NVT = MVT::i32; 8873 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8874 8875 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8876 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8877 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8878 8879 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8880 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8881 } 8882 8883 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8884 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8885 return C; 8886 8887 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8888 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8889 return C; 8890 } 8891 8892 return nullptr; 8893 } 8894 8895 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8896 const SDLoc &SL, 8897 SDValue Op0, 8898 SDValue Op1) const { 8899 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8900 if (!K1) 8901 return SDValue(); 8902 8903 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8904 if (!K0) 8905 return SDValue(); 8906 8907 // Ordered >= (although NaN inputs should have folded away by now). 8908 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 8909 if (Cmp == APFloat::cmpGreaterThan) 8910 return SDValue(); 8911 8912 const MachineFunction &MF = DAG.getMachineFunction(); 8913 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8914 8915 // TODO: Check IEEE bit enabled? 8916 EVT VT = Op0.getValueType(); 8917 if (Info->getMode().DX10Clamp) { 8918 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 8919 // hardware fmed3 behavior converting to a min. 8920 // FIXME: Should this be allowing -0.0? 8921 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 8922 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 8923 } 8924 8925 // med3 for f16 is only available on gfx9+, and not available for v2f16. 8926 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 8927 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 8928 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 8929 // then give the other result, which is different from med3 with a NaN 8930 // input. 8931 SDValue Var = Op0.getOperand(0); 8932 if (!DAG.isKnownNeverSNaN(Var)) 8933 return SDValue(); 8934 8935 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8936 8937 if ((!K0->hasOneUse() || 8938 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 8939 (!K1->hasOneUse() || 8940 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 8941 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 8942 Var, SDValue(K0, 0), SDValue(K1, 0)); 8943 } 8944 } 8945 8946 return SDValue(); 8947 } 8948 8949 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 8950 DAGCombinerInfo &DCI) const { 8951 SelectionDAG &DAG = DCI.DAG; 8952 8953 EVT VT = N->getValueType(0); 8954 unsigned Opc = N->getOpcode(); 8955 SDValue Op0 = N->getOperand(0); 8956 SDValue Op1 = N->getOperand(1); 8957 8958 // Only do this if the inner op has one use since this will just increases 8959 // register pressure for no benefit. 8960 8961 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 8962 !VT.isVector() && 8963 (VT == MVT::i32 || VT == MVT::f32 || 8964 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 8965 // max(max(a, b), c) -> max3(a, b, c) 8966 // min(min(a, b), c) -> min3(a, b, c) 8967 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 8968 SDLoc DL(N); 8969 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8970 DL, 8971 N->getValueType(0), 8972 Op0.getOperand(0), 8973 Op0.getOperand(1), 8974 Op1); 8975 } 8976 8977 // Try commuted. 8978 // max(a, max(b, c)) -> max3(a, b, c) 8979 // min(a, min(b, c)) -> min3(a, b, c) 8980 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 8981 SDLoc DL(N); 8982 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8983 DL, 8984 N->getValueType(0), 8985 Op0, 8986 Op1.getOperand(0), 8987 Op1.getOperand(1)); 8988 } 8989 } 8990 8991 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 8992 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 8993 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 8994 return Med3; 8995 } 8996 8997 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 8998 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 8999 return Med3; 9000 } 9001 9002 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9003 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9004 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9005 (Opc == AMDGPUISD::FMIN_LEGACY && 9006 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9007 (VT == MVT::f32 || VT == MVT::f64 || 9008 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9009 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9010 Op0.hasOneUse()) { 9011 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9012 return Res; 9013 } 9014 9015 return SDValue(); 9016 } 9017 9018 static bool isClampZeroToOne(SDValue A, SDValue B) { 9019 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9020 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9021 // FIXME: Should this be allowing -0.0? 9022 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9023 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9024 } 9025 } 9026 9027 return false; 9028 } 9029 9030 // FIXME: Should only worry about snans for version with chain. 9031 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9032 DAGCombinerInfo &DCI) const { 9033 EVT VT = N->getValueType(0); 9034 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9035 // NaNs. With a NaN input, the order of the operands may change the result. 9036 9037 SelectionDAG &DAG = DCI.DAG; 9038 SDLoc SL(N); 9039 9040 SDValue Src0 = N->getOperand(0); 9041 SDValue Src1 = N->getOperand(1); 9042 SDValue Src2 = N->getOperand(2); 9043 9044 if (isClampZeroToOne(Src0, Src1)) { 9045 // const_a, const_b, x -> clamp is safe in all cases including signaling 9046 // nans. 9047 // FIXME: Should this be allowing -0.0? 9048 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9049 } 9050 9051 const MachineFunction &MF = DAG.getMachineFunction(); 9052 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9053 9054 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9055 // handling no dx10-clamp? 9056 if (Info->getMode().DX10Clamp) { 9057 // If NaNs is clamped to 0, we are free to reorder the inputs. 9058 9059 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9060 std::swap(Src0, Src1); 9061 9062 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9063 std::swap(Src1, Src2); 9064 9065 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9066 std::swap(Src0, Src1); 9067 9068 if (isClampZeroToOne(Src1, Src2)) 9069 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9070 } 9071 9072 return SDValue(); 9073 } 9074 9075 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9076 DAGCombinerInfo &DCI) const { 9077 SDValue Src0 = N->getOperand(0); 9078 SDValue Src1 = N->getOperand(1); 9079 if (Src0.isUndef() && Src1.isUndef()) 9080 return DCI.DAG.getUNDEF(N->getValueType(0)); 9081 return SDValue(); 9082 } 9083 9084 SDValue SITargetLowering::performExtractVectorEltCombine( 9085 SDNode *N, DAGCombinerInfo &DCI) const { 9086 SDValue Vec = N->getOperand(0); 9087 SelectionDAG &DAG = DCI.DAG; 9088 9089 EVT VecVT = Vec.getValueType(); 9090 EVT EltVT = VecVT.getVectorElementType(); 9091 9092 if ((Vec.getOpcode() == ISD::FNEG || 9093 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9094 SDLoc SL(N); 9095 EVT EltVT = N->getValueType(0); 9096 SDValue Idx = N->getOperand(1); 9097 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9098 Vec.getOperand(0), Idx); 9099 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9100 } 9101 9102 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9103 // => 9104 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9105 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9106 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9107 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9108 SDLoc SL(N); 9109 EVT EltVT = N->getValueType(0); 9110 SDValue Idx = N->getOperand(1); 9111 unsigned Opc = Vec.getOpcode(); 9112 9113 switch(Opc) { 9114 default: 9115 break; 9116 // TODO: Support other binary operations. 9117 case ISD::FADD: 9118 case ISD::FSUB: 9119 case ISD::FMUL: 9120 case ISD::ADD: 9121 case ISD::UMIN: 9122 case ISD::UMAX: 9123 case ISD::SMIN: 9124 case ISD::SMAX: 9125 case ISD::FMAXNUM: 9126 case ISD::FMINNUM: 9127 case ISD::FMAXNUM_IEEE: 9128 case ISD::FMINNUM_IEEE: { 9129 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9130 Vec.getOperand(0), Idx); 9131 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9132 Vec.getOperand(1), Idx); 9133 9134 DCI.AddToWorklist(Elt0.getNode()); 9135 DCI.AddToWorklist(Elt1.getNode()); 9136 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9137 } 9138 } 9139 } 9140 9141 unsigned VecSize = VecVT.getSizeInBits(); 9142 unsigned EltSize = EltVT.getSizeInBits(); 9143 9144 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9145 // This elminates non-constant index and subsequent movrel or scratch access. 9146 // Sub-dword vectors of size 2 dword or less have better implementation. 9147 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9148 // instructions. 9149 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9150 !isa<ConstantSDNode>(N->getOperand(1))) { 9151 SDLoc SL(N); 9152 SDValue Idx = N->getOperand(1); 9153 EVT IdxVT = Idx.getValueType(); 9154 SDValue V; 9155 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9156 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9157 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9158 if (I == 0) 9159 V = Elt; 9160 else 9161 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9162 } 9163 return V; 9164 } 9165 9166 if (!DCI.isBeforeLegalize()) 9167 return SDValue(); 9168 9169 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9170 // elements. This exposes more load reduction opportunities by replacing 9171 // multiple small extract_vector_elements with a single 32-bit extract. 9172 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9173 if (isa<MemSDNode>(Vec) && 9174 EltSize <= 16 && 9175 EltVT.isByteSized() && 9176 VecSize > 32 && 9177 VecSize % 32 == 0 && 9178 Idx) { 9179 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9180 9181 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9182 unsigned EltIdx = BitIndex / 32; 9183 unsigned LeftoverBitIdx = BitIndex % 32; 9184 SDLoc SL(N); 9185 9186 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9187 DCI.AddToWorklist(Cast.getNode()); 9188 9189 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9190 DAG.getConstant(EltIdx, SL, MVT::i32)); 9191 DCI.AddToWorklist(Elt.getNode()); 9192 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9193 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9194 DCI.AddToWorklist(Srl.getNode()); 9195 9196 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9197 DCI.AddToWorklist(Trunc.getNode()); 9198 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9199 } 9200 9201 return SDValue(); 9202 } 9203 9204 SDValue 9205 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9206 DAGCombinerInfo &DCI) const { 9207 SDValue Vec = N->getOperand(0); 9208 SDValue Idx = N->getOperand(2); 9209 EVT VecVT = Vec.getValueType(); 9210 EVT EltVT = VecVT.getVectorElementType(); 9211 unsigned VecSize = VecVT.getSizeInBits(); 9212 unsigned EltSize = EltVT.getSizeInBits(); 9213 9214 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9215 // => BUILD_VECTOR n x select (e, const-idx) 9216 // This elminates non-constant index and subsequent movrel or scratch access. 9217 // Sub-dword vectors of size 2 dword or less have better implementation. 9218 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9219 // instructions. 9220 if (isa<ConstantSDNode>(Idx) || 9221 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9222 return SDValue(); 9223 9224 SelectionDAG &DAG = DCI.DAG; 9225 SDLoc SL(N); 9226 SDValue Ins = N->getOperand(1); 9227 EVT IdxVT = Idx.getValueType(); 9228 9229 SmallVector<SDValue, 16> Ops; 9230 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9231 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9232 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9233 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9234 Ops.push_back(V); 9235 } 9236 9237 return DAG.getBuildVector(VecVT, SL, Ops); 9238 } 9239 9240 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9241 const SDNode *N0, 9242 const SDNode *N1) const { 9243 EVT VT = N0->getValueType(0); 9244 9245 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9246 // support denormals ever. 9247 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 9248 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() && 9249 getSubtarget()->hasMadF16())) && 9250 isOperationLegal(ISD::FMAD, VT)) 9251 return ISD::FMAD; 9252 9253 const TargetOptions &Options = DAG.getTarget().Options; 9254 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9255 (N0->getFlags().hasAllowContract() && 9256 N1->getFlags().hasAllowContract())) && 9257 isFMAFasterThanFMulAndFAdd(VT)) { 9258 return ISD::FMA; 9259 } 9260 9261 return 0; 9262 } 9263 9264 // For a reassociatable opcode perform: 9265 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9266 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9267 SelectionDAG &DAG) const { 9268 EVT VT = N->getValueType(0); 9269 if (VT != MVT::i32 && VT != MVT::i64) 9270 return SDValue(); 9271 9272 unsigned Opc = N->getOpcode(); 9273 SDValue Op0 = N->getOperand(0); 9274 SDValue Op1 = N->getOperand(1); 9275 9276 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9277 return SDValue(); 9278 9279 if (Op0->isDivergent()) 9280 std::swap(Op0, Op1); 9281 9282 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9283 return SDValue(); 9284 9285 SDValue Op2 = Op1.getOperand(1); 9286 Op1 = Op1.getOperand(0); 9287 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9288 return SDValue(); 9289 9290 if (Op1->isDivergent()) 9291 std::swap(Op1, Op2); 9292 9293 // If either operand is constant this will conflict with 9294 // DAGCombiner::ReassociateOps(). 9295 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9296 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9297 return SDValue(); 9298 9299 SDLoc SL(N); 9300 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9301 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9302 } 9303 9304 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9305 EVT VT, 9306 SDValue N0, SDValue N1, SDValue N2, 9307 bool Signed) { 9308 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9309 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9310 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9311 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9312 } 9313 9314 SDValue SITargetLowering::performAddCombine(SDNode *N, 9315 DAGCombinerInfo &DCI) const { 9316 SelectionDAG &DAG = DCI.DAG; 9317 EVT VT = N->getValueType(0); 9318 SDLoc SL(N); 9319 SDValue LHS = N->getOperand(0); 9320 SDValue RHS = N->getOperand(1); 9321 9322 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9323 && Subtarget->hasMad64_32() && 9324 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9325 VT.getScalarSizeInBits() <= 64) { 9326 if (LHS.getOpcode() != ISD::MUL) 9327 std::swap(LHS, RHS); 9328 9329 SDValue MulLHS = LHS.getOperand(0); 9330 SDValue MulRHS = LHS.getOperand(1); 9331 SDValue AddRHS = RHS; 9332 9333 // TODO: Maybe restrict if SGPR inputs. 9334 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9335 numBitsUnsigned(MulRHS, DAG) <= 32) { 9336 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9337 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9338 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9339 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9340 } 9341 9342 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9343 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9344 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9345 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9346 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9347 } 9348 9349 return SDValue(); 9350 } 9351 9352 if (SDValue V = reassociateScalarOps(N, DAG)) { 9353 return V; 9354 } 9355 9356 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9357 return SDValue(); 9358 9359 // add x, zext (setcc) => addcarry x, 0, setcc 9360 // add x, sext (setcc) => subcarry x, 0, setcc 9361 unsigned Opc = LHS.getOpcode(); 9362 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9363 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9364 std::swap(RHS, LHS); 9365 9366 Opc = RHS.getOpcode(); 9367 switch (Opc) { 9368 default: break; 9369 case ISD::ZERO_EXTEND: 9370 case ISD::SIGN_EXTEND: 9371 case ISD::ANY_EXTEND: { 9372 auto Cond = RHS.getOperand(0); 9373 if (!isBoolSGPR(Cond)) 9374 break; 9375 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9376 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9377 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9378 return DAG.getNode(Opc, SL, VTList, Args); 9379 } 9380 case ISD::ADDCARRY: { 9381 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9382 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9383 if (!C || C->getZExtValue() != 0) break; 9384 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9385 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9386 } 9387 } 9388 return SDValue(); 9389 } 9390 9391 SDValue SITargetLowering::performSubCombine(SDNode *N, 9392 DAGCombinerInfo &DCI) const { 9393 SelectionDAG &DAG = DCI.DAG; 9394 EVT VT = N->getValueType(0); 9395 9396 if (VT != MVT::i32) 9397 return SDValue(); 9398 9399 SDLoc SL(N); 9400 SDValue LHS = N->getOperand(0); 9401 SDValue RHS = N->getOperand(1); 9402 9403 if (LHS.getOpcode() == ISD::SUBCARRY) { 9404 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9405 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9406 if (!C || !C->isNullValue()) 9407 return SDValue(); 9408 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9409 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9410 } 9411 return SDValue(); 9412 } 9413 9414 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9415 DAGCombinerInfo &DCI) const { 9416 9417 if (N->getValueType(0) != MVT::i32) 9418 return SDValue(); 9419 9420 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9421 if (!C || C->getZExtValue() != 0) 9422 return SDValue(); 9423 9424 SelectionDAG &DAG = DCI.DAG; 9425 SDValue LHS = N->getOperand(0); 9426 9427 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9428 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9429 unsigned LHSOpc = LHS.getOpcode(); 9430 unsigned Opc = N->getOpcode(); 9431 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9432 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9433 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9434 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9435 } 9436 return SDValue(); 9437 } 9438 9439 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9440 DAGCombinerInfo &DCI) const { 9441 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9442 return SDValue(); 9443 9444 SelectionDAG &DAG = DCI.DAG; 9445 EVT VT = N->getValueType(0); 9446 9447 SDLoc SL(N); 9448 SDValue LHS = N->getOperand(0); 9449 SDValue RHS = N->getOperand(1); 9450 9451 // These should really be instruction patterns, but writing patterns with 9452 // source modiifiers is a pain. 9453 9454 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9455 if (LHS.getOpcode() == ISD::FADD) { 9456 SDValue A = LHS.getOperand(0); 9457 if (A == LHS.getOperand(1)) { 9458 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9459 if (FusedOp != 0) { 9460 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9461 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9462 } 9463 } 9464 } 9465 9466 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9467 if (RHS.getOpcode() == ISD::FADD) { 9468 SDValue A = RHS.getOperand(0); 9469 if (A == RHS.getOperand(1)) { 9470 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9471 if (FusedOp != 0) { 9472 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9473 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9474 } 9475 } 9476 } 9477 9478 return SDValue(); 9479 } 9480 9481 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9482 DAGCombinerInfo &DCI) const { 9483 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9484 return SDValue(); 9485 9486 SelectionDAG &DAG = DCI.DAG; 9487 SDLoc SL(N); 9488 EVT VT = N->getValueType(0); 9489 assert(!VT.isVector()); 9490 9491 // Try to get the fneg to fold into the source modifier. This undoes generic 9492 // DAG combines and folds them into the mad. 9493 // 9494 // Only do this if we are not trying to support denormals. v_mad_f32 does 9495 // not support denormals ever. 9496 SDValue LHS = N->getOperand(0); 9497 SDValue RHS = N->getOperand(1); 9498 if (LHS.getOpcode() == ISD::FADD) { 9499 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9500 SDValue A = LHS.getOperand(0); 9501 if (A == LHS.getOperand(1)) { 9502 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9503 if (FusedOp != 0){ 9504 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9505 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9506 9507 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9508 } 9509 } 9510 } 9511 9512 if (RHS.getOpcode() == ISD::FADD) { 9513 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9514 9515 SDValue A = RHS.getOperand(0); 9516 if (A == RHS.getOperand(1)) { 9517 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9518 if (FusedOp != 0){ 9519 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9520 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9521 } 9522 } 9523 } 9524 9525 return SDValue(); 9526 } 9527 9528 SDValue SITargetLowering::performFMACombine(SDNode *N, 9529 DAGCombinerInfo &DCI) const { 9530 SelectionDAG &DAG = DCI.DAG; 9531 EVT VT = N->getValueType(0); 9532 SDLoc SL(N); 9533 9534 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9535 return SDValue(); 9536 9537 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9538 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9539 SDValue Op1 = N->getOperand(0); 9540 SDValue Op2 = N->getOperand(1); 9541 SDValue FMA = N->getOperand(2); 9542 9543 if (FMA.getOpcode() != ISD::FMA || 9544 Op1.getOpcode() != ISD::FP_EXTEND || 9545 Op2.getOpcode() != ISD::FP_EXTEND) 9546 return SDValue(); 9547 9548 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9549 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9550 // is sufficient to allow generaing fdot2. 9551 const TargetOptions &Options = DAG.getTarget().Options; 9552 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9553 (N->getFlags().hasAllowContract() && 9554 FMA->getFlags().hasAllowContract())) { 9555 Op1 = Op1.getOperand(0); 9556 Op2 = Op2.getOperand(0); 9557 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9558 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9559 return SDValue(); 9560 9561 SDValue Vec1 = Op1.getOperand(0); 9562 SDValue Idx1 = Op1.getOperand(1); 9563 SDValue Vec2 = Op2.getOperand(0); 9564 9565 SDValue FMAOp1 = FMA.getOperand(0); 9566 SDValue FMAOp2 = FMA.getOperand(1); 9567 SDValue FMAAcc = FMA.getOperand(2); 9568 9569 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9570 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9571 return SDValue(); 9572 9573 FMAOp1 = FMAOp1.getOperand(0); 9574 FMAOp2 = FMAOp2.getOperand(0); 9575 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9576 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9577 return SDValue(); 9578 9579 SDValue Vec3 = FMAOp1.getOperand(0); 9580 SDValue Vec4 = FMAOp2.getOperand(0); 9581 SDValue Idx2 = FMAOp1.getOperand(1); 9582 9583 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9584 // Idx1 and Idx2 cannot be the same. 9585 Idx1 == Idx2) 9586 return SDValue(); 9587 9588 if (Vec1 == Vec2 || Vec3 == Vec4) 9589 return SDValue(); 9590 9591 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9592 return SDValue(); 9593 9594 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9595 (Vec1 == Vec4 && Vec2 == Vec3)) { 9596 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9597 DAG.getTargetConstant(0, SL, MVT::i1)); 9598 } 9599 } 9600 return SDValue(); 9601 } 9602 9603 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9604 DAGCombinerInfo &DCI) const { 9605 SelectionDAG &DAG = DCI.DAG; 9606 SDLoc SL(N); 9607 9608 SDValue LHS = N->getOperand(0); 9609 SDValue RHS = N->getOperand(1); 9610 EVT VT = LHS.getValueType(); 9611 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9612 9613 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9614 if (!CRHS) { 9615 CRHS = dyn_cast<ConstantSDNode>(LHS); 9616 if (CRHS) { 9617 std::swap(LHS, RHS); 9618 CC = getSetCCSwappedOperands(CC); 9619 } 9620 } 9621 9622 if (CRHS) { 9623 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9624 isBoolSGPR(LHS.getOperand(0))) { 9625 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9626 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9627 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9628 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9629 if ((CRHS->isAllOnesValue() && 9630 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9631 (CRHS->isNullValue() && 9632 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9633 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9634 DAG.getConstant(-1, SL, MVT::i1)); 9635 if ((CRHS->isAllOnesValue() && 9636 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9637 (CRHS->isNullValue() && 9638 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9639 return LHS.getOperand(0); 9640 } 9641 9642 uint64_t CRHSVal = CRHS->getZExtValue(); 9643 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9644 LHS.getOpcode() == ISD::SELECT && 9645 isa<ConstantSDNode>(LHS.getOperand(1)) && 9646 isa<ConstantSDNode>(LHS.getOperand(2)) && 9647 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9648 isBoolSGPR(LHS.getOperand(0))) { 9649 // Given CT != FT: 9650 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9651 // setcc (select cc, CT, CF), CF, ne => cc 9652 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9653 // setcc (select cc, CT, CF), CT, eq => cc 9654 uint64_t CT = LHS.getConstantOperandVal(1); 9655 uint64_t CF = LHS.getConstantOperandVal(2); 9656 9657 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9658 (CT == CRHSVal && CC == ISD::SETNE)) 9659 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9660 DAG.getConstant(-1, SL, MVT::i1)); 9661 if ((CF == CRHSVal && CC == ISD::SETNE) || 9662 (CT == CRHSVal && CC == ISD::SETEQ)) 9663 return LHS.getOperand(0); 9664 } 9665 } 9666 9667 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9668 VT != MVT::f16)) 9669 return SDValue(); 9670 9671 // Match isinf/isfinite pattern 9672 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9673 // (fcmp one (fabs x), inf) -> (fp_class x, 9674 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9675 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9676 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9677 if (!CRHS) 9678 return SDValue(); 9679 9680 const APFloat &APF = CRHS->getValueAPF(); 9681 if (APF.isInfinity() && !APF.isNegative()) { 9682 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9683 SIInstrFlags::N_INFINITY; 9684 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9685 SIInstrFlags::P_ZERO | 9686 SIInstrFlags::N_NORMAL | 9687 SIInstrFlags::P_NORMAL | 9688 SIInstrFlags::N_SUBNORMAL | 9689 SIInstrFlags::P_SUBNORMAL; 9690 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9691 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9692 DAG.getConstant(Mask, SL, MVT::i32)); 9693 } 9694 } 9695 9696 return SDValue(); 9697 } 9698 9699 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9700 DAGCombinerInfo &DCI) const { 9701 SelectionDAG &DAG = DCI.DAG; 9702 SDLoc SL(N); 9703 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9704 9705 SDValue Src = N->getOperand(0); 9706 SDValue Srl = N->getOperand(0); 9707 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9708 Srl = Srl.getOperand(0); 9709 9710 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9711 if (Srl.getOpcode() == ISD::SRL) { 9712 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9713 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9714 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9715 9716 if (const ConstantSDNode *C = 9717 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9718 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9719 EVT(MVT::i32)); 9720 9721 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9722 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9723 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9724 MVT::f32, Srl); 9725 } 9726 } 9727 } 9728 9729 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9730 9731 KnownBits Known; 9732 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9733 !DCI.isBeforeLegalizeOps()); 9734 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9735 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9736 DCI.CommitTargetLoweringOpt(TLO); 9737 } 9738 9739 return SDValue(); 9740 } 9741 9742 SDValue SITargetLowering::performClampCombine(SDNode *N, 9743 DAGCombinerInfo &DCI) const { 9744 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9745 if (!CSrc) 9746 return SDValue(); 9747 9748 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9749 const APFloat &F = CSrc->getValueAPF(); 9750 APFloat Zero = APFloat::getZero(F.getSemantics()); 9751 APFloat::cmpResult Cmp0 = F.compare(Zero); 9752 if (Cmp0 == APFloat::cmpLessThan || 9753 (Cmp0 == APFloat::cmpUnordered && 9754 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9755 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9756 } 9757 9758 APFloat One(F.getSemantics(), "1.0"); 9759 APFloat::cmpResult Cmp1 = F.compare(One); 9760 if (Cmp1 == APFloat::cmpGreaterThan) 9761 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9762 9763 return SDValue(CSrc, 0); 9764 } 9765 9766 9767 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9768 DAGCombinerInfo &DCI) const { 9769 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9770 return SDValue(); 9771 switch (N->getOpcode()) { 9772 default: 9773 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9774 case ISD::ADD: 9775 return performAddCombine(N, DCI); 9776 case ISD::SUB: 9777 return performSubCombine(N, DCI); 9778 case ISD::ADDCARRY: 9779 case ISD::SUBCARRY: 9780 return performAddCarrySubCarryCombine(N, DCI); 9781 case ISD::FADD: 9782 return performFAddCombine(N, DCI); 9783 case ISD::FSUB: 9784 return performFSubCombine(N, DCI); 9785 case ISD::SETCC: 9786 return performSetCCCombine(N, DCI); 9787 case ISD::FMAXNUM: 9788 case ISD::FMINNUM: 9789 case ISD::FMAXNUM_IEEE: 9790 case ISD::FMINNUM_IEEE: 9791 case ISD::SMAX: 9792 case ISD::SMIN: 9793 case ISD::UMAX: 9794 case ISD::UMIN: 9795 case AMDGPUISD::FMIN_LEGACY: 9796 case AMDGPUISD::FMAX_LEGACY: 9797 return performMinMaxCombine(N, DCI); 9798 case ISD::FMA: 9799 return performFMACombine(N, DCI); 9800 case ISD::LOAD: { 9801 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9802 return Widended; 9803 LLVM_FALLTHROUGH; 9804 } 9805 case ISD::STORE: 9806 case ISD::ATOMIC_LOAD: 9807 case ISD::ATOMIC_STORE: 9808 case ISD::ATOMIC_CMP_SWAP: 9809 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9810 case ISD::ATOMIC_SWAP: 9811 case ISD::ATOMIC_LOAD_ADD: 9812 case ISD::ATOMIC_LOAD_SUB: 9813 case ISD::ATOMIC_LOAD_AND: 9814 case ISD::ATOMIC_LOAD_OR: 9815 case ISD::ATOMIC_LOAD_XOR: 9816 case ISD::ATOMIC_LOAD_NAND: 9817 case ISD::ATOMIC_LOAD_MIN: 9818 case ISD::ATOMIC_LOAD_MAX: 9819 case ISD::ATOMIC_LOAD_UMIN: 9820 case ISD::ATOMIC_LOAD_UMAX: 9821 case ISD::ATOMIC_LOAD_FADD: 9822 case AMDGPUISD::ATOMIC_INC: 9823 case AMDGPUISD::ATOMIC_DEC: 9824 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9825 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9826 if (DCI.isBeforeLegalize()) 9827 break; 9828 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9829 case ISD::AND: 9830 return performAndCombine(N, DCI); 9831 case ISD::OR: 9832 return performOrCombine(N, DCI); 9833 case ISD::XOR: 9834 return performXorCombine(N, DCI); 9835 case ISD::ZERO_EXTEND: 9836 return performZeroExtendCombine(N, DCI); 9837 case ISD::SIGN_EXTEND_INREG: 9838 return performSignExtendInRegCombine(N , DCI); 9839 case AMDGPUISD::FP_CLASS: 9840 return performClassCombine(N, DCI); 9841 case ISD::FCANONICALIZE: 9842 return performFCanonicalizeCombine(N, DCI); 9843 case AMDGPUISD::RCP: 9844 return performRcpCombine(N, DCI); 9845 case AMDGPUISD::FRACT: 9846 case AMDGPUISD::RSQ: 9847 case AMDGPUISD::RCP_LEGACY: 9848 case AMDGPUISD::RSQ_LEGACY: 9849 case AMDGPUISD::RCP_IFLAG: 9850 case AMDGPUISD::RSQ_CLAMP: 9851 case AMDGPUISD::LDEXP: { 9852 SDValue Src = N->getOperand(0); 9853 if (Src.isUndef()) 9854 return Src; 9855 break; 9856 } 9857 case ISD::SINT_TO_FP: 9858 case ISD::UINT_TO_FP: 9859 return performUCharToFloatCombine(N, DCI); 9860 case AMDGPUISD::CVT_F32_UBYTE0: 9861 case AMDGPUISD::CVT_F32_UBYTE1: 9862 case AMDGPUISD::CVT_F32_UBYTE2: 9863 case AMDGPUISD::CVT_F32_UBYTE3: 9864 return performCvtF32UByteNCombine(N, DCI); 9865 case AMDGPUISD::FMED3: 9866 return performFMed3Combine(N, DCI); 9867 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9868 return performCvtPkRTZCombine(N, DCI); 9869 case AMDGPUISD::CLAMP: 9870 return performClampCombine(N, DCI); 9871 case ISD::SCALAR_TO_VECTOR: { 9872 SelectionDAG &DAG = DCI.DAG; 9873 EVT VT = N->getValueType(0); 9874 9875 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9876 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9877 SDLoc SL(N); 9878 SDValue Src = N->getOperand(0); 9879 EVT EltVT = Src.getValueType(); 9880 if (EltVT == MVT::f16) 9881 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 9882 9883 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 9884 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 9885 } 9886 9887 break; 9888 } 9889 case ISD::EXTRACT_VECTOR_ELT: 9890 return performExtractVectorEltCombine(N, DCI); 9891 case ISD::INSERT_VECTOR_ELT: 9892 return performInsertVectorEltCombine(N, DCI); 9893 } 9894 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9895 } 9896 9897 /// Helper function for adjustWritemask 9898 static unsigned SubIdx2Lane(unsigned Idx) { 9899 switch (Idx) { 9900 default: return 0; 9901 case AMDGPU::sub0: return 0; 9902 case AMDGPU::sub1: return 1; 9903 case AMDGPU::sub2: return 2; 9904 case AMDGPU::sub3: return 3; 9905 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 9906 } 9907 } 9908 9909 /// Adjust the writemask of MIMG instructions 9910 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 9911 SelectionDAG &DAG) const { 9912 unsigned Opcode = Node->getMachineOpcode(); 9913 9914 // Subtract 1 because the vdata output is not a MachineSDNode operand. 9915 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 9916 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 9917 return Node; // not implemented for D16 9918 9919 SDNode *Users[5] = { nullptr }; 9920 unsigned Lane = 0; 9921 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 9922 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 9923 unsigned NewDmask = 0; 9924 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 9925 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 9926 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 9927 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 9928 unsigned TFCLane = 0; 9929 bool HasChain = Node->getNumValues() > 1; 9930 9931 if (OldDmask == 0) { 9932 // These are folded out, but on the chance it happens don't assert. 9933 return Node; 9934 } 9935 9936 unsigned OldBitsSet = countPopulation(OldDmask); 9937 // Work out which is the TFE/LWE lane if that is enabled. 9938 if (UsesTFC) { 9939 TFCLane = OldBitsSet; 9940 } 9941 9942 // Try to figure out the used register components 9943 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 9944 I != E; ++I) { 9945 9946 // Don't look at users of the chain. 9947 if (I.getUse().getResNo() != 0) 9948 continue; 9949 9950 // Abort if we can't understand the usage 9951 if (!I->isMachineOpcode() || 9952 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 9953 return Node; 9954 9955 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 9956 // Note that subregs are packed, i.e. Lane==0 is the first bit set 9957 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 9958 // set, etc. 9959 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 9960 9961 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 9962 if (UsesTFC && Lane == TFCLane) { 9963 Users[Lane] = *I; 9964 } else { 9965 // Set which texture component corresponds to the lane. 9966 unsigned Comp; 9967 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 9968 Comp = countTrailingZeros(Dmask); 9969 Dmask &= ~(1 << Comp); 9970 } 9971 9972 // Abort if we have more than one user per component. 9973 if (Users[Lane]) 9974 return Node; 9975 9976 Users[Lane] = *I; 9977 NewDmask |= 1 << Comp; 9978 } 9979 } 9980 9981 // Don't allow 0 dmask, as hardware assumes one channel enabled. 9982 bool NoChannels = !NewDmask; 9983 if (NoChannels) { 9984 if (!UsesTFC) { 9985 // No uses of the result and not using TFC. Then do nothing. 9986 return Node; 9987 } 9988 // If the original dmask has one channel - then nothing to do 9989 if (OldBitsSet == 1) 9990 return Node; 9991 // Use an arbitrary dmask - required for the instruction to work 9992 NewDmask = 1; 9993 } 9994 // Abort if there's no change 9995 if (NewDmask == OldDmask) 9996 return Node; 9997 9998 unsigned BitsSet = countPopulation(NewDmask); 9999 10000 // Check for TFE or LWE - increase the number of channels by one to account 10001 // for the extra return value 10002 // This will need adjustment for D16 if this is also included in 10003 // adjustWriteMask (this function) but at present D16 are excluded. 10004 unsigned NewChannels = BitsSet + UsesTFC; 10005 10006 int NewOpcode = 10007 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10008 assert(NewOpcode != -1 && 10009 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10010 "failed to find equivalent MIMG op"); 10011 10012 // Adjust the writemask in the node 10013 SmallVector<SDValue, 12> Ops; 10014 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10015 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10016 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10017 10018 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10019 10020 MVT ResultVT = NewChannels == 1 ? 10021 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10022 NewChannels == 5 ? 8 : NewChannels); 10023 SDVTList NewVTList = HasChain ? 10024 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10025 10026 10027 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10028 NewVTList, Ops); 10029 10030 if (HasChain) { 10031 // Update chain. 10032 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10033 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10034 } 10035 10036 if (NewChannels == 1) { 10037 assert(Node->hasNUsesOfValue(1, 0)); 10038 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10039 SDLoc(Node), Users[Lane]->getValueType(0), 10040 SDValue(NewNode, 0)); 10041 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10042 return nullptr; 10043 } 10044 10045 // Update the users of the node with the new indices 10046 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10047 SDNode *User = Users[i]; 10048 if (!User) { 10049 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10050 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10051 if (i || !NoChannels) 10052 continue; 10053 } else { 10054 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10055 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10056 } 10057 10058 switch (Idx) { 10059 default: break; 10060 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10061 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10062 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10063 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10064 } 10065 } 10066 10067 DAG.RemoveDeadNode(Node); 10068 return nullptr; 10069 } 10070 10071 static bool isFrameIndexOp(SDValue Op) { 10072 if (Op.getOpcode() == ISD::AssertZext) 10073 Op = Op.getOperand(0); 10074 10075 return isa<FrameIndexSDNode>(Op); 10076 } 10077 10078 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10079 /// with frame index operands. 10080 /// LLVM assumes that inputs are to these instructions are registers. 10081 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10082 SelectionDAG &DAG) const { 10083 if (Node->getOpcode() == ISD::CopyToReg) { 10084 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10085 SDValue SrcVal = Node->getOperand(2); 10086 10087 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10088 // to try understanding copies to physical registers. 10089 if (SrcVal.getValueType() == MVT::i1 && 10090 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 10091 SDLoc SL(Node); 10092 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10093 SDValue VReg = DAG.getRegister( 10094 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10095 10096 SDNode *Glued = Node->getGluedNode(); 10097 SDValue ToVReg 10098 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10099 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10100 SDValue ToResultReg 10101 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10102 VReg, ToVReg.getValue(1)); 10103 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10104 DAG.RemoveDeadNode(Node); 10105 return ToResultReg.getNode(); 10106 } 10107 } 10108 10109 SmallVector<SDValue, 8> Ops; 10110 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10111 if (!isFrameIndexOp(Node->getOperand(i))) { 10112 Ops.push_back(Node->getOperand(i)); 10113 continue; 10114 } 10115 10116 SDLoc DL(Node); 10117 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10118 Node->getOperand(i).getValueType(), 10119 Node->getOperand(i)), 0)); 10120 } 10121 10122 return DAG.UpdateNodeOperands(Node, Ops); 10123 } 10124 10125 /// Fold the instructions after selecting them. 10126 /// Returns null if users were already updated. 10127 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10128 SelectionDAG &DAG) const { 10129 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10130 unsigned Opcode = Node->getMachineOpcode(); 10131 10132 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10133 !TII->isGather4(Opcode)) { 10134 return adjustWritemask(Node, DAG); 10135 } 10136 10137 if (Opcode == AMDGPU::INSERT_SUBREG || 10138 Opcode == AMDGPU::REG_SEQUENCE) { 10139 legalizeTargetIndependentNode(Node, DAG); 10140 return Node; 10141 } 10142 10143 switch (Opcode) { 10144 case AMDGPU::V_DIV_SCALE_F32: 10145 case AMDGPU::V_DIV_SCALE_F64: { 10146 // Satisfy the operand register constraint when one of the inputs is 10147 // undefined. Ordinarily each undef value will have its own implicit_def of 10148 // a vreg, so force these to use a single register. 10149 SDValue Src0 = Node->getOperand(0); 10150 SDValue Src1 = Node->getOperand(1); 10151 SDValue Src2 = Node->getOperand(2); 10152 10153 if ((Src0.isMachineOpcode() && 10154 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10155 (Src0 == Src1 || Src0 == Src2)) 10156 break; 10157 10158 MVT VT = Src0.getValueType().getSimpleVT(); 10159 const TargetRegisterClass *RC = 10160 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10161 10162 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10163 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10164 10165 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10166 UndefReg, Src0, SDValue()); 10167 10168 // src0 must be the same register as src1 or src2, even if the value is 10169 // undefined, so make sure we don't violate this constraint. 10170 if (Src0.isMachineOpcode() && 10171 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10172 if (Src1.isMachineOpcode() && 10173 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10174 Src0 = Src1; 10175 else if (Src2.isMachineOpcode() && 10176 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10177 Src0 = Src2; 10178 else { 10179 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10180 Src0 = UndefReg; 10181 Src1 = UndefReg; 10182 } 10183 } else 10184 break; 10185 10186 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10187 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10188 Ops.push_back(Node->getOperand(I)); 10189 10190 Ops.push_back(ImpDef.getValue(1)); 10191 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10192 } 10193 case AMDGPU::V_PERMLANE16_B32: 10194 case AMDGPU::V_PERMLANEX16_B32: { 10195 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10196 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10197 if (!FI->getZExtValue() && !BC->getZExtValue()) 10198 break; 10199 SDValue VDstIn = Node->getOperand(6); 10200 if (VDstIn.isMachineOpcode() 10201 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10202 break; 10203 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10204 SDLoc(Node), MVT::i32); 10205 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10206 SDValue(BC, 0), Node->getOperand(3), 10207 Node->getOperand(4), Node->getOperand(5), 10208 SDValue(ImpDef, 0), Node->getOperand(7) }; 10209 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10210 } 10211 default: 10212 break; 10213 } 10214 10215 return Node; 10216 } 10217 10218 /// Assign the register class depending on the number of 10219 /// bits set in the writemask 10220 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10221 SDNode *Node) const { 10222 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10223 10224 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10225 10226 if (TII->isVOP3(MI.getOpcode())) { 10227 // Make sure constant bus requirements are respected. 10228 TII->legalizeOperandsVOP3(MRI, MI); 10229 10230 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10231 // This saves a chain-copy of registers and better ballance register 10232 // use between vgpr and agpr as agpr tuples tend to be big. 10233 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10234 unsigned Opc = MI.getOpcode(); 10235 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10236 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10237 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10238 if (I == -1) 10239 break; 10240 MachineOperand &Op = MI.getOperand(I); 10241 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10242 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10243 !TargetRegisterInfo::isVirtualRegister(Op.getReg()) || 10244 !TRI->isAGPR(MRI, Op.getReg())) 10245 continue; 10246 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10247 if (!Src || !Src->isCopy() || 10248 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10249 continue; 10250 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10251 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10252 // All uses of agpr64 and agpr32 can also accept vgpr except for 10253 // v_accvgpr_read, but we do not produce agpr reads during selection, 10254 // so no use checks are needed. 10255 MRI.setRegClass(Op.getReg(), NewRC); 10256 } 10257 } 10258 10259 return; 10260 } 10261 10262 // Replace unused atomics with the no return version. 10263 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10264 if (NoRetAtomicOp != -1) { 10265 if (!Node->hasAnyUseOfValue(0)) { 10266 MI.setDesc(TII->get(NoRetAtomicOp)); 10267 MI.RemoveOperand(0); 10268 return; 10269 } 10270 10271 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10272 // instruction, because the return type of these instructions is a vec2 of 10273 // the memory type, so it can be tied to the input operand. 10274 // This means these instructions always have a use, so we need to add a 10275 // special case to check if the atomic has only one extract_subreg use, 10276 // which itself has no uses. 10277 if ((Node->hasNUsesOfValue(1, 0) && 10278 Node->use_begin()->isMachineOpcode() && 10279 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10280 !Node->use_begin()->hasAnyUseOfValue(0))) { 10281 unsigned Def = MI.getOperand(0).getReg(); 10282 10283 // Change this into a noret atomic. 10284 MI.setDesc(TII->get(NoRetAtomicOp)); 10285 MI.RemoveOperand(0); 10286 10287 // If we only remove the def operand from the atomic instruction, the 10288 // extract_subreg will be left with a use of a vreg without a def. 10289 // So we need to insert an implicit_def to avoid machine verifier 10290 // errors. 10291 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10292 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10293 } 10294 return; 10295 } 10296 } 10297 10298 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10299 uint64_t Val) { 10300 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10301 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10302 } 10303 10304 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10305 const SDLoc &DL, 10306 SDValue Ptr) const { 10307 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10308 10309 // Build the half of the subregister with the constants before building the 10310 // full 128-bit register. If we are building multiple resource descriptors, 10311 // this will allow CSEing of the 2-component register. 10312 const SDValue Ops0[] = { 10313 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10314 buildSMovImm32(DAG, DL, 0), 10315 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10316 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10317 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10318 }; 10319 10320 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10321 MVT::v2i32, Ops0), 0); 10322 10323 // Combine the constants and the pointer. 10324 const SDValue Ops1[] = { 10325 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10326 Ptr, 10327 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10328 SubRegHi, 10329 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10330 }; 10331 10332 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10333 } 10334 10335 /// Return a resource descriptor with the 'Add TID' bit enabled 10336 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10337 /// of the resource descriptor) to create an offset, which is added to 10338 /// the resource pointer. 10339 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10340 SDValue Ptr, uint32_t RsrcDword1, 10341 uint64_t RsrcDword2And3) const { 10342 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10343 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10344 if (RsrcDword1) { 10345 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10346 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10347 0); 10348 } 10349 10350 SDValue DataLo = buildSMovImm32(DAG, DL, 10351 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10352 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10353 10354 const SDValue Ops[] = { 10355 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10356 PtrLo, 10357 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10358 PtrHi, 10359 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10360 DataLo, 10361 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10362 DataHi, 10363 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10364 }; 10365 10366 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10367 } 10368 10369 //===----------------------------------------------------------------------===// 10370 // SI Inline Assembly Support 10371 //===----------------------------------------------------------------------===// 10372 10373 std::pair<unsigned, const TargetRegisterClass *> 10374 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10375 StringRef Constraint, 10376 MVT VT) const { 10377 const TargetRegisterClass *RC = nullptr; 10378 if (Constraint.size() == 1) { 10379 switch (Constraint[0]) { 10380 default: 10381 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10382 case 's': 10383 case 'r': 10384 switch (VT.getSizeInBits()) { 10385 default: 10386 return std::make_pair(0U, nullptr); 10387 case 32: 10388 case 16: 10389 RC = &AMDGPU::SReg_32_XM0RegClass; 10390 break; 10391 case 64: 10392 RC = &AMDGPU::SGPR_64RegClass; 10393 break; 10394 case 96: 10395 RC = &AMDGPU::SReg_96RegClass; 10396 break; 10397 case 128: 10398 RC = &AMDGPU::SReg_128RegClass; 10399 break; 10400 case 160: 10401 RC = &AMDGPU::SReg_160RegClass; 10402 break; 10403 case 256: 10404 RC = &AMDGPU::SReg_256RegClass; 10405 break; 10406 case 512: 10407 RC = &AMDGPU::SReg_512RegClass; 10408 break; 10409 } 10410 break; 10411 case 'v': 10412 switch (VT.getSizeInBits()) { 10413 default: 10414 return std::make_pair(0U, nullptr); 10415 case 32: 10416 case 16: 10417 RC = &AMDGPU::VGPR_32RegClass; 10418 break; 10419 case 64: 10420 RC = &AMDGPU::VReg_64RegClass; 10421 break; 10422 case 96: 10423 RC = &AMDGPU::VReg_96RegClass; 10424 break; 10425 case 128: 10426 RC = &AMDGPU::VReg_128RegClass; 10427 break; 10428 case 160: 10429 RC = &AMDGPU::VReg_160RegClass; 10430 break; 10431 case 256: 10432 RC = &AMDGPU::VReg_256RegClass; 10433 break; 10434 case 512: 10435 RC = &AMDGPU::VReg_512RegClass; 10436 break; 10437 } 10438 break; 10439 case 'a': 10440 switch (VT.getSizeInBits()) { 10441 default: 10442 return std::make_pair(0U, nullptr); 10443 case 32: 10444 case 16: 10445 RC = &AMDGPU::AGPR_32RegClass; 10446 break; 10447 case 64: 10448 RC = &AMDGPU::AReg_64RegClass; 10449 break; 10450 case 128: 10451 RC = &AMDGPU::AReg_128RegClass; 10452 break; 10453 case 512: 10454 RC = &AMDGPU::AReg_512RegClass; 10455 break; 10456 case 1024: 10457 RC = &AMDGPU::AReg_1024RegClass; 10458 // v32 types are not legal but we support them here. 10459 return std::make_pair(0U, RC); 10460 } 10461 break; 10462 } 10463 // We actually support i128, i16 and f16 as inline parameters 10464 // even if they are not reported as legal 10465 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10466 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10467 return std::make_pair(0U, RC); 10468 } 10469 10470 if (Constraint.size() > 1) { 10471 if (Constraint[1] == 'v') { 10472 RC = &AMDGPU::VGPR_32RegClass; 10473 } else if (Constraint[1] == 's') { 10474 RC = &AMDGPU::SGPR_32RegClass; 10475 } else if (Constraint[1] == 'a') { 10476 RC = &AMDGPU::AGPR_32RegClass; 10477 } 10478 10479 if (RC) { 10480 uint32_t Idx; 10481 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10482 if (!Failed && Idx < RC->getNumRegs()) 10483 return std::make_pair(RC->getRegister(Idx), RC); 10484 } 10485 } 10486 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10487 } 10488 10489 SITargetLowering::ConstraintType 10490 SITargetLowering::getConstraintType(StringRef Constraint) const { 10491 if (Constraint.size() == 1) { 10492 switch (Constraint[0]) { 10493 default: break; 10494 case 's': 10495 case 'v': 10496 case 'a': 10497 return C_RegisterClass; 10498 } 10499 } 10500 return TargetLowering::getConstraintType(Constraint); 10501 } 10502 10503 // Figure out which registers should be reserved for stack access. Only after 10504 // the function is legalized do we know all of the non-spill stack objects or if 10505 // calls are present. 10506 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10507 MachineRegisterInfo &MRI = MF.getRegInfo(); 10508 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10509 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10510 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10511 10512 if (Info->isEntryFunction()) { 10513 // Callable functions have fixed registers used for stack access. 10514 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10515 } 10516 10517 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10518 Info->getStackPtrOffsetReg())); 10519 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10520 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10521 10522 // We need to worry about replacing the default register with itself in case 10523 // of MIR testcases missing the MFI. 10524 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10525 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10526 10527 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10528 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10529 10530 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10531 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10532 Info->getScratchWaveOffsetReg()); 10533 } 10534 10535 Info->limitOccupancy(MF); 10536 10537 if (ST.isWave32() && !MF.empty()) { 10538 // Add VCC_HI def because many instructions marked as imp-use VCC where 10539 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10540 // having a use of undef. 10541 10542 const SIInstrInfo *TII = ST.getInstrInfo(); 10543 DebugLoc DL; 10544 10545 MachineBasicBlock &MBB = MF.front(); 10546 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10547 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10548 10549 for (auto &MBB : MF) { 10550 for (auto &MI : MBB) { 10551 TII->fixImplicitOperands(MI); 10552 } 10553 } 10554 } 10555 10556 TargetLoweringBase::finalizeLowering(MF); 10557 } 10558 10559 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10560 KnownBits &Known, 10561 const APInt &DemandedElts, 10562 const SelectionDAG &DAG, 10563 unsigned Depth) const { 10564 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10565 DAG, Depth); 10566 10567 // Set the high bits to zero based on the maximum allowed scratch size per 10568 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10569 // calculation won't overflow, so assume the sign bit is never set. 10570 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10571 } 10572 10573 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10574 const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10575 const unsigned CacheLineAlign = 6; // log2(64) 10576 10577 // Pre-GFX10 target did not benefit from loop alignment 10578 if (!ML || DisableLoopAlignment || 10579 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10580 getSubtarget()->hasInstFwdPrefetchBug()) 10581 return PrefAlign; 10582 10583 // On GFX10 I$ is 4 x 64 bytes cache lines. 10584 // By default prefetcher keeps one cache line behind and reads two ahead. 10585 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10586 // behind and one ahead. 10587 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10588 // If loop fits 64 bytes it always spans no more than two cache lines and 10589 // does not need an alignment. 10590 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10591 // Else if loop is less or equal 192 bytes we need two lines behind. 10592 10593 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10594 const MachineBasicBlock *Header = ML->getHeader(); 10595 if (Header->getAlignment() != PrefAlign) 10596 return Header->getAlignment(); // Already processed. 10597 10598 unsigned LoopSize = 0; 10599 for (const MachineBasicBlock *MBB : ML->blocks()) { 10600 // If inner loop block is aligned assume in average half of the alignment 10601 // size to be added as nops. 10602 if (MBB != Header) 10603 LoopSize += (1 << MBB->getAlignment()) / 2; 10604 10605 for (const MachineInstr &MI : *MBB) { 10606 LoopSize += TII->getInstSizeInBytes(MI); 10607 if (LoopSize > 192) 10608 return PrefAlign; 10609 } 10610 } 10611 10612 if (LoopSize <= 64) 10613 return PrefAlign; 10614 10615 if (LoopSize <= 128) 10616 return CacheLineAlign; 10617 10618 // If any of parent loops is surrounded by prefetch instructions do not 10619 // insert new for inner loop, which would reset parent's settings. 10620 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10621 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10622 auto I = Exit->getFirstNonDebugInstr(); 10623 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10624 return CacheLineAlign; 10625 } 10626 } 10627 10628 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10629 MachineBasicBlock *Exit = ML->getExitBlock(); 10630 10631 if (Pre && Exit) { 10632 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10633 TII->get(AMDGPU::S_INST_PREFETCH)) 10634 .addImm(1); // prefetch 2 lines behind PC 10635 10636 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10637 TII->get(AMDGPU::S_INST_PREFETCH)) 10638 .addImm(2); // prefetch 1 line behind PC 10639 } 10640 10641 return CacheLineAlign; 10642 } 10643 10644 LLVM_ATTRIBUTE_UNUSED 10645 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10646 assert(N->getOpcode() == ISD::CopyFromReg); 10647 do { 10648 // Follow the chain until we find an INLINEASM node. 10649 N = N->getOperand(0).getNode(); 10650 if (N->getOpcode() == ISD::INLINEASM || 10651 N->getOpcode() == ISD::INLINEASM_BR) 10652 return true; 10653 } while (N->getOpcode() == ISD::CopyFromReg); 10654 return false; 10655 } 10656 10657 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10658 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10659 { 10660 switch (N->getOpcode()) { 10661 case ISD::CopyFromReg: 10662 { 10663 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10664 const MachineFunction * MF = FLI->MF; 10665 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10666 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10667 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10668 unsigned Reg = R->getReg(); 10669 if (TRI.isPhysicalRegister(Reg)) 10670 return !TRI.isSGPRReg(MRI, Reg); 10671 10672 if (MRI.isLiveIn(Reg)) { 10673 // workitem.id.x workitem.id.y workitem.id.z 10674 // Any VGPR formal argument is also considered divergent 10675 if (!TRI.isSGPRReg(MRI, Reg)) 10676 return true; 10677 // Formal arguments of non-entry functions 10678 // are conservatively considered divergent 10679 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10680 return true; 10681 return false; 10682 } 10683 const Value *V = FLI->getValueFromVirtualReg(Reg); 10684 if (V) 10685 return KDA->isDivergent(V); 10686 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10687 return !TRI.isSGPRReg(MRI, Reg); 10688 } 10689 break; 10690 case ISD::LOAD: { 10691 const LoadSDNode *L = cast<LoadSDNode>(N); 10692 unsigned AS = L->getAddressSpace(); 10693 // A flat load may access private memory. 10694 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10695 } break; 10696 case ISD::CALLSEQ_END: 10697 return true; 10698 break; 10699 case ISD::INTRINSIC_WO_CHAIN: 10700 { 10701 10702 } 10703 return AMDGPU::isIntrinsicSourceOfDivergence( 10704 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10705 case ISD::INTRINSIC_W_CHAIN: 10706 return AMDGPU::isIntrinsicSourceOfDivergence( 10707 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10708 // In some cases intrinsics that are a source of divergence have been 10709 // lowered to AMDGPUISD so we also need to check those too. 10710 case AMDGPUISD::INTERP_MOV: 10711 case AMDGPUISD::INTERP_P1: 10712 case AMDGPUISD::INTERP_P2: 10713 return true; 10714 } 10715 return false; 10716 } 10717 10718 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 10719 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10720 case MVT::f32: 10721 return Subtarget->hasFP32Denormals(); 10722 case MVT::f64: 10723 return Subtarget->hasFP64Denormals(); 10724 case MVT::f16: 10725 return Subtarget->hasFP16Denormals(); 10726 default: 10727 return false; 10728 } 10729 } 10730 10731 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10732 const SelectionDAG &DAG, 10733 bool SNaN, 10734 unsigned Depth) const { 10735 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10736 const MachineFunction &MF = DAG.getMachineFunction(); 10737 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10738 10739 if (Info->getMode().DX10Clamp) 10740 return true; // Clamped to 0. 10741 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10742 } 10743 10744 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10745 SNaN, Depth); 10746 } 10747 10748 TargetLowering::AtomicExpansionKind 10749 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10750 switch (RMW->getOperation()) { 10751 case AtomicRMWInst::FAdd: { 10752 Type *Ty = RMW->getType(); 10753 10754 // We don't have a way to support 16-bit atomics now, so just leave them 10755 // as-is. 10756 if (Ty->isHalfTy()) 10757 return AtomicExpansionKind::None; 10758 10759 if (!Ty->isFloatTy()) 10760 return AtomicExpansionKind::CmpXChg; 10761 10762 // TODO: Do have these for flat. Older targets also had them for buffers. 10763 unsigned AS = RMW->getPointerAddressSpace(); 10764 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10765 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10766 } 10767 default: 10768 break; 10769 } 10770 10771 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10772 } 10773