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::AReg_1024RegClass); 156 } 157 158 computeRegisterProperties(Subtarget->getRegisterInfo()); 159 160 // We need to custom lower vector stores from local memory 161 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 162 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 163 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 164 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 165 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 166 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 167 setOperationAction(ISD::LOAD, MVT::i1, Custom); 168 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 169 170 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 171 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 172 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 173 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 174 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 175 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 176 setOperationAction(ISD::STORE, MVT::i1, Custom); 177 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 178 179 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 180 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 181 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 182 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 183 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 184 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 185 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 186 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 187 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 188 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 189 190 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 191 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 192 193 setOperationAction(ISD::SELECT, MVT::i1, Promote); 194 setOperationAction(ISD::SELECT, MVT::i64, Custom); 195 setOperationAction(ISD::SELECT, MVT::f64, Promote); 196 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 197 198 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 199 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 200 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 201 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 202 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 203 204 setOperationAction(ISD::SETCC, MVT::i1, Promote); 205 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 206 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 207 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 208 209 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 210 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 211 212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 219 220 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 221 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 222 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 223 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 224 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 225 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 226 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 227 228 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 229 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 230 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 231 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 232 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 233 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 234 235 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 236 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 237 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 238 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 239 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 240 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 241 242 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 243 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 244 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 245 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 246 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 247 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 248 249 setOperationAction(ISD::UADDO, MVT::i32, Legal); 250 setOperationAction(ISD::USUBO, MVT::i32, Legal); 251 252 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 253 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 254 255 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 256 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 257 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 258 259 #if 0 260 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 261 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 262 #endif 263 264 // We only support LOAD/STORE and vector manipulation ops for vectors 265 // with > 4 elements. 266 for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 267 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) { 268 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 269 switch (Op) { 270 case ISD::LOAD: 271 case ISD::STORE: 272 case ISD::BUILD_VECTOR: 273 case ISD::BITCAST: 274 case ISD::EXTRACT_VECTOR_ELT: 275 case ISD::INSERT_VECTOR_ELT: 276 case ISD::INSERT_SUBVECTOR: 277 case ISD::EXTRACT_SUBVECTOR: 278 case ISD::SCALAR_TO_VECTOR: 279 break; 280 case ISD::CONCAT_VECTORS: 281 setOperationAction(Op, VT, Custom); 282 break; 283 default: 284 setOperationAction(Op, VT, Expand); 285 break; 286 } 287 } 288 } 289 290 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 291 292 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 293 // is expanded to avoid having two separate loops in case the index is a VGPR. 294 295 // Most operations are naturally 32-bit vector operations. We only support 296 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 297 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 298 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 299 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 300 301 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 302 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 303 304 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 305 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 306 307 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 308 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 309 } 310 311 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 312 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 313 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 314 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 315 316 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 317 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 318 319 // Avoid stack access for these. 320 // TODO: Generalize to more vector types. 321 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 322 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 323 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 324 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 325 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 327 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 328 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 330 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 331 332 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 333 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 335 336 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 338 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 339 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 340 341 // Deal with vec3 vector operations when widened to vec4. 342 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 343 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 346 347 // Deal with vec5 vector operations when widened to vec8. 348 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 349 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 350 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 351 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 352 353 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 354 // and output demarshalling 355 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 356 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 357 358 // We can't return success/failure, only the old value, 359 // let LLVM add the comparison 360 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 361 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 362 363 if (Subtarget->hasFlatAddressSpace()) { 364 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 365 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 366 } 367 368 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 369 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 370 371 // On SI this is s_memtime and s_memrealtime on VI. 372 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 373 setOperationAction(ISD::TRAP, MVT::Other, Custom); 374 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 375 376 if (Subtarget->has16BitInsts()) { 377 setOperationAction(ISD::FLOG, MVT::f16, Custom); 378 setOperationAction(ISD::FEXP, MVT::f16, Custom); 379 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 380 } 381 382 // v_mad_f32 does not support denormals according to some sources. 383 if (!Subtarget->hasFP32Denormals()) 384 setOperationAction(ISD::FMAD, MVT::f32, Legal); 385 386 if (!Subtarget->hasBFI()) { 387 // fcopysign can be done in a single instruction with BFI. 388 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 389 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 390 } 391 392 if (!Subtarget->hasBCNT(32)) 393 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 394 395 if (!Subtarget->hasBCNT(64)) 396 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 397 398 if (Subtarget->hasFFBH()) 399 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 400 401 if (Subtarget->hasFFBL()) 402 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 403 404 // We only really have 32-bit BFE instructions (and 16-bit on VI). 405 // 406 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 407 // effort to match them now. We want this to be false for i64 cases when the 408 // extraction isn't restricted to the upper or lower half. Ideally we would 409 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 410 // span the midpoint are probably relatively rare, so don't worry about them 411 // for now. 412 if (Subtarget->hasBFE()) 413 setHasExtractBitsInsn(true); 414 415 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 416 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 417 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 418 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 419 420 421 // These are really only legal for ieee_mode functions. We should be avoiding 422 // them for functions that don't have ieee_mode enabled, so just say they are 423 // legal. 424 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 425 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 426 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 427 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 428 429 430 if (Subtarget->haveRoundOpsF64()) { 431 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 432 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 433 setOperationAction(ISD::FRINT, MVT::f64, Legal); 434 } else { 435 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 436 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 437 setOperationAction(ISD::FRINT, MVT::f64, Custom); 438 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 439 } 440 441 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 442 443 setOperationAction(ISD::FSIN, MVT::f32, Custom); 444 setOperationAction(ISD::FCOS, MVT::f32, Custom); 445 setOperationAction(ISD::FDIV, MVT::f32, Custom); 446 setOperationAction(ISD::FDIV, MVT::f64, Custom); 447 448 if (Subtarget->has16BitInsts()) { 449 setOperationAction(ISD::Constant, MVT::i16, Legal); 450 451 setOperationAction(ISD::SMIN, MVT::i16, Legal); 452 setOperationAction(ISD::SMAX, MVT::i16, Legal); 453 454 setOperationAction(ISD::UMIN, MVT::i16, Legal); 455 setOperationAction(ISD::UMAX, MVT::i16, Legal); 456 457 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 458 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 459 460 setOperationAction(ISD::ROTR, MVT::i16, Promote); 461 setOperationAction(ISD::ROTL, MVT::i16, Promote); 462 463 setOperationAction(ISD::SDIV, MVT::i16, Promote); 464 setOperationAction(ISD::UDIV, MVT::i16, Promote); 465 setOperationAction(ISD::SREM, MVT::i16, Promote); 466 setOperationAction(ISD::UREM, MVT::i16, Promote); 467 468 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 469 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 470 471 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 472 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 473 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 474 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 475 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 476 477 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 478 479 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 480 481 setOperationAction(ISD::LOAD, MVT::i16, Custom); 482 483 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 484 485 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 486 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 487 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 488 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 489 490 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 491 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 492 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 493 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 494 495 // F16 - Constant Actions. 496 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 497 498 // F16 - Load/Store Actions. 499 setOperationAction(ISD::LOAD, MVT::f16, Promote); 500 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 501 setOperationAction(ISD::STORE, MVT::f16, Promote); 502 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 503 504 // F16 - VOP1 Actions. 505 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 506 setOperationAction(ISD::FCOS, MVT::f16, Promote); 507 setOperationAction(ISD::FSIN, MVT::f16, Promote); 508 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 509 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 510 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 511 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 512 setOperationAction(ISD::FROUND, MVT::f16, Custom); 513 514 // F16 - VOP2 Actions. 515 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 516 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 517 518 setOperationAction(ISD::FDIV, MVT::f16, Custom); 519 520 // F16 - VOP3 Actions. 521 setOperationAction(ISD::FMA, MVT::f16, Legal); 522 if (!Subtarget->hasFP16Denormals() && STI.hasMadF16()) 523 setOperationAction(ISD::FMAD, MVT::f16, Legal); 524 525 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 526 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 527 switch (Op) { 528 case ISD::LOAD: 529 case ISD::STORE: 530 case ISD::BUILD_VECTOR: 531 case ISD::BITCAST: 532 case ISD::EXTRACT_VECTOR_ELT: 533 case ISD::INSERT_VECTOR_ELT: 534 case ISD::INSERT_SUBVECTOR: 535 case ISD::EXTRACT_SUBVECTOR: 536 case ISD::SCALAR_TO_VECTOR: 537 break; 538 case ISD::CONCAT_VECTORS: 539 setOperationAction(Op, VT, Custom); 540 break; 541 default: 542 setOperationAction(Op, VT, Expand); 543 break; 544 } 545 } 546 } 547 548 // XXX - Do these do anything? Vector constants turn into build_vector. 549 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 550 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 551 552 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 553 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 554 555 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 556 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 557 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 558 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 559 560 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 561 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 562 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 563 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 564 565 setOperationAction(ISD::AND, MVT::v2i16, Promote); 566 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 567 setOperationAction(ISD::OR, MVT::v2i16, Promote); 568 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 569 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 571 572 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 573 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 574 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 575 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 576 577 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 578 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 579 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 580 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 581 582 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 583 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 584 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 585 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 586 587 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 588 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 589 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 590 591 if (!Subtarget->hasVOP3PInsts()) { 592 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 593 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 594 } 595 596 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 597 // This isn't really legal, but this avoids the legalizer unrolling it (and 598 // allows matching fneg (fabs x) patterns) 599 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 600 601 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 602 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 603 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 604 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 605 606 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 607 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 608 609 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 610 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 611 } 612 613 if (Subtarget->hasVOP3PInsts()) { 614 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 615 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 616 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 617 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 618 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 619 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 620 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 621 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 622 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 623 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 624 625 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 626 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 627 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 628 629 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 630 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 631 632 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 633 634 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 635 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 636 637 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 638 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 639 640 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 641 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 642 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 643 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 644 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 645 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 646 647 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 648 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 649 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 650 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 651 652 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 653 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 654 655 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 656 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 657 658 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 659 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 660 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 661 662 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 663 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 664 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 665 } 666 667 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 668 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 669 670 if (Subtarget->has16BitInsts()) { 671 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 672 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 673 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 674 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 675 } else { 676 // Legalization hack. 677 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 678 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 679 680 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 681 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 682 } 683 684 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 685 setOperationAction(ISD::SELECT, VT, Custom); 686 } 687 688 setTargetDAGCombine(ISD::ADD); 689 setTargetDAGCombine(ISD::ADDCARRY); 690 setTargetDAGCombine(ISD::SUB); 691 setTargetDAGCombine(ISD::SUBCARRY); 692 setTargetDAGCombine(ISD::FADD); 693 setTargetDAGCombine(ISD::FSUB); 694 setTargetDAGCombine(ISD::FMINNUM); 695 setTargetDAGCombine(ISD::FMAXNUM); 696 setTargetDAGCombine(ISD::FMINNUM_IEEE); 697 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 698 setTargetDAGCombine(ISD::FMA); 699 setTargetDAGCombine(ISD::SMIN); 700 setTargetDAGCombine(ISD::SMAX); 701 setTargetDAGCombine(ISD::UMIN); 702 setTargetDAGCombine(ISD::UMAX); 703 setTargetDAGCombine(ISD::SETCC); 704 setTargetDAGCombine(ISD::AND); 705 setTargetDAGCombine(ISD::OR); 706 setTargetDAGCombine(ISD::XOR); 707 setTargetDAGCombine(ISD::SINT_TO_FP); 708 setTargetDAGCombine(ISD::UINT_TO_FP); 709 setTargetDAGCombine(ISD::FCANONICALIZE); 710 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 711 setTargetDAGCombine(ISD::ZERO_EXTEND); 712 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 713 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 714 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 715 716 // All memory operations. Some folding on the pointer operand is done to help 717 // matching the constant offsets in the addressing modes. 718 setTargetDAGCombine(ISD::LOAD); 719 setTargetDAGCombine(ISD::STORE); 720 setTargetDAGCombine(ISD::ATOMIC_LOAD); 721 setTargetDAGCombine(ISD::ATOMIC_STORE); 722 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 723 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 724 setTargetDAGCombine(ISD::ATOMIC_SWAP); 725 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 726 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 727 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 728 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 729 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 730 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 731 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 732 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 733 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 734 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 735 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 736 737 setSchedulingPreference(Sched::RegPressure); 738 } 739 740 const GCNSubtarget *SITargetLowering::getSubtarget() const { 741 return Subtarget; 742 } 743 744 //===----------------------------------------------------------------------===// 745 // TargetLowering queries 746 //===----------------------------------------------------------------------===// 747 748 // v_mad_mix* support a conversion from f16 to f32. 749 // 750 // There is only one special case when denormals are enabled we don't currently, 751 // where this is OK to use. 752 bool SITargetLowering::isFPExtFoldable(unsigned Opcode, 753 EVT DestVT, EVT SrcVT) const { 754 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 755 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 756 DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() && 757 SrcVT.getScalarType() == MVT::f16; 758 } 759 760 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 761 // SI has some legal vector types, but no legal vector operations. Say no 762 // shuffles are legal in order to prefer scalarizing some vector operations. 763 return false; 764 } 765 766 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 767 CallingConv::ID CC, 768 EVT VT) const { 769 // TODO: Consider splitting all arguments into 32-bit pieces. 770 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 771 EVT ScalarVT = VT.getScalarType(); 772 unsigned Size = ScalarVT.getSizeInBits(); 773 if (Size == 32) 774 return ScalarVT.getSimpleVT(); 775 776 if (Size == 64) 777 return MVT::i32; 778 779 if (Size == 16 && Subtarget->has16BitInsts()) 780 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 781 } 782 783 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 784 } 785 786 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 787 CallingConv::ID CC, 788 EVT VT) const { 789 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 790 unsigned NumElts = VT.getVectorNumElements(); 791 EVT ScalarVT = VT.getScalarType(); 792 unsigned Size = ScalarVT.getSizeInBits(); 793 794 if (Size == 32) 795 return NumElts; 796 797 if (Size == 64) 798 return 2 * NumElts; 799 800 if (Size == 16 && Subtarget->has16BitInsts()) 801 return (VT.getVectorNumElements() + 1) / 2; 802 } 803 804 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 805 } 806 807 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 808 LLVMContext &Context, CallingConv::ID CC, 809 EVT VT, EVT &IntermediateVT, 810 unsigned &NumIntermediates, MVT &RegisterVT) const { 811 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 812 unsigned NumElts = VT.getVectorNumElements(); 813 EVT ScalarVT = VT.getScalarType(); 814 unsigned Size = ScalarVT.getSizeInBits(); 815 if (Size == 32) { 816 RegisterVT = ScalarVT.getSimpleVT(); 817 IntermediateVT = RegisterVT; 818 NumIntermediates = NumElts; 819 return NumIntermediates; 820 } 821 822 if (Size == 64) { 823 RegisterVT = MVT::i32; 824 IntermediateVT = RegisterVT; 825 NumIntermediates = 2 * NumElts; 826 return NumIntermediates; 827 } 828 829 // FIXME: We should fix the ABI to be the same on targets without 16-bit 830 // support, but unless we can properly handle 3-vectors, it will be still be 831 // inconsistent. 832 if (Size == 16 && Subtarget->has16BitInsts()) { 833 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 834 IntermediateVT = RegisterVT; 835 NumIntermediates = (NumElts + 1) / 2; 836 return NumIntermediates; 837 } 838 } 839 840 return TargetLowering::getVectorTypeBreakdownForCallingConv( 841 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 842 } 843 844 static MVT memVTFromAggregate(Type *Ty) { 845 // Only limited forms of aggregate type currently expected. 846 assert(Ty->isStructTy() && "Expected struct type"); 847 848 849 Type *ElementType = nullptr; 850 unsigned NumElts; 851 if (Ty->getContainedType(0)->isVectorTy()) { 852 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 853 ElementType = VecComponent->getElementType(); 854 NumElts = VecComponent->getNumElements(); 855 } else { 856 ElementType = Ty->getContainedType(0); 857 NumElts = 1; 858 } 859 860 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 861 862 // Calculate the size of the memVT type from the aggregate 863 unsigned Pow2Elts = 0; 864 unsigned ElementSize; 865 switch (ElementType->getTypeID()) { 866 default: 867 llvm_unreachable("Unknown type!"); 868 case Type::IntegerTyID: 869 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 870 break; 871 case Type::HalfTyID: 872 ElementSize = 16; 873 break; 874 case Type::FloatTyID: 875 ElementSize = 32; 876 break; 877 } 878 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 879 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 880 881 return MVT::getVectorVT(MVT::getVT(ElementType, false), 882 Pow2Elts); 883 } 884 885 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 886 const CallInst &CI, 887 MachineFunction &MF, 888 unsigned IntrID) const { 889 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 890 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 891 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 892 (Intrinsic::ID)IntrID); 893 if (Attr.hasFnAttribute(Attribute::ReadNone)) 894 return false; 895 896 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 897 898 if (RsrcIntr->IsImage) { 899 Info.ptrVal = MFI->getImagePSV( 900 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 901 CI.getArgOperand(RsrcIntr->RsrcArg)); 902 Info.align = 0; 903 } else { 904 Info.ptrVal = MFI->getBufferPSV( 905 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 906 CI.getArgOperand(RsrcIntr->RsrcArg)); 907 } 908 909 Info.flags = MachineMemOperand::MODereferenceable; 910 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 911 Info.opc = ISD::INTRINSIC_W_CHAIN; 912 Info.memVT = MVT::getVT(CI.getType(), true); 913 if (Info.memVT == MVT::Other) { 914 // Some intrinsics return an aggregate type - special case to work out 915 // the correct memVT 916 Info.memVT = memVTFromAggregate(CI.getType()); 917 } 918 Info.flags |= MachineMemOperand::MOLoad; 919 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 920 Info.opc = ISD::INTRINSIC_VOID; 921 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 922 Info.flags |= MachineMemOperand::MOStore; 923 } else { 924 // Atomic 925 Info.opc = ISD::INTRINSIC_W_CHAIN; 926 Info.memVT = MVT::getVT(CI.getType()); 927 Info.flags = MachineMemOperand::MOLoad | 928 MachineMemOperand::MOStore | 929 MachineMemOperand::MODereferenceable; 930 931 // XXX - Should this be volatile without known ordering? 932 Info.flags |= MachineMemOperand::MOVolatile; 933 } 934 return true; 935 } 936 937 switch (IntrID) { 938 case Intrinsic::amdgcn_atomic_inc: 939 case Intrinsic::amdgcn_atomic_dec: 940 case Intrinsic::amdgcn_ds_ordered_add: 941 case Intrinsic::amdgcn_ds_ordered_swap: 942 case Intrinsic::amdgcn_ds_fadd: 943 case Intrinsic::amdgcn_ds_fmin: 944 case Intrinsic::amdgcn_ds_fmax: { 945 Info.opc = ISD::INTRINSIC_W_CHAIN; 946 Info.memVT = MVT::getVT(CI.getType()); 947 Info.ptrVal = CI.getOperand(0); 948 Info.align = 0; 949 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 950 951 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 952 if (!Vol->isZero()) 953 Info.flags |= MachineMemOperand::MOVolatile; 954 955 return true; 956 } 957 case Intrinsic::amdgcn_buffer_atomic_fadd: { 958 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 959 960 Info.opc = ISD::INTRINSIC_VOID; 961 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 962 Info.ptrVal = MFI->getBufferPSV( 963 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 964 CI.getArgOperand(1)); 965 Info.align = 0; 966 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 967 968 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 969 if (!Vol || !Vol->isZero()) 970 Info.flags |= MachineMemOperand::MOVolatile; 971 972 return true; 973 } 974 case Intrinsic::amdgcn_global_atomic_fadd: { 975 Info.opc = ISD::INTRINSIC_VOID; 976 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 977 ->getPointerElementType()); 978 Info.ptrVal = CI.getOperand(0); 979 Info.align = 0; 980 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 981 982 return true; 983 } 984 case Intrinsic::amdgcn_ds_append: 985 case Intrinsic::amdgcn_ds_consume: { 986 Info.opc = ISD::INTRINSIC_W_CHAIN; 987 Info.memVT = MVT::getVT(CI.getType()); 988 Info.ptrVal = CI.getOperand(0); 989 Info.align = 0; 990 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 991 992 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 993 if (!Vol->isZero()) 994 Info.flags |= MachineMemOperand::MOVolatile; 995 996 return true; 997 } 998 case Intrinsic::amdgcn_ds_gws_init: 999 case Intrinsic::amdgcn_ds_gws_barrier: 1000 case Intrinsic::amdgcn_ds_gws_sema_v: 1001 case Intrinsic::amdgcn_ds_gws_sema_br: 1002 case Intrinsic::amdgcn_ds_gws_sema_p: 1003 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1004 Info.opc = ISD::INTRINSIC_VOID; 1005 1006 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1007 Info.ptrVal = 1008 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1009 1010 // This is an abstract access, but we need to specify a type and size. 1011 Info.memVT = MVT::i32; 1012 Info.size = 4; 1013 Info.align = 4; 1014 1015 Info.flags = MachineMemOperand::MOStore; 1016 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1017 Info.flags = MachineMemOperand::MOLoad; 1018 return true; 1019 } 1020 default: 1021 return false; 1022 } 1023 } 1024 1025 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1026 SmallVectorImpl<Value*> &Ops, 1027 Type *&AccessTy) const { 1028 switch (II->getIntrinsicID()) { 1029 case Intrinsic::amdgcn_atomic_inc: 1030 case Intrinsic::amdgcn_atomic_dec: 1031 case Intrinsic::amdgcn_ds_ordered_add: 1032 case Intrinsic::amdgcn_ds_ordered_swap: 1033 case Intrinsic::amdgcn_ds_fadd: 1034 case Intrinsic::amdgcn_ds_fmin: 1035 case Intrinsic::amdgcn_ds_fmax: { 1036 Value *Ptr = II->getArgOperand(0); 1037 AccessTy = II->getType(); 1038 Ops.push_back(Ptr); 1039 return true; 1040 } 1041 default: 1042 return false; 1043 } 1044 } 1045 1046 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1047 if (!Subtarget->hasFlatInstOffsets()) { 1048 // Flat instructions do not have offsets, and only have the register 1049 // address. 1050 return AM.BaseOffs == 0 && AM.Scale == 0; 1051 } 1052 1053 // GFX9 added a 13-bit signed offset. When using regular flat instructions, 1054 // the sign bit is ignored and is treated as a 12-bit unsigned offset. 1055 1056 // GFX10 shrinked signed offset to 12 bits. When using regular flat 1057 // instructions, the sign bit is also ignored and is treated as 11-bit 1058 // unsigned offset. 1059 1060 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 1061 return isUInt<11>(AM.BaseOffs) && AM.Scale == 0; 1062 1063 // Just r + i 1064 return isUInt<12>(AM.BaseOffs) && AM.Scale == 0; 1065 } 1066 1067 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1068 if (Subtarget->hasFlatGlobalInsts()) 1069 return isInt<13>(AM.BaseOffs) && AM.Scale == 0; 1070 1071 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1072 // Assume the we will use FLAT for all global memory accesses 1073 // on VI. 1074 // FIXME: This assumption is currently wrong. On VI we still use 1075 // MUBUF instructions for the r + i addressing mode. As currently 1076 // implemented, the MUBUF instructions only work on buffer < 4GB. 1077 // It may be possible to support > 4GB buffers with MUBUF instructions, 1078 // by setting the stride value in the resource descriptor which would 1079 // increase the size limit to (stride * 4GB). However, this is risky, 1080 // because it has never been validated. 1081 return isLegalFlatAddressingMode(AM); 1082 } 1083 1084 return isLegalMUBUFAddressingMode(AM); 1085 } 1086 1087 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1088 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1089 // additionally can do r + r + i with addr64. 32-bit has more addressing 1090 // mode options. Depending on the resource constant, it can also do 1091 // (i64 r0) + (i32 r1) * (i14 i). 1092 // 1093 // Private arrays end up using a scratch buffer most of the time, so also 1094 // assume those use MUBUF instructions. Scratch loads / stores are currently 1095 // implemented as mubuf instructions with offen bit set, so slightly 1096 // different than the normal addr64. 1097 if (!isUInt<12>(AM.BaseOffs)) 1098 return false; 1099 1100 // FIXME: Since we can split immediate into soffset and immediate offset, 1101 // would it make sense to allow any immediate? 1102 1103 switch (AM.Scale) { 1104 case 0: // r + i or just i, depending on HasBaseReg. 1105 return true; 1106 case 1: 1107 return true; // We have r + r or r + i. 1108 case 2: 1109 if (AM.HasBaseReg) { 1110 // Reject 2 * r + r. 1111 return false; 1112 } 1113 1114 // Allow 2 * r as r + r 1115 // Or 2 * r + i is allowed as r + r + i. 1116 return true; 1117 default: // Don't allow n * r 1118 return false; 1119 } 1120 } 1121 1122 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1123 const AddrMode &AM, Type *Ty, 1124 unsigned AS, Instruction *I) const { 1125 // No global is ever allowed as a base. 1126 if (AM.BaseGV) 1127 return false; 1128 1129 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1130 return isLegalGlobalAddressingMode(AM); 1131 1132 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1133 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1134 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1135 // If the offset isn't a multiple of 4, it probably isn't going to be 1136 // correctly aligned. 1137 // FIXME: Can we get the real alignment here? 1138 if (AM.BaseOffs % 4 != 0) 1139 return isLegalMUBUFAddressingMode(AM); 1140 1141 // There are no SMRD extloads, so if we have to do a small type access we 1142 // will use a MUBUF load. 1143 // FIXME?: We also need to do this if unaligned, but we don't know the 1144 // alignment here. 1145 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1146 return isLegalGlobalAddressingMode(AM); 1147 1148 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1149 // SMRD instructions have an 8-bit, dword offset on SI. 1150 if (!isUInt<8>(AM.BaseOffs / 4)) 1151 return false; 1152 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1153 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1154 // in 8-bits, it can use a smaller encoding. 1155 if (!isUInt<32>(AM.BaseOffs / 4)) 1156 return false; 1157 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1158 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1159 if (!isUInt<20>(AM.BaseOffs)) 1160 return false; 1161 } else 1162 llvm_unreachable("unhandled generation"); 1163 1164 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1165 return true; 1166 1167 if (AM.Scale == 1 && AM.HasBaseReg) 1168 return true; 1169 1170 return false; 1171 1172 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1173 return isLegalMUBUFAddressingMode(AM); 1174 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1175 AS == AMDGPUAS::REGION_ADDRESS) { 1176 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1177 // field. 1178 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1179 // an 8-bit dword offset but we don't know the alignment here. 1180 if (!isUInt<16>(AM.BaseOffs)) 1181 return false; 1182 1183 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1184 return true; 1185 1186 if (AM.Scale == 1 && AM.HasBaseReg) 1187 return true; 1188 1189 return false; 1190 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1191 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1192 // For an unknown address space, this usually means that this is for some 1193 // reason being used for pure arithmetic, and not based on some addressing 1194 // computation. We don't have instructions that compute pointers with any 1195 // addressing modes, so treat them as having no offset like flat 1196 // instructions. 1197 return isLegalFlatAddressingMode(AM); 1198 } else { 1199 llvm_unreachable("unhandled address space"); 1200 } 1201 } 1202 1203 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1204 const SelectionDAG &DAG) const { 1205 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1206 return (MemVT.getSizeInBits() <= 4 * 32); 1207 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1208 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1209 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1210 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1211 return (MemVT.getSizeInBits() <= 2 * 32); 1212 } 1213 return true; 1214 } 1215 1216 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1217 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1218 bool *IsFast) const { 1219 if (IsFast) 1220 *IsFast = false; 1221 1222 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1223 // which isn't a simple VT. 1224 // Until MVT is extended to handle this, simply check for the size and 1225 // rely on the condition below: allow accesses if the size is a multiple of 4. 1226 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1227 VT.getStoreSize() > 16)) { 1228 return false; 1229 } 1230 1231 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1232 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1233 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1234 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1235 // with adjacent offsets. 1236 bool AlignedBy4 = (Align % 4 == 0); 1237 if (IsFast) 1238 *IsFast = AlignedBy4; 1239 1240 return AlignedBy4; 1241 } 1242 1243 // FIXME: We have to be conservative here and assume that flat operations 1244 // will access scratch. If we had access to the IR function, then we 1245 // could determine if any private memory was used in the function. 1246 if (!Subtarget->hasUnalignedScratchAccess() && 1247 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1248 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1249 bool AlignedBy4 = Align >= 4; 1250 if (IsFast) 1251 *IsFast = AlignedBy4; 1252 1253 return AlignedBy4; 1254 } 1255 1256 if (Subtarget->hasUnalignedBufferAccess()) { 1257 // If we have an uniform constant load, it still requires using a slow 1258 // buffer instruction if unaligned. 1259 if (IsFast) { 1260 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1261 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1262 (Align % 4 == 0) : true; 1263 } 1264 1265 return true; 1266 } 1267 1268 // Smaller than dword value must be aligned. 1269 if (VT.bitsLT(MVT::i32)) 1270 return false; 1271 1272 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1273 // byte-address are ignored, thus forcing Dword alignment. 1274 // This applies to private, global, and constant memory. 1275 if (IsFast) 1276 *IsFast = true; 1277 1278 return VT.bitsGT(MVT::i32) && Align % 4 == 0; 1279 } 1280 1281 EVT SITargetLowering::getOptimalMemOpType( 1282 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1283 bool ZeroMemset, bool MemcpyStrSrc, 1284 const AttributeList &FuncAttributes) const { 1285 // FIXME: Should account for address space here. 1286 1287 // The default fallback uses the private pointer size as a guess for a type to 1288 // use. Make sure we switch these to 64-bit accesses. 1289 1290 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1291 return MVT::v4i32; 1292 1293 if (Size >= 8 && DstAlign >= 4) 1294 return MVT::v2i32; 1295 1296 // Use the default. 1297 return MVT::Other; 1298 } 1299 1300 static bool isFlatGlobalAddrSpace(unsigned AS) { 1301 return AS == AMDGPUAS::GLOBAL_ADDRESS || 1302 AS == AMDGPUAS::FLAT_ADDRESS || 1303 AS == AMDGPUAS::CONSTANT_ADDRESS || 1304 AS > AMDGPUAS::MAX_AMDGPU_ADDRESS; 1305 } 1306 1307 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1308 unsigned DestAS) const { 1309 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1310 } 1311 1312 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1313 const MemSDNode *MemNode = cast<MemSDNode>(N); 1314 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1315 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1316 return I && I->getMetadata("amdgpu.noclobber"); 1317 } 1318 1319 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1320 unsigned DestAS) const { 1321 // Flat -> private/local is a simple truncate. 1322 // Flat -> global is no-op 1323 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1324 return true; 1325 1326 return isNoopAddrSpaceCast(SrcAS, DestAS); 1327 } 1328 1329 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1330 const MemSDNode *MemNode = cast<MemSDNode>(N); 1331 1332 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1333 } 1334 1335 TargetLoweringBase::LegalizeTypeAction 1336 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1337 if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1338 return TypeSplitVector; 1339 1340 return TargetLoweringBase::getPreferredVectorAction(VT); 1341 } 1342 1343 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1344 Type *Ty) const { 1345 // FIXME: Could be smarter if called for vector constants. 1346 return true; 1347 } 1348 1349 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1350 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1351 switch (Op) { 1352 case ISD::LOAD: 1353 case ISD::STORE: 1354 1355 // These operations are done with 32-bit instructions anyway. 1356 case ISD::AND: 1357 case ISD::OR: 1358 case ISD::XOR: 1359 case ISD::SELECT: 1360 // TODO: Extensions? 1361 return true; 1362 default: 1363 return false; 1364 } 1365 } 1366 1367 // SimplifySetCC uses this function to determine whether or not it should 1368 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1369 if (VT == MVT::i1 && Op == ISD::SETCC) 1370 return false; 1371 1372 return TargetLowering::isTypeDesirableForOp(Op, VT); 1373 } 1374 1375 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1376 const SDLoc &SL, 1377 SDValue Chain, 1378 uint64_t Offset) const { 1379 const DataLayout &DL = DAG.getDataLayout(); 1380 MachineFunction &MF = DAG.getMachineFunction(); 1381 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1382 1383 const ArgDescriptor *InputPtrReg; 1384 const TargetRegisterClass *RC; 1385 1386 std::tie(InputPtrReg, RC) 1387 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1388 1389 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1390 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1391 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1392 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1393 1394 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1395 } 1396 1397 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1398 const SDLoc &SL) const { 1399 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1400 FIRST_IMPLICIT); 1401 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1402 } 1403 1404 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1405 const SDLoc &SL, SDValue Val, 1406 bool Signed, 1407 const ISD::InputArg *Arg) const { 1408 // First, if it is a widened vector, narrow it. 1409 if (VT.isVector() && 1410 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1411 EVT NarrowedVT = 1412 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1413 VT.getVectorNumElements()); 1414 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1415 DAG.getConstant(0, SL, MVT::i32)); 1416 } 1417 1418 // Then convert the vector elements or scalar value. 1419 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1420 VT.bitsLT(MemVT)) { 1421 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1422 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1423 } 1424 1425 if (MemVT.isFloatingPoint()) 1426 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1427 else if (Signed) 1428 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1429 else 1430 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1431 1432 return Val; 1433 } 1434 1435 SDValue SITargetLowering::lowerKernargMemParameter( 1436 SelectionDAG &DAG, EVT VT, EVT MemVT, 1437 const SDLoc &SL, SDValue Chain, 1438 uint64_t Offset, unsigned Align, bool Signed, 1439 const ISD::InputArg *Arg) const { 1440 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1441 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1442 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1443 1444 // Try to avoid using an extload by loading earlier than the argument address, 1445 // and extracting the relevant bits. The load should hopefully be merged with 1446 // the previous argument. 1447 if (MemVT.getStoreSize() < 4 && Align < 4) { 1448 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1449 int64_t AlignDownOffset = alignDown(Offset, 4); 1450 int64_t OffsetDiff = Offset - AlignDownOffset; 1451 1452 EVT IntVT = MemVT.changeTypeToInteger(); 1453 1454 // TODO: If we passed in the base kernel offset we could have a better 1455 // alignment than 4, but we don't really need it. 1456 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1457 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1458 MachineMemOperand::MODereferenceable | 1459 MachineMemOperand::MOInvariant); 1460 1461 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1462 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1463 1464 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1465 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1466 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1467 1468 1469 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1470 } 1471 1472 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1473 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1474 MachineMemOperand::MODereferenceable | 1475 MachineMemOperand::MOInvariant); 1476 1477 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1478 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1479 } 1480 1481 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1482 const SDLoc &SL, SDValue Chain, 1483 const ISD::InputArg &Arg) const { 1484 MachineFunction &MF = DAG.getMachineFunction(); 1485 MachineFrameInfo &MFI = MF.getFrameInfo(); 1486 1487 if (Arg.Flags.isByVal()) { 1488 unsigned Size = Arg.Flags.getByValSize(); 1489 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1490 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1491 } 1492 1493 unsigned ArgOffset = VA.getLocMemOffset(); 1494 unsigned ArgSize = VA.getValVT().getStoreSize(); 1495 1496 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1497 1498 // Create load nodes to retrieve arguments from the stack. 1499 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1500 SDValue ArgValue; 1501 1502 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1503 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1504 MVT MemVT = VA.getValVT(); 1505 1506 switch (VA.getLocInfo()) { 1507 default: 1508 break; 1509 case CCValAssign::BCvt: 1510 MemVT = VA.getLocVT(); 1511 break; 1512 case CCValAssign::SExt: 1513 ExtType = ISD::SEXTLOAD; 1514 break; 1515 case CCValAssign::ZExt: 1516 ExtType = ISD::ZEXTLOAD; 1517 break; 1518 case CCValAssign::AExt: 1519 ExtType = ISD::EXTLOAD; 1520 break; 1521 } 1522 1523 ArgValue = DAG.getExtLoad( 1524 ExtType, SL, VA.getLocVT(), Chain, FIN, 1525 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1526 MemVT); 1527 return ArgValue; 1528 } 1529 1530 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1531 const SIMachineFunctionInfo &MFI, 1532 EVT VT, 1533 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1534 const ArgDescriptor *Reg; 1535 const TargetRegisterClass *RC; 1536 1537 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1538 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1539 } 1540 1541 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1542 CallingConv::ID CallConv, 1543 ArrayRef<ISD::InputArg> Ins, 1544 BitVector &Skipped, 1545 FunctionType *FType, 1546 SIMachineFunctionInfo *Info) { 1547 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1548 const ISD::InputArg *Arg = &Ins[I]; 1549 1550 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1551 "vector type argument should have been split"); 1552 1553 // First check if it's a PS input addr. 1554 if (CallConv == CallingConv::AMDGPU_PS && 1555 !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) { 1556 1557 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1558 1559 // Inconveniently only the first part of the split is marked as isSplit, 1560 // so skip to the end. We only want to increment PSInputNum once for the 1561 // entire split argument. 1562 if (Arg->Flags.isSplit()) { 1563 while (!Arg->Flags.isSplitEnd()) { 1564 assert(!Arg->VT.isVector() && 1565 "unexpected vector split in ps argument type"); 1566 if (!SkipArg) 1567 Splits.push_back(*Arg); 1568 Arg = &Ins[++I]; 1569 } 1570 } 1571 1572 if (SkipArg) { 1573 // We can safely skip PS inputs. 1574 Skipped.set(Arg->getOrigArgIndex()); 1575 ++PSInputNum; 1576 continue; 1577 } 1578 1579 Info->markPSInputAllocated(PSInputNum); 1580 if (Arg->Used) 1581 Info->markPSInputEnabled(PSInputNum); 1582 1583 ++PSInputNum; 1584 } 1585 1586 Splits.push_back(*Arg); 1587 } 1588 } 1589 1590 // Allocate special inputs passed in VGPRs. 1591 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1592 MachineFunction &MF, 1593 const SIRegisterInfo &TRI, 1594 SIMachineFunctionInfo &Info) { 1595 if (Info.hasWorkItemIDX()) { 1596 unsigned Reg = AMDGPU::VGPR0; 1597 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1598 1599 CCInfo.AllocateReg(Reg); 1600 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1601 } 1602 1603 if (Info.hasWorkItemIDY()) { 1604 unsigned Reg = AMDGPU::VGPR1; 1605 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1606 1607 CCInfo.AllocateReg(Reg); 1608 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1609 } 1610 1611 if (Info.hasWorkItemIDZ()) { 1612 unsigned Reg = AMDGPU::VGPR2; 1613 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1614 1615 CCInfo.AllocateReg(Reg); 1616 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1617 } 1618 } 1619 1620 // Try to allocate a VGPR at the end of the argument list, or if no argument 1621 // VGPRs are left allocating a stack slot. 1622 // If \p Mask is is given it indicates bitfield position in the register. 1623 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1624 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1625 ArgDescriptor Arg = ArgDescriptor()) { 1626 if (Arg.isSet()) 1627 return ArgDescriptor::createArg(Arg, Mask); 1628 1629 ArrayRef<MCPhysReg> ArgVGPRs 1630 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1631 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1632 if (RegIdx == ArgVGPRs.size()) { 1633 // Spill to stack required. 1634 int64_t Offset = CCInfo.AllocateStack(4, 4); 1635 1636 return ArgDescriptor::createStack(Offset, Mask); 1637 } 1638 1639 unsigned Reg = ArgVGPRs[RegIdx]; 1640 Reg = CCInfo.AllocateReg(Reg); 1641 assert(Reg != AMDGPU::NoRegister); 1642 1643 MachineFunction &MF = CCInfo.getMachineFunction(); 1644 MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1645 return ArgDescriptor::createRegister(Reg, Mask); 1646 } 1647 1648 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1649 const TargetRegisterClass *RC, 1650 unsigned NumArgRegs) { 1651 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1652 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1653 if (RegIdx == ArgSGPRs.size()) 1654 report_fatal_error("ran out of SGPRs for arguments"); 1655 1656 unsigned Reg = ArgSGPRs[RegIdx]; 1657 Reg = CCInfo.AllocateReg(Reg); 1658 assert(Reg != AMDGPU::NoRegister); 1659 1660 MachineFunction &MF = CCInfo.getMachineFunction(); 1661 MF.addLiveIn(Reg, RC); 1662 return ArgDescriptor::createRegister(Reg); 1663 } 1664 1665 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1666 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1667 } 1668 1669 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1670 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1671 } 1672 1673 static void allocateSpecialInputVGPRs(CCState &CCInfo, 1674 MachineFunction &MF, 1675 const SIRegisterInfo &TRI, 1676 SIMachineFunctionInfo &Info) { 1677 const unsigned Mask = 0x3ff; 1678 ArgDescriptor Arg; 1679 1680 if (Info.hasWorkItemIDX()) { 1681 Arg = allocateVGPR32Input(CCInfo, Mask); 1682 Info.setWorkItemIDX(Arg); 1683 } 1684 1685 if (Info.hasWorkItemIDY()) { 1686 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1687 Info.setWorkItemIDY(Arg); 1688 } 1689 1690 if (Info.hasWorkItemIDZ()) 1691 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1692 } 1693 1694 static void allocateSpecialInputSGPRs(CCState &CCInfo, 1695 MachineFunction &MF, 1696 const SIRegisterInfo &TRI, 1697 SIMachineFunctionInfo &Info) { 1698 auto &ArgInfo = Info.getArgInfo(); 1699 1700 // TODO: Unify handling with private memory pointers. 1701 1702 if (Info.hasDispatchPtr()) 1703 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1704 1705 if (Info.hasQueuePtr()) 1706 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1707 1708 if (Info.hasKernargSegmentPtr()) 1709 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1710 1711 if (Info.hasDispatchID()) 1712 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1713 1714 // flat_scratch_init is not applicable for non-kernel functions. 1715 1716 if (Info.hasWorkGroupIDX()) 1717 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1718 1719 if (Info.hasWorkGroupIDY()) 1720 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1721 1722 if (Info.hasWorkGroupIDZ()) 1723 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1724 1725 if (Info.hasImplicitArgPtr()) 1726 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1727 } 1728 1729 // Allocate special inputs passed in user SGPRs. 1730 static void allocateHSAUserSGPRs(CCState &CCInfo, 1731 MachineFunction &MF, 1732 const SIRegisterInfo &TRI, 1733 SIMachineFunctionInfo &Info) { 1734 if (Info.hasImplicitBufferPtr()) { 1735 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1736 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1737 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1738 } 1739 1740 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1741 if (Info.hasPrivateSegmentBuffer()) { 1742 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1743 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1744 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1745 } 1746 1747 if (Info.hasDispatchPtr()) { 1748 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1749 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1750 CCInfo.AllocateReg(DispatchPtrReg); 1751 } 1752 1753 if (Info.hasQueuePtr()) { 1754 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1755 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1756 CCInfo.AllocateReg(QueuePtrReg); 1757 } 1758 1759 if (Info.hasKernargSegmentPtr()) { 1760 unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI); 1761 MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1762 CCInfo.AllocateReg(InputPtrReg); 1763 } 1764 1765 if (Info.hasDispatchID()) { 1766 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1767 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1768 CCInfo.AllocateReg(DispatchIDReg); 1769 } 1770 1771 if (Info.hasFlatScratchInit()) { 1772 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1773 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1774 CCInfo.AllocateReg(FlatScratchInitReg); 1775 } 1776 1777 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1778 // these from the dispatch pointer. 1779 } 1780 1781 // Allocate special input registers that are initialized per-wave. 1782 static void allocateSystemSGPRs(CCState &CCInfo, 1783 MachineFunction &MF, 1784 SIMachineFunctionInfo &Info, 1785 CallingConv::ID CallConv, 1786 bool IsShader) { 1787 if (Info.hasWorkGroupIDX()) { 1788 unsigned Reg = Info.addWorkGroupIDX(); 1789 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1790 CCInfo.AllocateReg(Reg); 1791 } 1792 1793 if (Info.hasWorkGroupIDY()) { 1794 unsigned Reg = Info.addWorkGroupIDY(); 1795 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1796 CCInfo.AllocateReg(Reg); 1797 } 1798 1799 if (Info.hasWorkGroupIDZ()) { 1800 unsigned Reg = Info.addWorkGroupIDZ(); 1801 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1802 CCInfo.AllocateReg(Reg); 1803 } 1804 1805 if (Info.hasWorkGroupInfo()) { 1806 unsigned Reg = Info.addWorkGroupInfo(); 1807 MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass); 1808 CCInfo.AllocateReg(Reg); 1809 } 1810 1811 if (Info.hasPrivateSegmentWaveByteOffset()) { 1812 // Scratch wave offset passed in system SGPR. 1813 unsigned PrivateSegmentWaveByteOffsetReg; 1814 1815 if (IsShader) { 1816 PrivateSegmentWaveByteOffsetReg = 1817 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1818 1819 // This is true if the scratch wave byte offset doesn't have a fixed 1820 // location. 1821 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1822 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1823 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1824 } 1825 } else 1826 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1827 1828 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1829 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1830 } 1831 } 1832 1833 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1834 MachineFunction &MF, 1835 const SIRegisterInfo &TRI, 1836 SIMachineFunctionInfo &Info) { 1837 // Now that we've figured out where the scratch register inputs are, see if 1838 // should reserve the arguments and use them directly. 1839 MachineFrameInfo &MFI = MF.getFrameInfo(); 1840 bool HasStackObjects = MFI.hasStackObjects(); 1841 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1842 1843 // Record that we know we have non-spill stack objects so we don't need to 1844 // check all stack objects later. 1845 if (HasStackObjects) 1846 Info.setHasNonSpillStackObjects(true); 1847 1848 // Everything live out of a block is spilled with fast regalloc, so it's 1849 // almost certain that spilling will be required. 1850 if (TM.getOptLevel() == CodeGenOpt::None) 1851 HasStackObjects = true; 1852 1853 // For now assume stack access is needed in any callee functions, so we need 1854 // the scratch registers to pass in. 1855 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1856 1857 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1858 // If we have stack objects, we unquestionably need the private buffer 1859 // resource. For the Code Object V2 ABI, this will be the first 4 user 1860 // SGPR inputs. We can reserve those and use them directly. 1861 1862 unsigned PrivateSegmentBufferReg = 1863 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1864 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1865 } else { 1866 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1867 // We tentatively reserve the last registers (skipping the last registers 1868 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1869 // we'll replace these with the ones immediately after those which were 1870 // really allocated. In the prologue copies will be inserted from the 1871 // argument to these reserved registers. 1872 1873 // Without HSA, relocations are used for the scratch pointer and the 1874 // buffer resource setup is always inserted in the prologue. Scratch wave 1875 // offset is still in an input SGPR. 1876 Info.setScratchRSrcReg(ReservedBufferReg); 1877 } 1878 1879 // hasFP should be accurate for kernels even before the frame is finalized. 1880 if (ST.getFrameLowering()->hasFP(MF)) { 1881 MachineRegisterInfo &MRI = MF.getRegInfo(); 1882 1883 // Try to use s32 as the SP, but move it if it would interfere with input 1884 // arguments. This won't work with calls though. 1885 // 1886 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1887 // registers. 1888 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1889 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1890 } else { 1891 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1892 1893 if (MFI.hasCalls()) 1894 report_fatal_error("call in graphics shader with too many input SGPRs"); 1895 1896 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1897 if (!MRI.isLiveIn(Reg)) { 1898 Info.setStackPtrOffsetReg(Reg); 1899 break; 1900 } 1901 } 1902 1903 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1904 report_fatal_error("failed to find register for SP"); 1905 } 1906 1907 if (MFI.hasCalls()) { 1908 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1909 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1910 } else { 1911 unsigned ReservedOffsetReg = 1912 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1913 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1914 Info.setFrameOffsetReg(ReservedOffsetReg); 1915 } 1916 } else if (RequiresStackAccess) { 1917 assert(!MFI.hasCalls()); 1918 // We know there are accesses and they will be done relative to SP, so just 1919 // pin it to the input. 1920 // 1921 // FIXME: Should not do this if inline asm is reading/writing these 1922 // registers. 1923 unsigned PreloadedSP = Info.getPreloadedReg( 1924 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1925 1926 Info.setStackPtrOffsetReg(PreloadedSP); 1927 Info.setScratchWaveOffsetReg(PreloadedSP); 1928 Info.setFrameOffsetReg(PreloadedSP); 1929 } else { 1930 assert(!MFI.hasCalls()); 1931 1932 // There may not be stack access at all. There may still be spills, or 1933 // access of a constant pointer (in which cases an extra copy will be 1934 // emitted in the prolog). 1935 unsigned ReservedOffsetReg 1936 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1937 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1938 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1939 Info.setFrameOffsetReg(ReservedOffsetReg); 1940 } 1941 } 1942 1943 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1944 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1945 return !Info->isEntryFunction(); 1946 } 1947 1948 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1949 1950 } 1951 1952 void SITargetLowering::insertCopiesSplitCSR( 1953 MachineBasicBlock *Entry, 1954 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1955 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1956 1957 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1958 if (!IStart) 1959 return; 1960 1961 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1962 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1963 MachineBasicBlock::iterator MBBI = Entry->begin(); 1964 for (const MCPhysReg *I = IStart; *I; ++I) { 1965 const TargetRegisterClass *RC = nullptr; 1966 if (AMDGPU::SReg_64RegClass.contains(*I)) 1967 RC = &AMDGPU::SGPR_64RegClass; 1968 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1969 RC = &AMDGPU::SGPR_32RegClass; 1970 else 1971 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1972 1973 unsigned NewVR = MRI->createVirtualRegister(RC); 1974 // Create copy from CSR to a virtual register. 1975 Entry->addLiveIn(*I); 1976 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1977 .addReg(*I); 1978 1979 // Insert the copy-back instructions right before the terminator. 1980 for (auto *Exit : Exits) 1981 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1982 TII->get(TargetOpcode::COPY), *I) 1983 .addReg(NewVR); 1984 } 1985 } 1986 1987 SDValue SITargetLowering::LowerFormalArguments( 1988 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 1989 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 1990 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 1991 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1992 1993 MachineFunction &MF = DAG.getMachineFunction(); 1994 const Function &Fn = MF.getFunction(); 1995 FunctionType *FType = MF.getFunction().getFunctionType(); 1996 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1997 1998 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 1999 DiagnosticInfoUnsupported NoGraphicsHSA( 2000 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2001 DAG.getContext()->diagnose(NoGraphicsHSA); 2002 return DAG.getEntryNode(); 2003 } 2004 2005 SmallVector<ISD::InputArg, 16> Splits; 2006 SmallVector<CCValAssign, 16> ArgLocs; 2007 BitVector Skipped(Ins.size()); 2008 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2009 *DAG.getContext()); 2010 2011 bool IsShader = AMDGPU::isShader(CallConv); 2012 bool IsKernel = AMDGPU::isKernel(CallConv); 2013 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2014 2015 if (IsShader) { 2016 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2017 2018 // At least one interpolation mode must be enabled or else the GPU will 2019 // hang. 2020 // 2021 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2022 // set PSInputAddr, the user wants to enable some bits after the compilation 2023 // based on run-time states. Since we can't know what the final PSInputEna 2024 // will look like, so we shouldn't do anything here and the user should take 2025 // responsibility for the correct programming. 2026 // 2027 // Otherwise, the following restrictions apply: 2028 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2029 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2030 // enabled too. 2031 if (CallConv == CallingConv::AMDGPU_PS) { 2032 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2033 ((Info->getPSInputAddr() & 0xF) == 0 && 2034 Info->isPSInputAllocated(11))) { 2035 CCInfo.AllocateReg(AMDGPU::VGPR0); 2036 CCInfo.AllocateReg(AMDGPU::VGPR1); 2037 Info->markPSInputAllocated(0); 2038 Info->markPSInputEnabled(0); 2039 } 2040 if (Subtarget->isAmdPalOS()) { 2041 // For isAmdPalOS, the user does not enable some bits after compilation 2042 // based on run-time states; the register values being generated here are 2043 // the final ones set in hardware. Therefore we need to apply the 2044 // workaround to PSInputAddr and PSInputEnable together. (The case where 2045 // a bit is set in PSInputAddr but not PSInputEnable is where the 2046 // frontend set up an input arg for a particular interpolation mode, but 2047 // nothing uses that input arg. Really we should have an earlier pass 2048 // that removes such an arg.) 2049 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2050 if ((PsInputBits & 0x7F) == 0 || 2051 ((PsInputBits & 0xF) == 0 && 2052 (PsInputBits >> 11 & 1))) 2053 Info->markPSInputEnabled( 2054 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2055 } 2056 } 2057 2058 assert(!Info->hasDispatchPtr() && 2059 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2060 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2061 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2062 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2063 !Info->hasWorkItemIDZ()); 2064 } else if (IsKernel) { 2065 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2066 } else { 2067 Splits.append(Ins.begin(), Ins.end()); 2068 } 2069 2070 if (IsEntryFunc) { 2071 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2072 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2073 } 2074 2075 if (IsKernel) { 2076 analyzeFormalArgumentsCompute(CCInfo, Ins); 2077 } else { 2078 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2079 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2080 } 2081 2082 SmallVector<SDValue, 16> Chains; 2083 2084 // FIXME: This is the minimum kernel argument alignment. We should improve 2085 // this to the maximum alignment of the arguments. 2086 // 2087 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2088 // kern arg offset. 2089 const unsigned KernelArgBaseAlign = 16; 2090 2091 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2092 const ISD::InputArg &Arg = Ins[i]; 2093 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2094 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2095 continue; 2096 } 2097 2098 CCValAssign &VA = ArgLocs[ArgIdx++]; 2099 MVT VT = VA.getLocVT(); 2100 2101 if (IsEntryFunc && VA.isMemLoc()) { 2102 VT = Ins[i].VT; 2103 EVT MemVT = VA.getLocVT(); 2104 2105 const uint64_t Offset = VA.getLocMemOffset(); 2106 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2107 2108 SDValue Arg = lowerKernargMemParameter( 2109 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2110 Chains.push_back(Arg.getValue(1)); 2111 2112 auto *ParamTy = 2113 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2114 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2115 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2116 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2117 // On SI local pointers are just offsets into LDS, so they are always 2118 // less than 16-bits. On CI and newer they could potentially be 2119 // real pointers, so we can't guarantee their size. 2120 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2121 DAG.getValueType(MVT::i16)); 2122 } 2123 2124 InVals.push_back(Arg); 2125 continue; 2126 } else if (!IsEntryFunc && VA.isMemLoc()) { 2127 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2128 InVals.push_back(Val); 2129 if (!Arg.Flags.isByVal()) 2130 Chains.push_back(Val.getValue(1)); 2131 continue; 2132 } 2133 2134 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2135 2136 unsigned Reg = VA.getLocReg(); 2137 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2138 EVT ValVT = VA.getValVT(); 2139 2140 Reg = MF.addLiveIn(Reg, RC); 2141 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2142 2143 if (Arg.Flags.isSRet()) { 2144 // The return object should be reasonably addressable. 2145 2146 // FIXME: This helps when the return is a real sret. If it is a 2147 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2148 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2149 unsigned NumBits 2150 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2151 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2152 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2153 } 2154 2155 // If this is an 8 or 16-bit value, it is really passed promoted 2156 // to 32 bits. Insert an assert[sz]ext to capture this, then 2157 // truncate to the right size. 2158 switch (VA.getLocInfo()) { 2159 case CCValAssign::Full: 2160 break; 2161 case CCValAssign::BCvt: 2162 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2163 break; 2164 case CCValAssign::SExt: 2165 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2166 DAG.getValueType(ValVT)); 2167 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2168 break; 2169 case CCValAssign::ZExt: 2170 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2171 DAG.getValueType(ValVT)); 2172 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2173 break; 2174 case CCValAssign::AExt: 2175 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2176 break; 2177 default: 2178 llvm_unreachable("Unknown loc info!"); 2179 } 2180 2181 InVals.push_back(Val); 2182 } 2183 2184 if (!IsEntryFunc) { 2185 // Special inputs come after user arguments. 2186 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2187 } 2188 2189 // Start adding system SGPRs. 2190 if (IsEntryFunc) { 2191 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2192 } else { 2193 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2194 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2195 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2196 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2197 } 2198 2199 auto &ArgUsageInfo = 2200 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2201 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2202 2203 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2204 Info->setBytesInStackArgArea(StackArgSize); 2205 2206 return Chains.empty() ? Chain : 2207 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2208 } 2209 2210 // TODO: If return values can't fit in registers, we should return as many as 2211 // possible in registers before passing on stack. 2212 bool SITargetLowering::CanLowerReturn( 2213 CallingConv::ID CallConv, 2214 MachineFunction &MF, bool IsVarArg, 2215 const SmallVectorImpl<ISD::OutputArg> &Outs, 2216 LLVMContext &Context) const { 2217 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2218 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2219 // for shaders. Vector types should be explicitly handled by CC. 2220 if (AMDGPU::isEntryFunctionCC(CallConv)) 2221 return true; 2222 2223 SmallVector<CCValAssign, 16> RVLocs; 2224 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2225 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2226 } 2227 2228 SDValue 2229 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2230 bool isVarArg, 2231 const SmallVectorImpl<ISD::OutputArg> &Outs, 2232 const SmallVectorImpl<SDValue> &OutVals, 2233 const SDLoc &DL, SelectionDAG &DAG) const { 2234 MachineFunction &MF = DAG.getMachineFunction(); 2235 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2236 2237 if (AMDGPU::isKernel(CallConv)) { 2238 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2239 OutVals, DL, DAG); 2240 } 2241 2242 bool IsShader = AMDGPU::isShader(CallConv); 2243 2244 Info->setIfReturnsVoid(Outs.empty()); 2245 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2246 2247 // CCValAssign - represent the assignment of the return value to a location. 2248 SmallVector<CCValAssign, 48> RVLocs; 2249 SmallVector<ISD::OutputArg, 48> Splits; 2250 2251 // CCState - Info about the registers and stack slots. 2252 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2253 *DAG.getContext()); 2254 2255 // Analyze outgoing return values. 2256 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2257 2258 SDValue Flag; 2259 SmallVector<SDValue, 48> RetOps; 2260 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2261 2262 // Add return address for callable functions. 2263 if (!Info->isEntryFunction()) { 2264 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2265 SDValue ReturnAddrReg = CreateLiveInRegister( 2266 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2267 2268 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2269 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2270 MVT::i64); 2271 Chain = 2272 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2273 Flag = Chain.getValue(1); 2274 RetOps.push_back(ReturnAddrVirtualReg); 2275 } 2276 2277 // Copy the result values into the output registers. 2278 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2279 ++I, ++RealRVLocIdx) { 2280 CCValAssign &VA = RVLocs[I]; 2281 assert(VA.isRegLoc() && "Can only return in registers!"); 2282 // TODO: Partially return in registers if return values don't fit. 2283 SDValue Arg = OutVals[RealRVLocIdx]; 2284 2285 // Copied from other backends. 2286 switch (VA.getLocInfo()) { 2287 case CCValAssign::Full: 2288 break; 2289 case CCValAssign::BCvt: 2290 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2291 break; 2292 case CCValAssign::SExt: 2293 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2294 break; 2295 case CCValAssign::ZExt: 2296 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2297 break; 2298 case CCValAssign::AExt: 2299 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2300 break; 2301 default: 2302 llvm_unreachable("Unknown loc info!"); 2303 } 2304 2305 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2306 Flag = Chain.getValue(1); 2307 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2308 } 2309 2310 // FIXME: Does sret work properly? 2311 if (!Info->isEntryFunction()) { 2312 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2313 const MCPhysReg *I = 2314 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2315 if (I) { 2316 for (; *I; ++I) { 2317 if (AMDGPU::SReg_64RegClass.contains(*I)) 2318 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2319 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2320 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2321 else 2322 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2323 } 2324 } 2325 } 2326 2327 // Update chain and glue. 2328 RetOps[0] = Chain; 2329 if (Flag.getNode()) 2330 RetOps.push_back(Flag); 2331 2332 unsigned Opc = AMDGPUISD::ENDPGM; 2333 if (!IsWaveEnd) 2334 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2335 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2336 } 2337 2338 SDValue SITargetLowering::LowerCallResult( 2339 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2340 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2341 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2342 SDValue ThisVal) const { 2343 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2344 2345 // Assign locations to each value returned by this call. 2346 SmallVector<CCValAssign, 16> RVLocs; 2347 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2348 *DAG.getContext()); 2349 CCInfo.AnalyzeCallResult(Ins, RetCC); 2350 2351 // Copy all of the result registers out of their specified physreg. 2352 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2353 CCValAssign VA = RVLocs[i]; 2354 SDValue Val; 2355 2356 if (VA.isRegLoc()) { 2357 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2358 Chain = Val.getValue(1); 2359 InFlag = Val.getValue(2); 2360 } else if (VA.isMemLoc()) { 2361 report_fatal_error("TODO: return values in memory"); 2362 } else 2363 llvm_unreachable("unknown argument location type"); 2364 2365 switch (VA.getLocInfo()) { 2366 case CCValAssign::Full: 2367 break; 2368 case CCValAssign::BCvt: 2369 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2370 break; 2371 case CCValAssign::ZExt: 2372 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2373 DAG.getValueType(VA.getValVT())); 2374 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2375 break; 2376 case CCValAssign::SExt: 2377 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2378 DAG.getValueType(VA.getValVT())); 2379 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2380 break; 2381 case CCValAssign::AExt: 2382 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2383 break; 2384 default: 2385 llvm_unreachable("Unknown loc info!"); 2386 } 2387 2388 InVals.push_back(Val); 2389 } 2390 2391 return Chain; 2392 } 2393 2394 // Add code to pass special inputs required depending on used features separate 2395 // from the explicit user arguments present in the IR. 2396 void SITargetLowering::passSpecialInputs( 2397 CallLoweringInfo &CLI, 2398 CCState &CCInfo, 2399 const SIMachineFunctionInfo &Info, 2400 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2401 SmallVectorImpl<SDValue> &MemOpChains, 2402 SDValue Chain) const { 2403 // If we don't have a call site, this was a call inserted by 2404 // legalization. These can never use special inputs. 2405 if (!CLI.CS) 2406 return; 2407 2408 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2409 assert(CalleeFunc); 2410 2411 SelectionDAG &DAG = CLI.DAG; 2412 const SDLoc &DL = CLI.DL; 2413 2414 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2415 2416 auto &ArgUsageInfo = 2417 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2418 const AMDGPUFunctionArgInfo &CalleeArgInfo 2419 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2420 2421 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2422 2423 // TODO: Unify with private memory register handling. This is complicated by 2424 // the fact that at least in kernels, the input argument is not necessarily 2425 // in the same location as the input. 2426 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2427 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2428 AMDGPUFunctionArgInfo::QUEUE_PTR, 2429 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2430 AMDGPUFunctionArgInfo::DISPATCH_ID, 2431 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2432 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2433 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2434 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2435 }; 2436 2437 for (auto InputID : InputRegs) { 2438 const ArgDescriptor *OutgoingArg; 2439 const TargetRegisterClass *ArgRC; 2440 2441 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2442 if (!OutgoingArg) 2443 continue; 2444 2445 const ArgDescriptor *IncomingArg; 2446 const TargetRegisterClass *IncomingArgRC; 2447 std::tie(IncomingArg, IncomingArgRC) 2448 = CallerArgInfo.getPreloadedValue(InputID); 2449 assert(IncomingArgRC == ArgRC); 2450 2451 // All special arguments are ints for now. 2452 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2453 SDValue InputReg; 2454 2455 if (IncomingArg) { 2456 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2457 } else { 2458 // The implicit arg ptr is special because it doesn't have a corresponding 2459 // input for kernels, and is computed from the kernarg segment pointer. 2460 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2461 InputReg = getImplicitArgPtr(DAG, DL); 2462 } 2463 2464 if (OutgoingArg->isRegister()) { 2465 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2466 } else { 2467 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2468 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2469 SpecialArgOffset); 2470 MemOpChains.push_back(ArgStore); 2471 } 2472 } 2473 2474 // Pack workitem IDs into a single register or pass it as is if already 2475 // packed. 2476 const ArgDescriptor *OutgoingArg; 2477 const TargetRegisterClass *ArgRC; 2478 2479 std::tie(OutgoingArg, ArgRC) = 2480 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2481 if (!OutgoingArg) 2482 std::tie(OutgoingArg, ArgRC) = 2483 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2484 if (!OutgoingArg) 2485 std::tie(OutgoingArg, ArgRC) = 2486 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2487 if (!OutgoingArg) 2488 return; 2489 2490 const ArgDescriptor *IncomingArgX 2491 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2492 const ArgDescriptor *IncomingArgY 2493 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2494 const ArgDescriptor *IncomingArgZ 2495 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2496 2497 SDValue InputReg; 2498 SDLoc SL; 2499 2500 // If incoming ids are not packed we need to pack them. 2501 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2502 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2503 2504 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2505 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2506 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2507 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2508 InputReg = InputReg.getNode() ? 2509 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2510 } 2511 2512 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2513 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2514 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2515 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2516 InputReg = InputReg.getNode() ? 2517 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2518 } 2519 2520 if (!InputReg.getNode()) { 2521 // Workitem ids are already packed, any of present incoming arguments 2522 // will carry all required fields. 2523 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2524 IncomingArgX ? *IncomingArgX : 2525 IncomingArgY ? *IncomingArgY : 2526 *IncomingArgZ, ~0u); 2527 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2528 } 2529 2530 if (OutgoingArg->isRegister()) { 2531 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2532 } else { 2533 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2534 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2535 SpecialArgOffset); 2536 MemOpChains.push_back(ArgStore); 2537 } 2538 } 2539 2540 static bool canGuaranteeTCO(CallingConv::ID CC) { 2541 return CC == CallingConv::Fast; 2542 } 2543 2544 /// Return true if we might ever do TCO for calls with this calling convention. 2545 static bool mayTailCallThisCC(CallingConv::ID CC) { 2546 switch (CC) { 2547 case CallingConv::C: 2548 return true; 2549 default: 2550 return canGuaranteeTCO(CC); 2551 } 2552 } 2553 2554 bool SITargetLowering::isEligibleForTailCallOptimization( 2555 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2556 const SmallVectorImpl<ISD::OutputArg> &Outs, 2557 const SmallVectorImpl<SDValue> &OutVals, 2558 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2559 if (!mayTailCallThisCC(CalleeCC)) 2560 return false; 2561 2562 MachineFunction &MF = DAG.getMachineFunction(); 2563 const Function &CallerF = MF.getFunction(); 2564 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2565 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2566 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2567 2568 // Kernels aren't callable, and don't have a live in return address so it 2569 // doesn't make sense to do a tail call with entry functions. 2570 if (!CallerPreserved) 2571 return false; 2572 2573 bool CCMatch = CallerCC == CalleeCC; 2574 2575 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2576 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2577 return true; 2578 return false; 2579 } 2580 2581 // TODO: Can we handle var args? 2582 if (IsVarArg) 2583 return false; 2584 2585 for (const Argument &Arg : CallerF.args()) { 2586 if (Arg.hasByValAttr()) 2587 return false; 2588 } 2589 2590 LLVMContext &Ctx = *DAG.getContext(); 2591 2592 // Check that the call results are passed in the same way. 2593 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2594 CCAssignFnForCall(CalleeCC, IsVarArg), 2595 CCAssignFnForCall(CallerCC, IsVarArg))) 2596 return false; 2597 2598 // The callee has to preserve all registers the caller needs to preserve. 2599 if (!CCMatch) { 2600 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2601 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2602 return false; 2603 } 2604 2605 // Nothing more to check if the callee is taking no arguments. 2606 if (Outs.empty()) 2607 return true; 2608 2609 SmallVector<CCValAssign, 16> ArgLocs; 2610 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2611 2612 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2613 2614 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2615 // If the stack arguments for this call do not fit into our own save area then 2616 // the call cannot be made tail. 2617 // TODO: Is this really necessary? 2618 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2619 return false; 2620 2621 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2622 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2623 } 2624 2625 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2626 if (!CI->isTailCall()) 2627 return false; 2628 2629 const Function *ParentFn = CI->getParent()->getParent(); 2630 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2631 return false; 2632 2633 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2634 return (Attr.getValueAsString() != "true"); 2635 } 2636 2637 // The wave scratch offset register is used as the global base pointer. 2638 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2639 SmallVectorImpl<SDValue> &InVals) const { 2640 SelectionDAG &DAG = CLI.DAG; 2641 const SDLoc &DL = CLI.DL; 2642 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2643 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2644 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2645 SDValue Chain = CLI.Chain; 2646 SDValue Callee = CLI.Callee; 2647 bool &IsTailCall = CLI.IsTailCall; 2648 CallingConv::ID CallConv = CLI.CallConv; 2649 bool IsVarArg = CLI.IsVarArg; 2650 bool IsSibCall = false; 2651 bool IsThisReturn = false; 2652 MachineFunction &MF = DAG.getMachineFunction(); 2653 2654 if (IsVarArg) { 2655 return lowerUnhandledCall(CLI, InVals, 2656 "unsupported call to variadic function "); 2657 } 2658 2659 if (!CLI.CS.getInstruction()) 2660 report_fatal_error("unsupported libcall legalization"); 2661 2662 if (!CLI.CS.getCalledFunction()) { 2663 return lowerUnhandledCall(CLI, InVals, 2664 "unsupported indirect call to function "); 2665 } 2666 2667 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2668 return lowerUnhandledCall(CLI, InVals, 2669 "unsupported required tail call to function "); 2670 } 2671 2672 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2673 // Note the issue is with the CC of the calling function, not of the call 2674 // itself. 2675 return lowerUnhandledCall(CLI, InVals, 2676 "unsupported call from graphics shader of function "); 2677 } 2678 2679 if (IsTailCall) { 2680 IsTailCall = isEligibleForTailCallOptimization( 2681 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2682 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2683 report_fatal_error("failed to perform tail call elimination on a call " 2684 "site marked musttail"); 2685 } 2686 2687 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2688 2689 // A sibling call is one where we're under the usual C ABI and not planning 2690 // to change that but can still do a tail call: 2691 if (!TailCallOpt && IsTailCall) 2692 IsSibCall = true; 2693 2694 if (IsTailCall) 2695 ++NumTailCalls; 2696 } 2697 2698 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2699 2700 // Analyze operands of the call, assigning locations to each operand. 2701 SmallVector<CCValAssign, 16> ArgLocs; 2702 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2703 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2704 2705 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2706 2707 // Get a count of how many bytes are to be pushed on the stack. 2708 unsigned NumBytes = CCInfo.getNextStackOffset(); 2709 2710 if (IsSibCall) { 2711 // Since we're not changing the ABI to make this a tail call, the memory 2712 // operands are already available in the caller's incoming argument space. 2713 NumBytes = 0; 2714 } 2715 2716 // FPDiff is the byte offset of the call's argument area from the callee's. 2717 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2718 // by this amount for a tail call. In a sibling call it must be 0 because the 2719 // caller will deallocate the entire stack and the callee still expects its 2720 // arguments to begin at SP+0. Completely unused for non-tail calls. 2721 int32_t FPDiff = 0; 2722 MachineFrameInfo &MFI = MF.getFrameInfo(); 2723 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2724 2725 // Adjust the stack pointer for the new arguments... 2726 // These operations are automatically eliminated by the prolog/epilog pass 2727 if (!IsSibCall) { 2728 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2729 2730 SmallVector<SDValue, 4> CopyFromChains; 2731 2732 // In the HSA case, this should be an identity copy. 2733 SDValue ScratchRSrcReg 2734 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2735 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2736 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2737 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2738 } 2739 2740 SmallVector<SDValue, 8> MemOpChains; 2741 MVT PtrVT = MVT::i32; 2742 2743 // Walk the register/memloc assignments, inserting copies/loads. 2744 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2745 ++i, ++realArgIdx) { 2746 CCValAssign &VA = ArgLocs[i]; 2747 SDValue Arg = OutVals[realArgIdx]; 2748 2749 // Promote the value if needed. 2750 switch (VA.getLocInfo()) { 2751 case CCValAssign::Full: 2752 break; 2753 case CCValAssign::BCvt: 2754 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2755 break; 2756 case CCValAssign::ZExt: 2757 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2758 break; 2759 case CCValAssign::SExt: 2760 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2761 break; 2762 case CCValAssign::AExt: 2763 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2764 break; 2765 case CCValAssign::FPExt: 2766 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2767 break; 2768 default: 2769 llvm_unreachable("Unknown loc info!"); 2770 } 2771 2772 if (VA.isRegLoc()) { 2773 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2774 } else { 2775 assert(VA.isMemLoc()); 2776 2777 SDValue DstAddr; 2778 MachinePointerInfo DstInfo; 2779 2780 unsigned LocMemOffset = VA.getLocMemOffset(); 2781 int32_t Offset = LocMemOffset; 2782 2783 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2784 unsigned Align = 0; 2785 2786 if (IsTailCall) { 2787 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2788 unsigned OpSize = Flags.isByVal() ? 2789 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2790 2791 // FIXME: We can have better than the minimum byval required alignment. 2792 Align = Flags.isByVal() ? Flags.getByValAlign() : 2793 MinAlign(Subtarget->getStackAlignment(), Offset); 2794 2795 Offset = Offset + FPDiff; 2796 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2797 2798 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2799 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2800 2801 // Make sure any stack arguments overlapping with where we're storing 2802 // are loaded before this eventual operation. Otherwise they'll be 2803 // clobbered. 2804 2805 // FIXME: Why is this really necessary? This seems to just result in a 2806 // lot of code to copy the stack and write them back to the same 2807 // locations, which are supposed to be immutable? 2808 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2809 } else { 2810 DstAddr = PtrOff; 2811 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2812 Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset); 2813 } 2814 2815 if (Outs[i].Flags.isByVal()) { 2816 SDValue SizeNode = 2817 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2818 SDValue Cpy = DAG.getMemcpy( 2819 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2820 /*isVol = */ false, /*AlwaysInline = */ true, 2821 /*isTailCall = */ false, DstInfo, 2822 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2823 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS)))); 2824 2825 MemOpChains.push_back(Cpy); 2826 } else { 2827 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align); 2828 MemOpChains.push_back(Store); 2829 } 2830 } 2831 } 2832 2833 // Copy special input registers after user input arguments. 2834 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2835 2836 if (!MemOpChains.empty()) 2837 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2838 2839 // Build a sequence of copy-to-reg nodes chained together with token chain 2840 // and flag operands which copy the outgoing args into the appropriate regs. 2841 SDValue InFlag; 2842 for (auto &RegToPass : RegsToPass) { 2843 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2844 RegToPass.second, InFlag); 2845 InFlag = Chain.getValue(1); 2846 } 2847 2848 2849 SDValue PhysReturnAddrReg; 2850 if (IsTailCall) { 2851 // Since the return is being combined with the call, we need to pass on the 2852 // return address. 2853 2854 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2855 SDValue ReturnAddrReg = CreateLiveInRegister( 2856 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2857 2858 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2859 MVT::i64); 2860 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2861 InFlag = Chain.getValue(1); 2862 } 2863 2864 // We don't usually want to end the call-sequence here because we would tidy 2865 // the frame up *after* the call, however in the ABI-changing tail-call case 2866 // we've carefully laid out the parameters so that when sp is reset they'll be 2867 // in the correct location. 2868 if (IsTailCall && !IsSibCall) { 2869 Chain = DAG.getCALLSEQ_END(Chain, 2870 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2871 DAG.getTargetConstant(0, DL, MVT::i32), 2872 InFlag, DL); 2873 InFlag = Chain.getValue(1); 2874 } 2875 2876 std::vector<SDValue> Ops; 2877 Ops.push_back(Chain); 2878 Ops.push_back(Callee); 2879 // Add a redundant copy of the callee global which will not be legalized, as 2880 // we need direct access to the callee later. 2881 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2882 const GlobalValue *GV = GSD->getGlobal(); 2883 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2884 2885 if (IsTailCall) { 2886 // Each tail call may have to adjust the stack by a different amount, so 2887 // this information must travel along with the operation for eventual 2888 // consumption by emitEpilogue. 2889 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2890 2891 Ops.push_back(PhysReturnAddrReg); 2892 } 2893 2894 // Add argument registers to the end of the list so that they are known live 2895 // into the call. 2896 for (auto &RegToPass : RegsToPass) { 2897 Ops.push_back(DAG.getRegister(RegToPass.first, 2898 RegToPass.second.getValueType())); 2899 } 2900 2901 // Add a register mask operand representing the call-preserved registers. 2902 2903 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2904 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2905 assert(Mask && "Missing call preserved mask for calling convention"); 2906 Ops.push_back(DAG.getRegisterMask(Mask)); 2907 2908 if (InFlag.getNode()) 2909 Ops.push_back(InFlag); 2910 2911 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2912 2913 // If we're doing a tall call, use a TC_RETURN here rather than an 2914 // actual call instruction. 2915 if (IsTailCall) { 2916 MFI.setHasTailCall(); 2917 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2918 } 2919 2920 // Returns a chain and a flag for retval copy to use. 2921 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2922 Chain = Call.getValue(0); 2923 InFlag = Call.getValue(1); 2924 2925 uint64_t CalleePopBytes = NumBytes; 2926 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2927 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2928 InFlag, DL); 2929 if (!Ins.empty()) 2930 InFlag = Chain.getValue(1); 2931 2932 // Handle result values, copying them out of physregs into vregs that we 2933 // return. 2934 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2935 InVals, IsThisReturn, 2936 IsThisReturn ? OutVals[0] : SDValue()); 2937 } 2938 2939 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2940 SelectionDAG &DAG) const { 2941 unsigned Reg = StringSwitch<unsigned>(RegName) 2942 .Case("m0", AMDGPU::M0) 2943 .Case("exec", AMDGPU::EXEC) 2944 .Case("exec_lo", AMDGPU::EXEC_LO) 2945 .Case("exec_hi", AMDGPU::EXEC_HI) 2946 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2947 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2948 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2949 .Default(AMDGPU::NoRegister); 2950 2951 if (Reg == AMDGPU::NoRegister) { 2952 report_fatal_error(Twine("invalid register name \"" 2953 + StringRef(RegName) + "\".")); 2954 2955 } 2956 2957 if (!Subtarget->hasFlatScrRegister() && 2958 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2959 report_fatal_error(Twine("invalid register \"" 2960 + StringRef(RegName) + "\" for subtarget.")); 2961 } 2962 2963 switch (Reg) { 2964 case AMDGPU::M0: 2965 case AMDGPU::EXEC_LO: 2966 case AMDGPU::EXEC_HI: 2967 case AMDGPU::FLAT_SCR_LO: 2968 case AMDGPU::FLAT_SCR_HI: 2969 if (VT.getSizeInBits() == 32) 2970 return Reg; 2971 break; 2972 case AMDGPU::EXEC: 2973 case AMDGPU::FLAT_SCR: 2974 if (VT.getSizeInBits() == 64) 2975 return Reg; 2976 break; 2977 default: 2978 llvm_unreachable("missing register type checking"); 2979 } 2980 2981 report_fatal_error(Twine("invalid type for register \"" 2982 + StringRef(RegName) + "\".")); 2983 } 2984 2985 // If kill is not the last instruction, split the block so kill is always a 2986 // proper terminator. 2987 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 2988 MachineBasicBlock *BB) const { 2989 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 2990 2991 MachineBasicBlock::iterator SplitPoint(&MI); 2992 ++SplitPoint; 2993 2994 if (SplitPoint == BB->end()) { 2995 // Don't bother with a new block. 2996 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 2997 return BB; 2998 } 2999 3000 MachineFunction *MF = BB->getParent(); 3001 MachineBasicBlock *SplitBB 3002 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3003 3004 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3005 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3006 3007 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3008 BB->addSuccessor(SplitBB); 3009 3010 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3011 return SplitBB; 3012 } 3013 3014 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3015 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3016 // be the first instruction in the remainder block. 3017 // 3018 /// \returns { LoopBody, Remainder } 3019 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3020 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3021 MachineFunction *MF = MBB.getParent(); 3022 MachineBasicBlock::iterator I(&MI); 3023 3024 // To insert the loop we need to split the block. Move everything after this 3025 // point to a new block, and insert a new empty block between the two. 3026 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3027 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3028 MachineFunction::iterator MBBI(MBB); 3029 ++MBBI; 3030 3031 MF->insert(MBBI, LoopBB); 3032 MF->insert(MBBI, RemainderBB); 3033 3034 LoopBB->addSuccessor(LoopBB); 3035 LoopBB->addSuccessor(RemainderBB); 3036 3037 // Move the rest of the block into a new block. 3038 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3039 3040 if (InstInLoop) { 3041 auto Next = std::next(I); 3042 3043 // Move instruction to loop body. 3044 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3045 3046 // Move the rest of the block. 3047 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3048 } else { 3049 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3050 } 3051 3052 MBB.addSuccessor(LoopBB); 3053 3054 return std::make_pair(LoopBB, RemainderBB); 3055 } 3056 3057 MachineBasicBlock * 3058 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3059 MachineBasicBlock *BB) const { 3060 const DebugLoc &DL = MI.getDebugLoc(); 3061 3062 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3063 3064 MachineBasicBlock *LoopBB; 3065 MachineBasicBlock *RemainderBB; 3066 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3067 3068 MachineBasicBlock::iterator Prev = std::prev(MI.getIterator()); 3069 3070 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3071 3072 MachineBasicBlock::iterator I = LoopBB->end(); 3073 MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0); 3074 3075 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3076 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3077 3078 // Clear TRAP_STS.MEM_VIOL 3079 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3080 .addImm(0) 3081 .addImm(EncodedReg); 3082 3083 // This is a pain, but we're not allowed to have physical register live-ins 3084 // yet. Insert a pair of copies if the VGPR0 hack is necessary. 3085 if (Src && TargetRegisterInfo::isPhysicalRegister(Src->getReg())) { 3086 unsigned Data0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3087 BuildMI(*BB, std::next(Prev), DL, TII->get(AMDGPU::COPY), Data0) 3088 .add(*Src); 3089 3090 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::COPY), Src->getReg()) 3091 .addReg(Data0); 3092 3093 MRI.setSimpleHint(Data0, Src->getReg()); 3094 } 3095 3096 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_WAITCNT)) 3097 .addImm(0); 3098 3099 unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3100 3101 // Load and check TRAP_STS.MEM_VIOL 3102 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3103 .addImm(EncodedReg); 3104 3105 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3106 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3107 .addReg(Reg, RegState::Kill) 3108 .addImm(0); 3109 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3110 .addMBB(LoopBB); 3111 3112 return RemainderBB; 3113 } 3114 3115 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3116 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3117 // will only do one iteration. In the worst case, this will loop 64 times. 3118 // 3119 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3120 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3121 const SIInstrInfo *TII, 3122 MachineRegisterInfo &MRI, 3123 MachineBasicBlock &OrigBB, 3124 MachineBasicBlock &LoopBB, 3125 const DebugLoc &DL, 3126 const MachineOperand &IdxReg, 3127 unsigned InitReg, 3128 unsigned ResultReg, 3129 unsigned PhiReg, 3130 unsigned InitSaveExecReg, 3131 int Offset, 3132 bool UseGPRIdxMode, 3133 bool IsIndirectSrc) { 3134 MachineFunction *MF = OrigBB.getParent(); 3135 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3136 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3137 MachineBasicBlock::iterator I = LoopBB.begin(); 3138 3139 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3140 unsigned PhiExec = MRI.createVirtualRegister(BoolRC); 3141 unsigned NewExec = MRI.createVirtualRegister(BoolRC); 3142 unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3143 unsigned CondReg = MRI.createVirtualRegister(BoolRC); 3144 3145 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3146 .addReg(InitReg) 3147 .addMBB(&OrigBB) 3148 .addReg(ResultReg) 3149 .addMBB(&LoopBB); 3150 3151 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3152 .addReg(InitSaveExecReg) 3153 .addMBB(&OrigBB) 3154 .addReg(NewExec) 3155 .addMBB(&LoopBB); 3156 3157 // Read the next variant <- also loop target. 3158 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3159 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3160 3161 // Compare the just read M0 value to all possible Idx values. 3162 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3163 .addReg(CurrentIdxReg) 3164 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3165 3166 // Update EXEC, save the original EXEC value to VCC. 3167 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3168 : AMDGPU::S_AND_SAVEEXEC_B64), 3169 NewExec) 3170 .addReg(CondReg, RegState::Kill); 3171 3172 MRI.setSimpleHint(NewExec, CondReg); 3173 3174 if (UseGPRIdxMode) { 3175 unsigned IdxReg; 3176 if (Offset == 0) { 3177 IdxReg = CurrentIdxReg; 3178 } else { 3179 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3180 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3181 .addReg(CurrentIdxReg, RegState::Kill) 3182 .addImm(Offset); 3183 } 3184 unsigned IdxMode = IsIndirectSrc ? 3185 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3186 MachineInstr *SetOn = 3187 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3188 .addReg(IdxReg, RegState::Kill) 3189 .addImm(IdxMode); 3190 SetOn->getOperand(3).setIsUndef(); 3191 } else { 3192 // Move index from VCC into M0 3193 if (Offset == 0) { 3194 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3195 .addReg(CurrentIdxReg, RegState::Kill); 3196 } else { 3197 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3198 .addReg(CurrentIdxReg, RegState::Kill) 3199 .addImm(Offset); 3200 } 3201 } 3202 3203 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3204 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3205 MachineInstr *InsertPt = 3206 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3207 : AMDGPU::S_XOR_B64_term), Exec) 3208 .addReg(Exec) 3209 .addReg(NewExec); 3210 3211 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3212 // s_cbranch_scc0? 3213 3214 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3215 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3216 .addMBB(&LoopBB); 3217 3218 return InsertPt->getIterator(); 3219 } 3220 3221 // This has slightly sub-optimal regalloc when the source vector is killed by 3222 // the read. The register allocator does not understand that the kill is 3223 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3224 // subregister from it, using 1 more VGPR than necessary. This was saved when 3225 // this was expanded after register allocation. 3226 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3227 MachineBasicBlock &MBB, 3228 MachineInstr &MI, 3229 unsigned InitResultReg, 3230 unsigned PhiReg, 3231 int Offset, 3232 bool UseGPRIdxMode, 3233 bool IsIndirectSrc) { 3234 MachineFunction *MF = MBB.getParent(); 3235 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3236 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3237 MachineRegisterInfo &MRI = MF->getRegInfo(); 3238 const DebugLoc &DL = MI.getDebugLoc(); 3239 MachineBasicBlock::iterator I(&MI); 3240 3241 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3242 unsigned DstReg = MI.getOperand(0).getReg(); 3243 unsigned SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3244 unsigned TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3245 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3246 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3247 3248 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3249 3250 // Save the EXEC mask 3251 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3252 .addReg(Exec); 3253 3254 MachineBasicBlock *LoopBB; 3255 MachineBasicBlock *RemainderBB; 3256 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3257 3258 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3259 3260 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3261 InitResultReg, DstReg, PhiReg, TmpExec, 3262 Offset, UseGPRIdxMode, IsIndirectSrc); 3263 3264 MachineBasicBlock::iterator First = RemainderBB->begin(); 3265 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3266 .addReg(SaveExec); 3267 3268 return InsPt; 3269 } 3270 3271 // Returns subreg index, offset 3272 static std::pair<unsigned, int> 3273 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3274 const TargetRegisterClass *SuperRC, 3275 unsigned VecReg, 3276 int Offset) { 3277 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3278 3279 // Skip out of bounds offsets, or else we would end up using an undefined 3280 // register. 3281 if (Offset >= NumElts || Offset < 0) 3282 return std::make_pair(AMDGPU::sub0, Offset); 3283 3284 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3285 } 3286 3287 // Return true if the index is an SGPR and was set. 3288 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3289 MachineRegisterInfo &MRI, 3290 MachineInstr &MI, 3291 int Offset, 3292 bool UseGPRIdxMode, 3293 bool IsIndirectSrc) { 3294 MachineBasicBlock *MBB = MI.getParent(); 3295 const DebugLoc &DL = MI.getDebugLoc(); 3296 MachineBasicBlock::iterator I(&MI); 3297 3298 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3299 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3300 3301 assert(Idx->getReg() != AMDGPU::NoRegister); 3302 3303 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3304 return false; 3305 3306 if (UseGPRIdxMode) { 3307 unsigned IdxMode = IsIndirectSrc ? 3308 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3309 if (Offset == 0) { 3310 MachineInstr *SetOn = 3311 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3312 .add(*Idx) 3313 .addImm(IdxMode); 3314 3315 SetOn->getOperand(3).setIsUndef(); 3316 } else { 3317 unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3318 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3319 .add(*Idx) 3320 .addImm(Offset); 3321 MachineInstr *SetOn = 3322 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3323 .addReg(Tmp, RegState::Kill) 3324 .addImm(IdxMode); 3325 3326 SetOn->getOperand(3).setIsUndef(); 3327 } 3328 3329 return true; 3330 } 3331 3332 if (Offset == 0) { 3333 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3334 .add(*Idx); 3335 } else { 3336 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3337 .add(*Idx) 3338 .addImm(Offset); 3339 } 3340 3341 return true; 3342 } 3343 3344 // Control flow needs to be inserted if indexing with a VGPR. 3345 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3346 MachineBasicBlock &MBB, 3347 const GCNSubtarget &ST) { 3348 const SIInstrInfo *TII = ST.getInstrInfo(); 3349 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3350 MachineFunction *MF = MBB.getParent(); 3351 MachineRegisterInfo &MRI = MF->getRegInfo(); 3352 3353 unsigned Dst = MI.getOperand(0).getReg(); 3354 unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3355 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3356 3357 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3358 3359 unsigned SubReg; 3360 std::tie(SubReg, Offset) 3361 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3362 3363 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3364 3365 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3366 MachineBasicBlock::iterator I(&MI); 3367 const DebugLoc &DL = MI.getDebugLoc(); 3368 3369 if (UseGPRIdxMode) { 3370 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3371 // to avoid interfering with other uses, so probably requires a new 3372 // optimization pass. 3373 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3374 .addReg(SrcReg, RegState::Undef, SubReg) 3375 .addReg(SrcReg, RegState::Implicit) 3376 .addReg(AMDGPU::M0, RegState::Implicit); 3377 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3378 } else { 3379 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3380 .addReg(SrcReg, RegState::Undef, SubReg) 3381 .addReg(SrcReg, RegState::Implicit); 3382 } 3383 3384 MI.eraseFromParent(); 3385 3386 return &MBB; 3387 } 3388 3389 const DebugLoc &DL = MI.getDebugLoc(); 3390 MachineBasicBlock::iterator I(&MI); 3391 3392 unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3393 unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3394 3395 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3396 3397 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3398 Offset, UseGPRIdxMode, true); 3399 MachineBasicBlock *LoopBB = InsPt->getParent(); 3400 3401 if (UseGPRIdxMode) { 3402 BuildMI(*LoopBB, InsPt, 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(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3407 } else { 3408 BuildMI(*LoopBB, InsPt, 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 LoopBB; 3416 } 3417 3418 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3419 const TargetRegisterClass *VecRC) { 3420 switch (TRI.getRegSizeInBits(*VecRC)) { 3421 case 32: // 4 bytes 3422 return AMDGPU::V_MOVRELD_B32_V1; 3423 case 64: // 8 bytes 3424 return AMDGPU::V_MOVRELD_B32_V2; 3425 case 128: // 16 bytes 3426 return AMDGPU::V_MOVRELD_B32_V4; 3427 case 256: // 32 bytes 3428 return AMDGPU::V_MOVRELD_B32_V8; 3429 case 512: // 64 bytes 3430 return AMDGPU::V_MOVRELD_B32_V16; 3431 default: 3432 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3433 } 3434 } 3435 3436 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3437 MachineBasicBlock &MBB, 3438 const GCNSubtarget &ST) { 3439 const SIInstrInfo *TII = ST.getInstrInfo(); 3440 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3441 MachineFunction *MF = MBB.getParent(); 3442 MachineRegisterInfo &MRI = MF->getRegInfo(); 3443 3444 unsigned Dst = MI.getOperand(0).getReg(); 3445 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3446 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3447 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3448 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3449 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3450 3451 // This can be an immediate, but will be folded later. 3452 assert(Val->getReg()); 3453 3454 unsigned SubReg; 3455 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3456 SrcVec->getReg(), 3457 Offset); 3458 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3459 3460 if (Idx->getReg() == AMDGPU::NoRegister) { 3461 MachineBasicBlock::iterator I(&MI); 3462 const DebugLoc &DL = MI.getDebugLoc(); 3463 3464 assert(Offset == 0); 3465 3466 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3467 .add(*SrcVec) 3468 .add(*Val) 3469 .addImm(SubReg); 3470 3471 MI.eraseFromParent(); 3472 return &MBB; 3473 } 3474 3475 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3476 MachineBasicBlock::iterator I(&MI); 3477 const DebugLoc &DL = MI.getDebugLoc(); 3478 3479 if (UseGPRIdxMode) { 3480 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3481 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3482 .add(*Val) 3483 .addReg(Dst, RegState::ImplicitDefine) 3484 .addReg(SrcVec->getReg(), RegState::Implicit) 3485 .addReg(AMDGPU::M0, RegState::Implicit); 3486 3487 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3488 } else { 3489 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3490 3491 BuildMI(MBB, I, DL, MovRelDesc) 3492 .addReg(Dst, RegState::Define) 3493 .addReg(SrcVec->getReg()) 3494 .add(*Val) 3495 .addImm(SubReg - AMDGPU::sub0); 3496 } 3497 3498 MI.eraseFromParent(); 3499 return &MBB; 3500 } 3501 3502 if (Val->isReg()) 3503 MRI.clearKillFlags(Val->getReg()); 3504 3505 const DebugLoc &DL = MI.getDebugLoc(); 3506 3507 unsigned PhiReg = MRI.createVirtualRegister(VecRC); 3508 3509 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3510 Offset, UseGPRIdxMode, false); 3511 MachineBasicBlock *LoopBB = InsPt->getParent(); 3512 3513 if (UseGPRIdxMode) { 3514 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3515 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3516 .add(*Val) // src0 3517 .addReg(Dst, RegState::ImplicitDefine) 3518 .addReg(PhiReg, RegState::Implicit) 3519 .addReg(AMDGPU::M0, RegState::Implicit); 3520 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3521 } else { 3522 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3523 3524 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3525 .addReg(Dst, RegState::Define) 3526 .addReg(PhiReg) 3527 .add(*Val) 3528 .addImm(SubReg - AMDGPU::sub0); 3529 } 3530 3531 MI.eraseFromParent(); 3532 3533 return LoopBB; 3534 } 3535 3536 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3537 MachineInstr &MI, MachineBasicBlock *BB) const { 3538 3539 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3540 MachineFunction *MF = BB->getParent(); 3541 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3542 3543 if (TII->isMIMG(MI)) { 3544 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3545 report_fatal_error("missing mem operand from MIMG instruction"); 3546 } 3547 // Add a memoperand for mimg instructions so that they aren't assumed to 3548 // be ordered memory instuctions. 3549 3550 return BB; 3551 } 3552 3553 switch (MI.getOpcode()) { 3554 case AMDGPU::S_ADD_U64_PSEUDO: 3555 case AMDGPU::S_SUB_U64_PSEUDO: { 3556 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3557 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3558 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3559 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3560 const DebugLoc &DL = MI.getDebugLoc(); 3561 3562 MachineOperand &Dest = MI.getOperand(0); 3563 MachineOperand &Src0 = MI.getOperand(1); 3564 MachineOperand &Src1 = MI.getOperand(2); 3565 3566 unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3567 unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3568 3569 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3570 Src0, BoolRC, AMDGPU::sub0, 3571 &AMDGPU::SReg_32_XM0RegClass); 3572 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3573 Src0, BoolRC, AMDGPU::sub1, 3574 &AMDGPU::SReg_32_XM0RegClass); 3575 3576 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3577 Src1, BoolRC, AMDGPU::sub0, 3578 &AMDGPU::SReg_32_XM0RegClass); 3579 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3580 Src1, BoolRC, AMDGPU::sub1, 3581 &AMDGPU::SReg_32_XM0RegClass); 3582 3583 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3584 3585 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3586 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3587 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3588 .add(Src0Sub0) 3589 .add(Src1Sub0); 3590 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3591 .add(Src0Sub1) 3592 .add(Src1Sub1); 3593 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3594 .addReg(DestSub0) 3595 .addImm(AMDGPU::sub0) 3596 .addReg(DestSub1) 3597 .addImm(AMDGPU::sub1); 3598 MI.eraseFromParent(); 3599 return BB; 3600 } 3601 case AMDGPU::SI_INIT_M0: { 3602 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3603 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3604 .add(MI.getOperand(0)); 3605 MI.eraseFromParent(); 3606 return BB; 3607 } 3608 case AMDGPU::SI_INIT_EXEC: 3609 // This should be before all vector instructions. 3610 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3611 AMDGPU::EXEC) 3612 .addImm(MI.getOperand(0).getImm()); 3613 MI.eraseFromParent(); 3614 return BB; 3615 3616 case AMDGPU::SI_INIT_EXEC_LO: 3617 // This should be before all vector instructions. 3618 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3619 AMDGPU::EXEC_LO) 3620 .addImm(MI.getOperand(0).getImm()); 3621 MI.eraseFromParent(); 3622 return BB; 3623 3624 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3625 // Extract the thread count from an SGPR input and set EXEC accordingly. 3626 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3627 // 3628 // S_BFE_U32 count, input, {shift, 7} 3629 // S_BFM_B64 exec, count, 0 3630 // S_CMP_EQ_U32 count, 64 3631 // S_CMOV_B64 exec, -1 3632 MachineInstr *FirstMI = &*BB->begin(); 3633 MachineRegisterInfo &MRI = MF->getRegInfo(); 3634 unsigned InputReg = MI.getOperand(0).getReg(); 3635 unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3636 bool Found = false; 3637 3638 // Move the COPY of the input reg to the beginning, so that we can use it. 3639 for (auto I = BB->begin(); I != &MI; I++) { 3640 if (I->getOpcode() != TargetOpcode::COPY || 3641 I->getOperand(0).getReg() != InputReg) 3642 continue; 3643 3644 if (I == FirstMI) { 3645 FirstMI = &*++BB->begin(); 3646 } else { 3647 I->removeFromParent(); 3648 BB->insert(FirstMI, &*I); 3649 } 3650 Found = true; 3651 break; 3652 } 3653 assert(Found); 3654 (void)Found; 3655 3656 // This should be before all vector instructions. 3657 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3658 bool isWave32 = getSubtarget()->isWave32(); 3659 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3660 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3661 .addReg(InputReg) 3662 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3663 BuildMI(*BB, FirstMI, DebugLoc(), 3664 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3665 Exec) 3666 .addReg(CountReg) 3667 .addImm(0); 3668 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3669 .addReg(CountReg, RegState::Kill) 3670 .addImm(getSubtarget()->getWavefrontSize()); 3671 BuildMI(*BB, FirstMI, DebugLoc(), 3672 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3673 Exec) 3674 .addImm(-1); 3675 MI.eraseFromParent(); 3676 return BB; 3677 } 3678 3679 case AMDGPU::GET_GROUPSTATICSIZE: { 3680 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3681 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3682 DebugLoc DL = MI.getDebugLoc(); 3683 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3684 .add(MI.getOperand(0)) 3685 .addImm(MFI->getLDSSize()); 3686 MI.eraseFromParent(); 3687 return BB; 3688 } 3689 case AMDGPU::SI_INDIRECT_SRC_V1: 3690 case AMDGPU::SI_INDIRECT_SRC_V2: 3691 case AMDGPU::SI_INDIRECT_SRC_V4: 3692 case AMDGPU::SI_INDIRECT_SRC_V8: 3693 case AMDGPU::SI_INDIRECT_SRC_V16: 3694 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3695 case AMDGPU::SI_INDIRECT_DST_V1: 3696 case AMDGPU::SI_INDIRECT_DST_V2: 3697 case AMDGPU::SI_INDIRECT_DST_V4: 3698 case AMDGPU::SI_INDIRECT_DST_V8: 3699 case AMDGPU::SI_INDIRECT_DST_V16: 3700 return emitIndirectDst(MI, *BB, *getSubtarget()); 3701 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3702 case AMDGPU::SI_KILL_I1_PSEUDO: 3703 return splitKillBlock(MI, BB); 3704 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3705 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3706 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3707 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3708 3709 unsigned Dst = MI.getOperand(0).getReg(); 3710 unsigned Src0 = MI.getOperand(1).getReg(); 3711 unsigned Src1 = MI.getOperand(2).getReg(); 3712 const DebugLoc &DL = MI.getDebugLoc(); 3713 unsigned SrcCond = MI.getOperand(3).getReg(); 3714 3715 unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3716 unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3717 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3718 unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC); 3719 3720 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3721 .addReg(SrcCond); 3722 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3723 .addImm(0) 3724 .addReg(Src0, 0, AMDGPU::sub0) 3725 .addImm(0) 3726 .addReg(Src1, 0, AMDGPU::sub0) 3727 .addReg(SrcCondCopy); 3728 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3729 .addImm(0) 3730 .addReg(Src0, 0, AMDGPU::sub1) 3731 .addImm(0) 3732 .addReg(Src1, 0, AMDGPU::sub1) 3733 .addReg(SrcCondCopy); 3734 3735 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3736 .addReg(DstLo) 3737 .addImm(AMDGPU::sub0) 3738 .addReg(DstHi) 3739 .addImm(AMDGPU::sub1); 3740 MI.eraseFromParent(); 3741 return BB; 3742 } 3743 case AMDGPU::SI_BR_UNDEF: { 3744 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3745 const DebugLoc &DL = MI.getDebugLoc(); 3746 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3747 .add(MI.getOperand(0)); 3748 Br->getOperand(1).setIsUndef(true); // read undef SCC 3749 MI.eraseFromParent(); 3750 return BB; 3751 } 3752 case AMDGPU::ADJCALLSTACKUP: 3753 case AMDGPU::ADJCALLSTACKDOWN: { 3754 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3755 MachineInstrBuilder MIB(*MF, &MI); 3756 3757 // Add an implicit use of the frame offset reg to prevent the restore copy 3758 // inserted after the call from being reorderd after stack operations in the 3759 // the caller's frame. 3760 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3761 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3762 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3763 return BB; 3764 } 3765 case AMDGPU::SI_CALL_ISEL: { 3766 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3767 const DebugLoc &DL = MI.getDebugLoc(); 3768 3769 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3770 3771 MachineInstrBuilder MIB; 3772 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3773 3774 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3775 MIB.add(MI.getOperand(I)); 3776 3777 MIB.cloneMemRefs(MI); 3778 MI.eraseFromParent(); 3779 return BB; 3780 } 3781 case AMDGPU::V_ADD_I32_e32: 3782 case AMDGPU::V_SUB_I32_e32: 3783 case AMDGPU::V_SUBREV_I32_e32: { 3784 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3785 const DebugLoc &DL = MI.getDebugLoc(); 3786 unsigned Opc = MI.getOpcode(); 3787 3788 bool NeedClampOperand = false; 3789 if (TII->pseudoToMCOpcode(Opc) == -1) { 3790 Opc = AMDGPU::getVOPe64(Opc); 3791 NeedClampOperand = true; 3792 } 3793 3794 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3795 if (TII->isVOP3(*I)) { 3796 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3797 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3798 I.addReg(TRI->getVCC(), RegState::Define); 3799 } 3800 I.add(MI.getOperand(1)) 3801 .add(MI.getOperand(2)); 3802 if (NeedClampOperand) 3803 I.addImm(0); // clamp bit for e64 encoding 3804 3805 TII->legalizeOperands(*I); 3806 3807 MI.eraseFromParent(); 3808 return BB; 3809 } 3810 case AMDGPU::DS_GWS_INIT: 3811 case AMDGPU::DS_GWS_SEMA_V: 3812 case AMDGPU::DS_GWS_SEMA_BR: 3813 case AMDGPU::DS_GWS_SEMA_P: 3814 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3815 case AMDGPU::DS_GWS_BARRIER: 3816 if (getSubtarget()->hasGWSAutoReplay()) 3817 return BB; 3818 return emitGWSMemViolTestLoop(MI, BB); 3819 default: 3820 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3821 } 3822 } 3823 3824 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3825 return isTypeLegal(VT.getScalarType()); 3826 } 3827 3828 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3829 // This currently forces unfolding various combinations of fsub into fma with 3830 // free fneg'd operands. As long as we have fast FMA (controlled by 3831 // isFMAFasterThanFMulAndFAdd), we should perform these. 3832 3833 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3834 // most of these combines appear to be cycle neutral but save on instruction 3835 // count / code size. 3836 return true; 3837 } 3838 3839 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3840 EVT VT) const { 3841 if (!VT.isVector()) { 3842 return MVT::i1; 3843 } 3844 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3845 } 3846 3847 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3848 // TODO: Should i16 be used always if legal? For now it would force VALU 3849 // shifts. 3850 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3851 } 3852 3853 // Answering this is somewhat tricky and depends on the specific device which 3854 // have different rates for fma or all f64 operations. 3855 // 3856 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3857 // regardless of which device (although the number of cycles differs between 3858 // devices), so it is always profitable for f64. 3859 // 3860 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3861 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3862 // which we can always do even without fused FP ops since it returns the same 3863 // result as the separate operations and since it is always full 3864 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3865 // however does not support denormals, so we do report fma as faster if we have 3866 // a fast fma device and require denormals. 3867 // 3868 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 3869 VT = VT.getScalarType(); 3870 3871 switch (VT.getSimpleVT().SimpleTy) { 3872 case MVT::f32: { 3873 // This is as fast on some subtargets. However, we always have full rate f32 3874 // mad available which returns the same result as the separate operations 3875 // which we should prefer over fma. We can't use this if we want to support 3876 // denormals, so only report this in these cases. 3877 if (Subtarget->hasFP32Denormals()) 3878 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3879 3880 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3881 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3882 } 3883 case MVT::f64: 3884 return true; 3885 case MVT::f16: 3886 return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals(); 3887 default: 3888 break; 3889 } 3890 3891 return false; 3892 } 3893 3894 //===----------------------------------------------------------------------===// 3895 // Custom DAG Lowering Operations 3896 //===----------------------------------------------------------------------===// 3897 3898 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3899 // wider vector type is legal. 3900 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3901 SelectionDAG &DAG) const { 3902 unsigned Opc = Op.getOpcode(); 3903 EVT VT = Op.getValueType(); 3904 assert(VT == MVT::v4f16); 3905 3906 SDValue Lo, Hi; 3907 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3908 3909 SDLoc SL(Op); 3910 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3911 Op->getFlags()); 3912 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3913 Op->getFlags()); 3914 3915 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3916 } 3917 3918 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3919 // wider vector type is legal. 3920 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3921 SelectionDAG &DAG) const { 3922 unsigned Opc = Op.getOpcode(); 3923 EVT VT = Op.getValueType(); 3924 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3925 3926 SDValue Lo0, Hi0; 3927 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3928 SDValue Lo1, Hi1; 3929 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3930 3931 SDLoc SL(Op); 3932 3933 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3934 Op->getFlags()); 3935 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3936 Op->getFlags()); 3937 3938 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3939 } 3940 3941 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3942 switch (Op.getOpcode()) { 3943 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3944 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3945 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 3946 case ISD::LOAD: { 3947 SDValue Result = LowerLOAD(Op, DAG); 3948 assert((!Result.getNode() || 3949 Result.getNode()->getNumValues() == 2) && 3950 "Load should return a value and a chain"); 3951 return Result; 3952 } 3953 3954 case ISD::FSIN: 3955 case ISD::FCOS: 3956 return LowerTrig(Op, DAG); 3957 case ISD::SELECT: return LowerSELECT(Op, DAG); 3958 case ISD::FDIV: return LowerFDIV(Op, DAG); 3959 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3960 case ISD::STORE: return LowerSTORE(Op, DAG); 3961 case ISD::GlobalAddress: { 3962 MachineFunction &MF = DAG.getMachineFunction(); 3963 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 3964 return LowerGlobalAddress(MFI, Op, DAG); 3965 } 3966 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3967 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 3968 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 3969 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 3970 case ISD::INSERT_SUBVECTOR: 3971 return lowerINSERT_SUBVECTOR(Op, DAG); 3972 case ISD::INSERT_VECTOR_ELT: 3973 return lowerINSERT_VECTOR_ELT(Op, DAG); 3974 case ISD::EXTRACT_VECTOR_ELT: 3975 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3976 case ISD::VECTOR_SHUFFLE: 3977 return lowerVECTOR_SHUFFLE(Op, DAG); 3978 case ISD::BUILD_VECTOR: 3979 return lowerBUILD_VECTOR(Op, DAG); 3980 case ISD::FP_ROUND: 3981 return lowerFP_ROUND(Op, DAG); 3982 case ISD::TRAP: 3983 return lowerTRAP(Op, DAG); 3984 case ISD::DEBUGTRAP: 3985 return lowerDEBUGTRAP(Op, DAG); 3986 case ISD::FABS: 3987 case ISD::FNEG: 3988 case ISD::FCANONICALIZE: 3989 return splitUnaryVectorOp(Op, DAG); 3990 case ISD::FMINNUM: 3991 case ISD::FMAXNUM: 3992 return lowerFMINNUM_FMAXNUM(Op, DAG); 3993 case ISD::SHL: 3994 case ISD::SRA: 3995 case ISD::SRL: 3996 case ISD::ADD: 3997 case ISD::SUB: 3998 case ISD::MUL: 3999 case ISD::SMIN: 4000 case ISD::SMAX: 4001 case ISD::UMIN: 4002 case ISD::UMAX: 4003 case ISD::FADD: 4004 case ISD::FMUL: 4005 case ISD::FMINNUM_IEEE: 4006 case ISD::FMAXNUM_IEEE: 4007 return splitBinaryVectorOp(Op, DAG); 4008 } 4009 return SDValue(); 4010 } 4011 4012 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4013 const SDLoc &DL, 4014 SelectionDAG &DAG, bool Unpacked) { 4015 if (!LoadVT.isVector()) 4016 return Result; 4017 4018 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4019 // Truncate to v2i16/v4i16. 4020 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4021 4022 // Workaround legalizer not scalarizing truncate after vector op 4023 // legalization byt not creating intermediate vector trunc. 4024 SmallVector<SDValue, 4> Elts; 4025 DAG.ExtractVectorElements(Result, Elts); 4026 for (SDValue &Elt : Elts) 4027 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4028 4029 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4030 4031 // Bitcast to original type (v2f16/v4f16). 4032 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4033 } 4034 4035 // Cast back to the original packed type. 4036 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4037 } 4038 4039 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4040 MemSDNode *M, 4041 SelectionDAG &DAG, 4042 ArrayRef<SDValue> Ops, 4043 bool IsIntrinsic) const { 4044 SDLoc DL(M); 4045 4046 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4047 EVT LoadVT = M->getValueType(0); 4048 4049 EVT EquivLoadVT = LoadVT; 4050 if (Unpacked && LoadVT.isVector()) { 4051 EquivLoadVT = LoadVT.isVector() ? 4052 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4053 LoadVT.getVectorNumElements()) : LoadVT; 4054 } 4055 4056 // Change from v4f16/v2f16 to EquivLoadVT. 4057 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4058 4059 SDValue Load 4060 = DAG.getMemIntrinsicNode( 4061 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4062 VTList, Ops, M->getMemoryVT(), 4063 M->getMemOperand()); 4064 if (!Unpacked) // Just adjusted the opcode. 4065 return Load; 4066 4067 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4068 4069 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4070 } 4071 4072 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4073 SDNode *N, SelectionDAG &DAG) { 4074 EVT VT = N->getValueType(0); 4075 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4076 int CondCode = CD->getSExtValue(); 4077 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4078 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4079 return DAG.getUNDEF(VT); 4080 4081 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4082 4083 SDValue LHS = N->getOperand(1); 4084 SDValue RHS = N->getOperand(2); 4085 4086 SDLoc DL(N); 4087 4088 EVT CmpVT = LHS.getValueType(); 4089 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4090 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4091 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4092 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4093 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4094 } 4095 4096 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4097 4098 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4099 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4100 4101 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4102 DAG.getCondCode(CCOpcode)); 4103 if (VT.bitsEq(CCVT)) 4104 return SetCC; 4105 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4106 } 4107 4108 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4109 SDNode *N, SelectionDAG &DAG) { 4110 EVT VT = N->getValueType(0); 4111 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4112 4113 int CondCode = CD->getSExtValue(); 4114 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4115 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4116 return DAG.getUNDEF(VT); 4117 } 4118 4119 SDValue Src0 = N->getOperand(1); 4120 SDValue Src1 = N->getOperand(2); 4121 EVT CmpVT = Src0.getValueType(); 4122 SDLoc SL(N); 4123 4124 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4125 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4126 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4127 } 4128 4129 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4130 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4131 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4132 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4133 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4134 Src1, DAG.getCondCode(CCOpcode)); 4135 if (VT.bitsEq(CCVT)) 4136 return SetCC; 4137 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4138 } 4139 4140 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4141 SmallVectorImpl<SDValue> &Results, 4142 SelectionDAG &DAG) const { 4143 switch (N->getOpcode()) { 4144 case ISD::INSERT_VECTOR_ELT: { 4145 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4146 Results.push_back(Res); 4147 return; 4148 } 4149 case ISD::EXTRACT_VECTOR_ELT: { 4150 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4151 Results.push_back(Res); 4152 return; 4153 } 4154 case ISD::INTRINSIC_WO_CHAIN: { 4155 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4156 switch (IID) { 4157 case Intrinsic::amdgcn_cvt_pkrtz: { 4158 SDValue Src0 = N->getOperand(1); 4159 SDValue Src1 = N->getOperand(2); 4160 SDLoc SL(N); 4161 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4162 Src0, Src1); 4163 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4164 return; 4165 } 4166 case Intrinsic::amdgcn_cvt_pknorm_i16: 4167 case Intrinsic::amdgcn_cvt_pknorm_u16: 4168 case Intrinsic::amdgcn_cvt_pk_i16: 4169 case Intrinsic::amdgcn_cvt_pk_u16: { 4170 SDValue Src0 = N->getOperand(1); 4171 SDValue Src1 = N->getOperand(2); 4172 SDLoc SL(N); 4173 unsigned Opcode; 4174 4175 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4176 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4177 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4178 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4179 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4180 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4181 else 4182 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4183 4184 EVT VT = N->getValueType(0); 4185 if (isTypeLegal(VT)) 4186 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4187 else { 4188 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4189 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4190 } 4191 return; 4192 } 4193 } 4194 break; 4195 } 4196 case ISD::INTRINSIC_W_CHAIN: { 4197 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4198 Results.push_back(Res); 4199 Results.push_back(Res.getValue(1)); 4200 return; 4201 } 4202 4203 break; 4204 } 4205 case ISD::SELECT: { 4206 SDLoc SL(N); 4207 EVT VT = N->getValueType(0); 4208 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4209 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4210 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4211 4212 EVT SelectVT = NewVT; 4213 if (NewVT.bitsLT(MVT::i32)) { 4214 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4215 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4216 SelectVT = MVT::i32; 4217 } 4218 4219 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4220 N->getOperand(0), LHS, RHS); 4221 4222 if (NewVT != SelectVT) 4223 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4224 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4225 return; 4226 } 4227 case ISD::FNEG: { 4228 if (N->getValueType(0) != MVT::v2f16) 4229 break; 4230 4231 SDLoc SL(N); 4232 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4233 4234 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4235 BC, 4236 DAG.getConstant(0x80008000, SL, MVT::i32)); 4237 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4238 return; 4239 } 4240 case ISD::FABS: { 4241 if (N->getValueType(0) != MVT::v2f16) 4242 break; 4243 4244 SDLoc SL(N); 4245 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4246 4247 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4248 BC, 4249 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4250 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4251 return; 4252 } 4253 default: 4254 break; 4255 } 4256 } 4257 4258 /// Helper function for LowerBRCOND 4259 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4260 4261 SDNode *Parent = Value.getNode(); 4262 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4263 I != E; ++I) { 4264 4265 if (I.getUse().get() != Value) 4266 continue; 4267 4268 if (I->getOpcode() == Opcode) 4269 return *I; 4270 } 4271 return nullptr; 4272 } 4273 4274 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4275 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4276 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4277 case Intrinsic::amdgcn_if: 4278 return AMDGPUISD::IF; 4279 case Intrinsic::amdgcn_else: 4280 return AMDGPUISD::ELSE; 4281 case Intrinsic::amdgcn_loop: 4282 return AMDGPUISD::LOOP; 4283 case Intrinsic::amdgcn_end_cf: 4284 llvm_unreachable("should not occur"); 4285 default: 4286 return 0; 4287 } 4288 } 4289 4290 // break, if_break, else_break are all only used as inputs to loop, not 4291 // directly as branch conditions. 4292 return 0; 4293 } 4294 4295 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4296 const Triple &TT = getTargetMachine().getTargetTriple(); 4297 return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4298 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4299 AMDGPU::shouldEmitConstantsToTextSection(TT); 4300 } 4301 4302 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4303 // FIXME: Either avoid relying on address space here or change the default 4304 // address space for functions to avoid the explicit check. 4305 return (GV->getValueType()->isFunctionTy() || 4306 GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4307 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4308 GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4309 !shouldEmitFixup(GV) && 4310 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4311 } 4312 4313 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4314 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4315 } 4316 4317 /// This transforms the control flow intrinsics to get the branch destination as 4318 /// last parameter, also switches branch target with BR if the need arise 4319 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4320 SelectionDAG &DAG) const { 4321 SDLoc DL(BRCOND); 4322 4323 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4324 SDValue Target = BRCOND.getOperand(2); 4325 SDNode *BR = nullptr; 4326 SDNode *SetCC = nullptr; 4327 4328 if (Intr->getOpcode() == ISD::SETCC) { 4329 // As long as we negate the condition everything is fine 4330 SetCC = Intr; 4331 Intr = SetCC->getOperand(0).getNode(); 4332 4333 } else { 4334 // Get the target from BR if we don't negate the condition 4335 BR = findUser(BRCOND, ISD::BR); 4336 Target = BR->getOperand(1); 4337 } 4338 4339 // FIXME: This changes the types of the intrinsics instead of introducing new 4340 // nodes with the correct types. 4341 // e.g. llvm.amdgcn.loop 4342 4343 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4344 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4345 4346 unsigned CFNode = isCFIntrinsic(Intr); 4347 if (CFNode == 0) { 4348 // This is a uniform branch so we don't need to legalize. 4349 return BRCOND; 4350 } 4351 4352 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4353 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4354 4355 assert(!SetCC || 4356 (SetCC->getConstantOperandVal(1) == 1 && 4357 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4358 ISD::SETNE)); 4359 4360 // operands of the new intrinsic call 4361 SmallVector<SDValue, 4> Ops; 4362 if (HaveChain) 4363 Ops.push_back(BRCOND.getOperand(0)); 4364 4365 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4366 Ops.push_back(Target); 4367 4368 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4369 4370 // build the new intrinsic call 4371 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4372 4373 if (!HaveChain) { 4374 SDValue Ops[] = { 4375 SDValue(Result, 0), 4376 BRCOND.getOperand(0) 4377 }; 4378 4379 Result = DAG.getMergeValues(Ops, DL).getNode(); 4380 } 4381 4382 if (BR) { 4383 // Give the branch instruction our target 4384 SDValue Ops[] = { 4385 BR->getOperand(0), 4386 BRCOND.getOperand(2) 4387 }; 4388 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4389 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4390 BR = NewBR.getNode(); 4391 } 4392 4393 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4394 4395 // Copy the intrinsic results to registers 4396 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4397 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4398 if (!CopyToReg) 4399 continue; 4400 4401 Chain = DAG.getCopyToReg( 4402 Chain, DL, 4403 CopyToReg->getOperand(1), 4404 SDValue(Result, i - 1), 4405 SDValue()); 4406 4407 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4408 } 4409 4410 // Remove the old intrinsic from the chain 4411 DAG.ReplaceAllUsesOfValueWith( 4412 SDValue(Intr, Intr->getNumValues() - 1), 4413 Intr->getOperand(0)); 4414 4415 return Chain; 4416 } 4417 4418 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4419 SelectionDAG &DAG) const { 4420 MVT VT = Op.getSimpleValueType(); 4421 SDLoc DL(Op); 4422 // Checking the depth 4423 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4424 return DAG.getConstant(0, DL, VT); 4425 4426 MachineFunction &MF = DAG.getMachineFunction(); 4427 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4428 // Check for kernel and shader functions 4429 if (Info->isEntryFunction()) 4430 return DAG.getConstant(0, DL, VT); 4431 4432 MachineFrameInfo &MFI = MF.getFrameInfo(); 4433 // There is a call to @llvm.returnaddress in this function 4434 MFI.setReturnAddressIsTaken(true); 4435 4436 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4437 // Get the return address reg and mark it as an implicit live-in 4438 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4439 4440 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4441 } 4442 4443 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4444 SDValue Op, 4445 const SDLoc &DL, 4446 EVT VT) const { 4447 return Op.getValueType().bitsLE(VT) ? 4448 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4449 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4450 } 4451 4452 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4453 assert(Op.getValueType() == MVT::f16 && 4454 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4455 4456 SDValue Src = Op.getOperand(0); 4457 EVT SrcVT = Src.getValueType(); 4458 if (SrcVT != MVT::f64) 4459 return Op; 4460 4461 SDLoc DL(Op); 4462 4463 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4464 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4465 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4466 } 4467 4468 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4469 SelectionDAG &DAG) const { 4470 EVT VT = Op.getValueType(); 4471 const MachineFunction &MF = DAG.getMachineFunction(); 4472 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4473 bool IsIEEEMode = Info->getMode().IEEE; 4474 4475 // FIXME: Assert during eslection that this is only selected for 4476 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4477 // mode functions, but this happens to be OK since it's only done in cases 4478 // where there is known no sNaN. 4479 if (IsIEEEMode) 4480 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4481 4482 if (VT == MVT::v4f16) 4483 return splitBinaryVectorOp(Op, DAG); 4484 return Op; 4485 } 4486 4487 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4488 SDLoc SL(Op); 4489 SDValue Chain = Op.getOperand(0); 4490 4491 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4492 !Subtarget->isTrapHandlerEnabled()) 4493 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4494 4495 MachineFunction &MF = DAG.getMachineFunction(); 4496 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4497 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4498 assert(UserSGPR != AMDGPU::NoRegister); 4499 SDValue QueuePtr = CreateLiveInRegister( 4500 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4501 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4502 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4503 QueuePtr, SDValue()); 4504 SDValue Ops[] = { 4505 ToReg, 4506 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4507 SGPR01, 4508 ToReg.getValue(1) 4509 }; 4510 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4511 } 4512 4513 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4514 SDLoc SL(Op); 4515 SDValue Chain = Op.getOperand(0); 4516 MachineFunction &MF = DAG.getMachineFunction(); 4517 4518 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4519 !Subtarget->isTrapHandlerEnabled()) { 4520 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4521 "debugtrap handler not supported", 4522 Op.getDebugLoc(), 4523 DS_Warning); 4524 LLVMContext &Ctx = MF.getFunction().getContext(); 4525 Ctx.diagnose(NoTrap); 4526 return Chain; 4527 } 4528 4529 SDValue Ops[] = { 4530 Chain, 4531 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4532 }; 4533 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4534 } 4535 4536 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4537 SelectionDAG &DAG) const { 4538 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4539 if (Subtarget->hasApertureRegs()) { 4540 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4541 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4542 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4543 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4544 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4545 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4546 unsigned Encoding = 4547 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4548 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4549 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4550 4551 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4552 SDValue ApertureReg = SDValue( 4553 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4554 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4555 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4556 } 4557 4558 MachineFunction &MF = DAG.getMachineFunction(); 4559 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4560 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4561 assert(UserSGPR != AMDGPU::NoRegister); 4562 4563 SDValue QueuePtr = CreateLiveInRegister( 4564 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4565 4566 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4567 // private_segment_aperture_base_hi. 4568 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4569 4570 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4571 4572 // TODO: Use custom target PseudoSourceValue. 4573 // TODO: We should use the value from the IR intrinsic call, but it might not 4574 // be available and how do we get it? 4575 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4576 AMDGPUAS::CONSTANT_ADDRESS)); 4577 4578 MachinePointerInfo PtrInfo(V, StructOffset); 4579 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4580 MinAlign(64, StructOffset), 4581 MachineMemOperand::MODereferenceable | 4582 MachineMemOperand::MOInvariant); 4583 } 4584 4585 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4586 SelectionDAG &DAG) const { 4587 SDLoc SL(Op); 4588 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4589 4590 SDValue Src = ASC->getOperand(0); 4591 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4592 4593 const AMDGPUTargetMachine &TM = 4594 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4595 4596 // flat -> local/private 4597 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4598 unsigned DestAS = ASC->getDestAddressSpace(); 4599 4600 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4601 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4602 unsigned NullVal = TM.getNullPointerValue(DestAS); 4603 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4604 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4605 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4606 4607 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4608 NonNull, Ptr, SegmentNullPtr); 4609 } 4610 } 4611 4612 // local/private -> flat 4613 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4614 unsigned SrcAS = ASC->getSrcAddressSpace(); 4615 4616 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4617 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4618 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4619 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4620 4621 SDValue NonNull 4622 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4623 4624 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4625 SDValue CvtPtr 4626 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4627 4628 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4629 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4630 FlatNullPtr); 4631 } 4632 } 4633 4634 // global <-> flat are no-ops and never emitted. 4635 4636 const MachineFunction &MF = DAG.getMachineFunction(); 4637 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4638 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4639 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4640 4641 return DAG.getUNDEF(ASC->getValueType(0)); 4642 } 4643 4644 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4645 // the small vector and inserting them into the big vector. That is better than 4646 // the default expansion of doing it via a stack slot. Even though the use of 4647 // the stack slot would be optimized away afterwards, the stack slot itself 4648 // remains. 4649 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4650 SelectionDAG &DAG) const { 4651 SDValue Vec = Op.getOperand(0); 4652 SDValue Ins = Op.getOperand(1); 4653 SDValue Idx = Op.getOperand(2); 4654 EVT VecVT = Vec.getValueType(); 4655 EVT InsVT = Ins.getValueType(); 4656 EVT EltVT = VecVT.getVectorElementType(); 4657 unsigned InsNumElts = InsVT.getVectorNumElements(); 4658 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4659 SDLoc SL(Op); 4660 4661 for (unsigned I = 0; I != InsNumElts; ++I) { 4662 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4663 DAG.getConstant(I, SL, MVT::i32)); 4664 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4665 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4666 } 4667 return Vec; 4668 } 4669 4670 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4671 SelectionDAG &DAG) const { 4672 SDValue Vec = Op.getOperand(0); 4673 SDValue InsVal = Op.getOperand(1); 4674 SDValue Idx = Op.getOperand(2); 4675 EVT VecVT = Vec.getValueType(); 4676 EVT EltVT = VecVT.getVectorElementType(); 4677 unsigned VecSize = VecVT.getSizeInBits(); 4678 unsigned EltSize = EltVT.getSizeInBits(); 4679 4680 4681 assert(VecSize <= 64); 4682 4683 unsigned NumElts = VecVT.getVectorNumElements(); 4684 SDLoc SL(Op); 4685 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4686 4687 if (NumElts == 4 && EltSize == 16 && KIdx) { 4688 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4689 4690 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4691 DAG.getConstant(0, SL, MVT::i32)); 4692 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4693 DAG.getConstant(1, SL, MVT::i32)); 4694 4695 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4696 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4697 4698 unsigned Idx = KIdx->getZExtValue(); 4699 bool InsertLo = Idx < 2; 4700 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4701 InsertLo ? LoVec : HiVec, 4702 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4703 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4704 4705 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4706 4707 SDValue Concat = InsertLo ? 4708 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4709 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4710 4711 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4712 } 4713 4714 if (isa<ConstantSDNode>(Idx)) 4715 return SDValue(); 4716 4717 MVT IntVT = MVT::getIntegerVT(VecSize); 4718 4719 // Avoid stack access for dynamic indexing. 4720 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4721 4722 // Create a congruent vector with the target value in each element so that 4723 // the required element can be masked and ORed into the target vector. 4724 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4725 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4726 4727 assert(isPowerOf2_32(EltSize)); 4728 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4729 4730 // Convert vector index to bit-index. 4731 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4732 4733 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4734 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4735 DAG.getConstant(0xffff, SL, IntVT), 4736 ScaledIdx); 4737 4738 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4739 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4740 DAG.getNOT(SL, BFM, IntVT), BCVec); 4741 4742 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4743 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4744 } 4745 4746 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4747 SelectionDAG &DAG) const { 4748 SDLoc SL(Op); 4749 4750 EVT ResultVT = Op.getValueType(); 4751 SDValue Vec = Op.getOperand(0); 4752 SDValue Idx = Op.getOperand(1); 4753 EVT VecVT = Vec.getValueType(); 4754 unsigned VecSize = VecVT.getSizeInBits(); 4755 EVT EltVT = VecVT.getVectorElementType(); 4756 assert(VecSize <= 64); 4757 4758 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4759 4760 // Make sure we do any optimizations that will make it easier to fold 4761 // source modifiers before obscuring it with bit operations. 4762 4763 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4764 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4765 return Combined; 4766 4767 unsigned EltSize = EltVT.getSizeInBits(); 4768 assert(isPowerOf2_32(EltSize)); 4769 4770 MVT IntVT = MVT::getIntegerVT(VecSize); 4771 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4772 4773 // Convert vector index to bit-index (* EltSize) 4774 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4775 4776 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4777 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4778 4779 if (ResultVT == MVT::f16) { 4780 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4781 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4782 } 4783 4784 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4785 } 4786 4787 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4788 assert(Elt % 2 == 0); 4789 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4790 } 4791 4792 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4793 SelectionDAG &DAG) const { 4794 SDLoc SL(Op); 4795 EVT ResultVT = Op.getValueType(); 4796 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4797 4798 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4799 EVT EltVT = PackVT.getVectorElementType(); 4800 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4801 4802 // vector_shuffle <0,1,6,7> lhs, rhs 4803 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4804 // 4805 // vector_shuffle <6,7,2,3> lhs, rhs 4806 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4807 // 4808 // vector_shuffle <6,7,0,1> lhs, rhs 4809 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4810 4811 // Avoid scalarizing when both halves are reading from consecutive elements. 4812 SmallVector<SDValue, 4> Pieces; 4813 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4814 if (elementPairIsContiguous(SVN->getMask(), I)) { 4815 const int Idx = SVN->getMaskElt(I); 4816 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4817 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4818 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4819 PackVT, SVN->getOperand(VecIdx), 4820 DAG.getConstant(EltIdx, SL, MVT::i32)); 4821 Pieces.push_back(SubVec); 4822 } else { 4823 const int Idx0 = SVN->getMaskElt(I); 4824 const int Idx1 = SVN->getMaskElt(I + 1); 4825 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4826 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4827 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4828 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4829 4830 SDValue Vec0 = SVN->getOperand(VecIdx0); 4831 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4832 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4833 4834 SDValue Vec1 = SVN->getOperand(VecIdx1); 4835 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4836 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4837 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4838 } 4839 } 4840 4841 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4842 } 4843 4844 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4845 SelectionDAG &DAG) const { 4846 SDLoc SL(Op); 4847 EVT VT = Op.getValueType(); 4848 4849 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4850 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4851 4852 // Turn into pair of packed build_vectors. 4853 // TODO: Special case for constants that can be materialized with s_mov_b64. 4854 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4855 { Op.getOperand(0), Op.getOperand(1) }); 4856 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4857 { Op.getOperand(2), Op.getOperand(3) }); 4858 4859 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4860 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4861 4862 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4863 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4864 } 4865 4866 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4867 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4868 4869 SDValue Lo = Op.getOperand(0); 4870 SDValue Hi = Op.getOperand(1); 4871 4872 // Avoid adding defined bits with the zero_extend. 4873 if (Hi.isUndef()) { 4874 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4875 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4876 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4877 } 4878 4879 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4880 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4881 4882 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4883 DAG.getConstant(16, SL, MVT::i32)); 4884 if (Lo.isUndef()) 4885 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4886 4887 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4888 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4889 4890 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4891 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4892 } 4893 4894 bool 4895 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4896 // We can fold offsets for anything that doesn't require a GOT relocation. 4897 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4898 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4899 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4900 !shouldEmitGOTReloc(GA->getGlobal()); 4901 } 4902 4903 static SDValue 4904 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4905 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4906 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4907 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4908 // lowered to the following code sequence: 4909 // 4910 // For constant address space: 4911 // s_getpc_b64 s[0:1] 4912 // s_add_u32 s0, s0, $symbol 4913 // s_addc_u32 s1, s1, 0 4914 // 4915 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4916 // a fixup or relocation is emitted to replace $symbol with a literal 4917 // constant, which is a pc-relative offset from the encoding of the $symbol 4918 // operand to the global variable. 4919 // 4920 // For global address space: 4921 // s_getpc_b64 s[0:1] 4922 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 4923 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 4924 // 4925 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 4926 // fixups or relocations are emitted to replace $symbol@*@lo and 4927 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 4928 // which is a 64-bit pc-relative offset from the encoding of the $symbol 4929 // operand to the global variable. 4930 // 4931 // What we want here is an offset from the value returned by s_getpc 4932 // (which is the address of the s_add_u32 instruction) to the global 4933 // variable, but since the encoding of $symbol starts 4 bytes after the start 4934 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 4935 // small. This requires us to add 4 to the global variable offset in order to 4936 // compute the correct address. 4937 unsigned LoFlags = GAFlags; 4938 if (LoFlags == SIInstrInfo::MO_NONE) 4939 LoFlags = SIInstrInfo::MO_REL32; 4940 SDValue PtrLo = 4941 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags); 4942 SDValue PtrHi; 4943 if (GAFlags == SIInstrInfo::MO_NONE) { 4944 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 4945 } else { 4946 PtrHi = 4947 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 4948 } 4949 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 4950 } 4951 4952 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 4953 SDValue Op, 4954 SelectionDAG &DAG) const { 4955 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 4956 const GlobalValue *GV = GSD->getGlobal(); 4957 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 4958 (!GV->hasExternalLinkage() || 4959 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4960 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 4961 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 4962 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 4963 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 4964 4965 SDLoc DL(GSD); 4966 EVT PtrVT = Op.getValueType(); 4967 4968 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 4969 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 4970 SIInstrInfo::MO_ABS32_LO); 4971 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 4972 } 4973 4974 if (shouldEmitFixup(GV)) 4975 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 4976 else if (shouldEmitPCReloc(GV)) 4977 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 4978 SIInstrInfo::MO_REL32); 4979 4980 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 4981 SIInstrInfo::MO_GOTPCREL32); 4982 4983 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 4984 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 4985 const DataLayout &DataLayout = DAG.getDataLayout(); 4986 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 4987 MachinePointerInfo PtrInfo 4988 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 4989 4990 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 4991 MachineMemOperand::MODereferenceable | 4992 MachineMemOperand::MOInvariant); 4993 } 4994 4995 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 4996 const SDLoc &DL, SDValue V) const { 4997 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 4998 // the destination register. 4999 // 5000 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5001 // so we will end up with redundant moves to m0. 5002 // 5003 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5004 5005 // A Null SDValue creates a glue result. 5006 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5007 V, Chain); 5008 return SDValue(M0, 0); 5009 } 5010 5011 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5012 SDValue Op, 5013 MVT VT, 5014 unsigned Offset) const { 5015 SDLoc SL(Op); 5016 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5017 DAG.getEntryNode(), Offset, 4, false); 5018 // The local size values will have the hi 16-bits as zero. 5019 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5020 DAG.getValueType(VT)); 5021 } 5022 5023 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5024 EVT VT) { 5025 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5026 "non-hsa intrinsic with hsa target", 5027 DL.getDebugLoc()); 5028 DAG.getContext()->diagnose(BadIntrin); 5029 return DAG.getUNDEF(VT); 5030 } 5031 5032 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5033 EVT VT) { 5034 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5035 "intrinsic not supported on subtarget", 5036 DL.getDebugLoc()); 5037 DAG.getContext()->diagnose(BadIntrin); 5038 return DAG.getUNDEF(VT); 5039 } 5040 5041 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5042 ArrayRef<SDValue> Elts) { 5043 assert(!Elts.empty()); 5044 MVT Type; 5045 unsigned NumElts; 5046 5047 if (Elts.size() == 1) { 5048 Type = MVT::f32; 5049 NumElts = 1; 5050 } else if (Elts.size() == 2) { 5051 Type = MVT::v2f32; 5052 NumElts = 2; 5053 } else if (Elts.size() <= 4) { 5054 Type = MVT::v4f32; 5055 NumElts = 4; 5056 } else if (Elts.size() <= 8) { 5057 Type = MVT::v8f32; 5058 NumElts = 8; 5059 } else { 5060 assert(Elts.size() <= 16); 5061 Type = MVT::v16f32; 5062 NumElts = 16; 5063 } 5064 5065 SmallVector<SDValue, 16> VecElts(NumElts); 5066 for (unsigned i = 0; i < Elts.size(); ++i) { 5067 SDValue Elt = Elts[i]; 5068 if (Elt.getValueType() != MVT::f32) 5069 Elt = DAG.getBitcast(MVT::f32, Elt); 5070 VecElts[i] = Elt; 5071 } 5072 for (unsigned i = Elts.size(); i < NumElts; ++i) 5073 VecElts[i] = DAG.getUNDEF(MVT::f32); 5074 5075 if (NumElts == 1) 5076 return VecElts[0]; 5077 return DAG.getBuildVector(Type, DL, VecElts); 5078 } 5079 5080 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5081 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5082 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5083 5084 uint64_t Value = CachePolicyConst->getZExtValue(); 5085 SDLoc DL(CachePolicy); 5086 if (GLC) { 5087 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5088 Value &= ~(uint64_t)0x1; 5089 } 5090 if (SLC) { 5091 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5092 Value &= ~(uint64_t)0x2; 5093 } 5094 if (DLC) { 5095 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5096 Value &= ~(uint64_t)0x4; 5097 } 5098 5099 return Value == 0; 5100 } 5101 5102 // Re-construct the required return value for a image load intrinsic. 5103 // This is more complicated due to the optional use TexFailCtrl which means the required 5104 // return type is an aggregate 5105 static SDValue constructRetValue(SelectionDAG &DAG, 5106 MachineSDNode *Result, 5107 ArrayRef<EVT> ResultTypes, 5108 bool IsTexFail, bool Unpacked, bool IsD16, 5109 int DMaskPop, int NumVDataDwords, 5110 const SDLoc &DL, LLVMContext &Context) { 5111 // Determine the required return type. This is the same regardless of IsTexFail flag 5112 EVT ReqRetVT = ResultTypes[0]; 5113 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5114 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5115 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5116 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5117 : AdjEltVT 5118 : ReqRetVT; 5119 5120 // Extract data part of the result 5121 // Bitcast the result to the same type as the required return type 5122 int NumElts; 5123 if (IsD16 && !Unpacked) 5124 NumElts = NumVDataDwords << 1; 5125 else 5126 NumElts = NumVDataDwords; 5127 5128 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5129 : AdjEltVT; 5130 5131 // Special case for v6f16. Rather than add support for this, use v3i32 to 5132 // extract the data elements 5133 bool V6F16Special = false; 5134 if (NumElts == 6) { 5135 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5136 DMaskPop >>= 1; 5137 ReqRetNumElts >>= 1; 5138 V6F16Special = true; 5139 AdjVT = MVT::v2i32; 5140 } 5141 5142 SDValue N = SDValue(Result, 0); 5143 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5144 5145 // Iterate over the result 5146 SmallVector<SDValue, 4> BVElts; 5147 5148 if (CastVT.isVector()) { 5149 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5150 } else { 5151 BVElts.push_back(CastRes); 5152 } 5153 int ExtraElts = ReqRetNumElts - DMaskPop; 5154 while(ExtraElts--) 5155 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5156 5157 SDValue PreTFCRes; 5158 if (ReqRetNumElts > 1) { 5159 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5160 if (IsD16 && Unpacked) 5161 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5162 else 5163 PreTFCRes = NewVec; 5164 } else { 5165 PreTFCRes = BVElts[0]; 5166 } 5167 5168 if (V6F16Special) 5169 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5170 5171 if (!IsTexFail) { 5172 if (Result->getNumValues() > 1) 5173 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5174 else 5175 return PreTFCRes; 5176 } 5177 5178 // Extract the TexFail result and insert into aggregate return 5179 SmallVector<SDValue, 1> TFCElt; 5180 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5181 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5182 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5183 } 5184 5185 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5186 SDValue *LWE, bool &IsTexFail) { 5187 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5188 5189 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5190 if (Value) { 5191 IsTexFail = true; 5192 } 5193 5194 SDLoc DL(TexFailCtrlConst); 5195 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5196 Value &= ~(uint64_t)0x1; 5197 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5198 Value &= ~(uint64_t)0x2; 5199 5200 return Value == 0; 5201 } 5202 5203 SDValue SITargetLowering::lowerImage(SDValue Op, 5204 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5205 SelectionDAG &DAG) const { 5206 SDLoc DL(Op); 5207 MachineFunction &MF = DAG.getMachineFunction(); 5208 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5209 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5210 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5211 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5212 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5213 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5214 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5215 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5216 unsigned IntrOpcode = Intr->BaseOpcode; 5217 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5218 5219 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5220 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5221 bool IsD16 = false; 5222 bool IsA16 = false; 5223 SDValue VData; 5224 int NumVDataDwords; 5225 bool AdjustRetType = false; 5226 5227 unsigned AddrIdx; // Index of first address argument 5228 unsigned DMask; 5229 unsigned DMaskLanes = 0; 5230 5231 if (BaseOpcode->Atomic) { 5232 VData = Op.getOperand(2); 5233 5234 bool Is64Bit = VData.getValueType() == MVT::i64; 5235 if (BaseOpcode->AtomicX2) { 5236 SDValue VData2 = Op.getOperand(3); 5237 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5238 {VData, VData2}); 5239 if (Is64Bit) 5240 VData = DAG.getBitcast(MVT::v4i32, VData); 5241 5242 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5243 DMask = Is64Bit ? 0xf : 0x3; 5244 NumVDataDwords = Is64Bit ? 4 : 2; 5245 AddrIdx = 4; 5246 } else { 5247 DMask = Is64Bit ? 0x3 : 0x1; 5248 NumVDataDwords = Is64Bit ? 2 : 1; 5249 AddrIdx = 3; 5250 } 5251 } else { 5252 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5253 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5254 DMask = DMaskConst->getZExtValue(); 5255 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5256 5257 if (BaseOpcode->Store) { 5258 VData = Op.getOperand(2); 5259 5260 MVT StoreVT = VData.getSimpleValueType(); 5261 if (StoreVT.getScalarType() == MVT::f16) { 5262 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5263 return Op; // D16 is unsupported for this instruction 5264 5265 IsD16 = true; 5266 VData = handleD16VData(VData, DAG); 5267 } 5268 5269 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5270 } else { 5271 // Work out the num dwords based on the dmask popcount and underlying type 5272 // and whether packing is supported. 5273 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5274 if (LoadVT.getScalarType() == MVT::f16) { 5275 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5276 return Op; // D16 is unsupported for this instruction 5277 5278 IsD16 = true; 5279 } 5280 5281 // Confirm that the return type is large enough for the dmask specified 5282 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5283 (!LoadVT.isVector() && DMaskLanes > 1)) 5284 return Op; 5285 5286 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5287 NumVDataDwords = (DMaskLanes + 1) / 2; 5288 else 5289 NumVDataDwords = DMaskLanes; 5290 5291 AdjustRetType = true; 5292 } 5293 5294 AddrIdx = DMaskIdx + 1; 5295 } 5296 5297 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5298 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5299 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5300 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5301 NumCoords + NumLCM; 5302 unsigned NumMIVAddrs = NumVAddrs; 5303 5304 SmallVector<SDValue, 4> VAddrs; 5305 5306 // Optimize _L to _LZ when _L is zero 5307 if (LZMappingInfo) { 5308 if (auto ConstantLod = 5309 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5310 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5311 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5312 NumMIVAddrs--; // remove 'lod' 5313 } 5314 } 5315 } 5316 5317 // Optimize _mip away, when 'lod' is zero 5318 if (MIPMappingInfo) { 5319 if (auto ConstantLod = 5320 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5321 if (ConstantLod->isNullValue()) { 5322 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5323 NumMIVAddrs--; // remove 'lod' 5324 } 5325 } 5326 } 5327 5328 // Check for 16 bit addresses and pack if true. 5329 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5330 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5331 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5332 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5333 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5334 IsA16 = true; 5335 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5336 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5337 SDValue AddrLo, AddrHi; 5338 // Push back extra arguments. 5339 if (i < DimIdx) { 5340 AddrLo = Op.getOperand(i); 5341 } else { 5342 AddrLo = Op.getOperand(i); 5343 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5344 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5345 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5346 ((NumGradients / 2) % 2 == 1 && 5347 (i == DimIdx + (NumGradients / 2) - 1 || 5348 i == DimIdx + NumGradients - 1))) { 5349 AddrHi = DAG.getUNDEF(MVT::f16); 5350 } else { 5351 AddrHi = Op.getOperand(i + 1); 5352 i++; 5353 } 5354 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5355 {AddrLo, AddrHi}); 5356 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5357 } 5358 VAddrs.push_back(AddrLo); 5359 } 5360 } else { 5361 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5362 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5363 } 5364 5365 // If the register allocator cannot place the address registers contiguously 5366 // without introducing moves, then using the non-sequential address encoding 5367 // is always preferable, since it saves VALU instructions and is usually a 5368 // wash in terms of code size or even better. 5369 // 5370 // However, we currently have no way of hinting to the register allocator that 5371 // MIMG addresses should be placed contiguously when it is possible to do so, 5372 // so force non-NSA for the common 2-address case as a heuristic. 5373 // 5374 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5375 // allocation when possible. 5376 bool UseNSA = 5377 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5378 SDValue VAddr; 5379 if (!UseNSA) 5380 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5381 5382 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5383 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5384 unsigned CtrlIdx; // Index of texfailctrl argument 5385 SDValue Unorm; 5386 if (!BaseOpcode->Sampler) { 5387 Unorm = True; 5388 CtrlIdx = AddrIdx + NumVAddrs + 1; 5389 } else { 5390 auto UnormConst = 5391 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5392 5393 Unorm = UnormConst->getZExtValue() ? True : False; 5394 CtrlIdx = AddrIdx + NumVAddrs + 3; 5395 } 5396 5397 SDValue TFE; 5398 SDValue LWE; 5399 SDValue TexFail = Op.getOperand(CtrlIdx); 5400 bool IsTexFail = false; 5401 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5402 return Op; 5403 5404 if (IsTexFail) { 5405 if (!DMaskLanes) { 5406 // Expecting to get an error flag since TFC is on - and dmask is 0 5407 // Force dmask to be at least 1 otherwise the instruction will fail 5408 DMask = 0x1; 5409 DMaskLanes = 1; 5410 NumVDataDwords = 1; 5411 } 5412 NumVDataDwords += 1; 5413 AdjustRetType = true; 5414 } 5415 5416 // Has something earlier tagged that the return type needs adjusting 5417 // This happens if the instruction is a load or has set TexFailCtrl flags 5418 if (AdjustRetType) { 5419 // NumVDataDwords reflects the true number of dwords required in the return type 5420 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5421 // This is a no-op load. This can be eliminated 5422 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5423 if (isa<MemSDNode>(Op)) 5424 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5425 return Undef; 5426 } 5427 5428 EVT NewVT = NumVDataDwords > 1 ? 5429 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5430 : MVT::f32; 5431 5432 ResultTypes[0] = NewVT; 5433 if (ResultTypes.size() == 3) { 5434 // Original result was aggregate type used for TexFailCtrl results 5435 // The actual instruction returns as a vector type which has now been 5436 // created. Remove the aggregate result. 5437 ResultTypes.erase(&ResultTypes[1]); 5438 } 5439 } 5440 5441 SDValue GLC; 5442 SDValue SLC; 5443 SDValue DLC; 5444 if (BaseOpcode->Atomic) { 5445 GLC = True; // TODO no-return optimization 5446 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5447 IsGFX10 ? &DLC : nullptr)) 5448 return Op; 5449 } else { 5450 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5451 IsGFX10 ? &DLC : nullptr)) 5452 return Op; 5453 } 5454 5455 SmallVector<SDValue, 26> Ops; 5456 if (BaseOpcode->Store || BaseOpcode->Atomic) 5457 Ops.push_back(VData); // vdata 5458 if (UseNSA) { 5459 for (const SDValue &Addr : VAddrs) 5460 Ops.push_back(Addr); 5461 } else { 5462 Ops.push_back(VAddr); 5463 } 5464 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5465 if (BaseOpcode->Sampler) 5466 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5467 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5468 if (IsGFX10) 5469 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5470 Ops.push_back(Unorm); 5471 if (IsGFX10) 5472 Ops.push_back(DLC); 5473 Ops.push_back(GLC); 5474 Ops.push_back(SLC); 5475 Ops.push_back(IsA16 && // a16 or r128 5476 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5477 Ops.push_back(TFE); // tfe 5478 Ops.push_back(LWE); // lwe 5479 if (!IsGFX10) 5480 Ops.push_back(DimInfo->DA ? True : False); 5481 if (BaseOpcode->HasD16) 5482 Ops.push_back(IsD16 ? True : False); 5483 if (isa<MemSDNode>(Op)) 5484 Ops.push_back(Op.getOperand(0)); // chain 5485 5486 int NumVAddrDwords = 5487 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5488 int Opcode = -1; 5489 5490 if (IsGFX10) { 5491 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5492 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5493 : AMDGPU::MIMGEncGfx10Default, 5494 NumVDataDwords, NumVAddrDwords); 5495 } else { 5496 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5497 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5498 NumVDataDwords, NumVAddrDwords); 5499 if (Opcode == -1) 5500 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5501 NumVDataDwords, NumVAddrDwords); 5502 } 5503 assert(Opcode != -1); 5504 5505 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5506 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5507 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5508 DAG.setNodeMemRefs(NewNode, {MemRef}); 5509 } 5510 5511 if (BaseOpcode->AtomicX2) { 5512 SmallVector<SDValue, 1> Elt; 5513 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5514 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5515 } else if (!BaseOpcode->Store) { 5516 return constructRetValue(DAG, NewNode, 5517 OrigResultTypes, IsTexFail, 5518 Subtarget->hasUnpackedD16VMem(), IsD16, 5519 DMaskLanes, NumVDataDwords, DL, 5520 *DAG.getContext()); 5521 } 5522 5523 return SDValue(NewNode, 0); 5524 } 5525 5526 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5527 SDValue Offset, SDValue GLC, SDValue DLC, 5528 SelectionDAG &DAG) const { 5529 MachineFunction &MF = DAG.getMachineFunction(); 5530 MachineMemOperand *MMO = MF.getMachineMemOperand( 5531 MachinePointerInfo(), 5532 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5533 MachineMemOperand::MOInvariant, 5534 VT.getStoreSize(), VT.getStoreSize()); 5535 5536 if (!Offset->isDivergent()) { 5537 SDValue Ops[] = { 5538 Rsrc, 5539 Offset, // Offset 5540 GLC, 5541 DLC, 5542 }; 5543 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5544 DAG.getVTList(VT), Ops, VT, MMO); 5545 } 5546 5547 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5548 // assume that the buffer is unswizzled. 5549 SmallVector<SDValue, 4> Loads; 5550 unsigned NumLoads = 1; 5551 MVT LoadVT = VT.getSimpleVT(); 5552 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5553 assert((LoadVT.getScalarType() == MVT::i32 || 5554 LoadVT.getScalarType() == MVT::f32) && 5555 isPowerOf2_32(NumElts)); 5556 5557 if (NumElts == 8 || NumElts == 16) { 5558 NumLoads = NumElts == 16 ? 4 : 2; 5559 LoadVT = MVT::v4i32; 5560 } 5561 5562 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5563 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5564 SDValue Ops[] = { 5565 DAG.getEntryNode(), // Chain 5566 Rsrc, // rsrc 5567 DAG.getConstant(0, DL, MVT::i32), // vindex 5568 {}, // voffset 5569 {}, // soffset 5570 {}, // offset 5571 DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5572 DAG.getConstant(0, DL, MVT::i1), // idxen 5573 }; 5574 5575 // Use the alignment to ensure that the required offsets will fit into the 5576 // immediate offsets. 5577 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5578 5579 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5580 for (unsigned i = 0; i < NumLoads; ++i) { 5581 Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32); 5582 Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, 5583 Ops, LoadVT, MMO)); 5584 } 5585 5586 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5587 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5588 5589 return Loads[0]; 5590 } 5591 5592 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5593 SelectionDAG &DAG) const { 5594 MachineFunction &MF = DAG.getMachineFunction(); 5595 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5596 5597 EVT VT = Op.getValueType(); 5598 SDLoc DL(Op); 5599 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5600 5601 // TODO: Should this propagate fast-math-flags? 5602 5603 switch (IntrinsicID) { 5604 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5605 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5606 return emitNonHSAIntrinsicError(DAG, DL, VT); 5607 return getPreloadedValue(DAG, *MFI, VT, 5608 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5609 } 5610 case Intrinsic::amdgcn_dispatch_ptr: 5611 case Intrinsic::amdgcn_queue_ptr: { 5612 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5613 DiagnosticInfoUnsupported BadIntrin( 5614 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5615 DL.getDebugLoc()); 5616 DAG.getContext()->diagnose(BadIntrin); 5617 return DAG.getUNDEF(VT); 5618 } 5619 5620 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5621 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5622 return getPreloadedValue(DAG, *MFI, VT, RegID); 5623 } 5624 case Intrinsic::amdgcn_implicitarg_ptr: { 5625 if (MFI->isEntryFunction()) 5626 return getImplicitArgPtr(DAG, DL); 5627 return getPreloadedValue(DAG, *MFI, VT, 5628 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5629 } 5630 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5631 return getPreloadedValue(DAG, *MFI, VT, 5632 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5633 } 5634 case Intrinsic::amdgcn_dispatch_id: { 5635 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5636 } 5637 case Intrinsic::amdgcn_rcp: 5638 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5639 case Intrinsic::amdgcn_rsq: 5640 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5641 case Intrinsic::amdgcn_rsq_legacy: 5642 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5643 return emitRemovedIntrinsicError(DAG, DL, VT); 5644 5645 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5646 case Intrinsic::amdgcn_rcp_legacy: 5647 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5648 return emitRemovedIntrinsicError(DAG, DL, VT); 5649 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5650 case Intrinsic::amdgcn_rsq_clamp: { 5651 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5652 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5653 5654 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5655 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5656 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5657 5658 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5659 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5660 DAG.getConstantFP(Max, DL, VT)); 5661 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5662 DAG.getConstantFP(Min, DL, VT)); 5663 } 5664 case Intrinsic::r600_read_ngroups_x: 5665 if (Subtarget->isAmdHsaOS()) 5666 return emitNonHSAIntrinsicError(DAG, DL, VT); 5667 5668 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5669 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5670 case Intrinsic::r600_read_ngroups_y: 5671 if (Subtarget->isAmdHsaOS()) 5672 return emitNonHSAIntrinsicError(DAG, DL, VT); 5673 5674 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5675 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5676 case Intrinsic::r600_read_ngroups_z: 5677 if (Subtarget->isAmdHsaOS()) 5678 return emitNonHSAIntrinsicError(DAG, DL, VT); 5679 5680 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5681 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5682 case Intrinsic::r600_read_global_size_x: 5683 if (Subtarget->isAmdHsaOS()) 5684 return emitNonHSAIntrinsicError(DAG, DL, VT); 5685 5686 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5687 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5688 case Intrinsic::r600_read_global_size_y: 5689 if (Subtarget->isAmdHsaOS()) 5690 return emitNonHSAIntrinsicError(DAG, DL, VT); 5691 5692 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5693 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5694 case Intrinsic::r600_read_global_size_z: 5695 if (Subtarget->isAmdHsaOS()) 5696 return emitNonHSAIntrinsicError(DAG, DL, VT); 5697 5698 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5699 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5700 case Intrinsic::r600_read_local_size_x: 5701 if (Subtarget->isAmdHsaOS()) 5702 return emitNonHSAIntrinsicError(DAG, DL, VT); 5703 5704 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5705 SI::KernelInputOffsets::LOCAL_SIZE_X); 5706 case Intrinsic::r600_read_local_size_y: 5707 if (Subtarget->isAmdHsaOS()) 5708 return emitNonHSAIntrinsicError(DAG, DL, VT); 5709 5710 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5711 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5712 case Intrinsic::r600_read_local_size_z: 5713 if (Subtarget->isAmdHsaOS()) 5714 return emitNonHSAIntrinsicError(DAG, DL, VT); 5715 5716 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5717 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5718 case Intrinsic::amdgcn_workgroup_id_x: 5719 case Intrinsic::r600_read_tgid_x: 5720 return getPreloadedValue(DAG, *MFI, VT, 5721 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5722 case Intrinsic::amdgcn_workgroup_id_y: 5723 case Intrinsic::r600_read_tgid_y: 5724 return getPreloadedValue(DAG, *MFI, VT, 5725 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5726 case Intrinsic::amdgcn_workgroup_id_z: 5727 case Intrinsic::r600_read_tgid_z: 5728 return getPreloadedValue(DAG, *MFI, VT, 5729 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5730 case Intrinsic::amdgcn_workitem_id_x: 5731 case Intrinsic::r600_read_tidig_x: 5732 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5733 SDLoc(DAG.getEntryNode()), 5734 MFI->getArgInfo().WorkItemIDX); 5735 case Intrinsic::amdgcn_workitem_id_y: 5736 case Intrinsic::r600_read_tidig_y: 5737 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5738 SDLoc(DAG.getEntryNode()), 5739 MFI->getArgInfo().WorkItemIDY); 5740 case Intrinsic::amdgcn_workitem_id_z: 5741 case Intrinsic::r600_read_tidig_z: 5742 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5743 SDLoc(DAG.getEntryNode()), 5744 MFI->getArgInfo().WorkItemIDZ); 5745 case Intrinsic::amdgcn_wavefrontsize: 5746 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5747 SDLoc(Op), MVT::i32); 5748 case Intrinsic::amdgcn_s_buffer_load: { 5749 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5750 SDValue GLC; 5751 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5752 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5753 IsGFX10 ? &DLC : nullptr)) 5754 return Op; 5755 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5756 DAG); 5757 } 5758 case Intrinsic::amdgcn_fdiv_fast: 5759 return lowerFDIV_FAST(Op, DAG); 5760 case Intrinsic::amdgcn_interp_mov: { 5761 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5762 SDValue Glue = M0.getValue(1); 5763 return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1), 5764 Op.getOperand(2), Op.getOperand(3), Glue); 5765 } 5766 case Intrinsic::amdgcn_interp_p1: { 5767 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4)); 5768 SDValue Glue = M0.getValue(1); 5769 return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1), 5770 Op.getOperand(2), Op.getOperand(3), Glue); 5771 } 5772 case Intrinsic::amdgcn_interp_p2: { 5773 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5774 SDValue Glue = SDValue(M0.getNode(), 1); 5775 return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1), 5776 Op.getOperand(2), Op.getOperand(3), Op.getOperand(4), 5777 Glue); 5778 } 5779 case Intrinsic::amdgcn_interp_p1_f16: { 5780 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5)); 5781 SDValue Glue = M0.getValue(1); 5782 if (getSubtarget()->getLDSBankCount() == 16) { 5783 // 16 bank LDS 5784 SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, 5785 DAG.getConstant(2, DL, MVT::i32), // P0 5786 Op.getOperand(2), // Attrchan 5787 Op.getOperand(3), // Attr 5788 Glue); 5789 SDValue Ops[] = { 5790 Op.getOperand(1), // Src0 5791 Op.getOperand(2), // Attrchan 5792 Op.getOperand(3), // Attr 5793 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5794 S, // Src2 - holds two f16 values selected by high 5795 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5796 Op.getOperand(4), // high 5797 DAG.getConstant(0, DL, MVT::i1), // $clamp 5798 DAG.getConstant(0, DL, MVT::i32) // $omod 5799 }; 5800 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5801 } else { 5802 // 32 bank LDS 5803 SDValue Ops[] = { 5804 Op.getOperand(1), // Src0 5805 Op.getOperand(2), // Attrchan 5806 Op.getOperand(3), // Attr 5807 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5808 Op.getOperand(4), // high 5809 DAG.getConstant(0, DL, MVT::i1), // $clamp 5810 DAG.getConstant(0, DL, MVT::i32), // $omod 5811 Glue 5812 }; 5813 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5814 } 5815 } 5816 case Intrinsic::amdgcn_interp_p2_f16: { 5817 SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6)); 5818 SDValue Glue = SDValue(M0.getNode(), 1); 5819 SDValue Ops[] = { 5820 Op.getOperand(2), // Src0 5821 Op.getOperand(3), // Attrchan 5822 Op.getOperand(4), // Attr 5823 DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers 5824 Op.getOperand(1), // Src2 5825 DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers 5826 Op.getOperand(5), // high 5827 DAG.getConstant(0, DL, MVT::i1), // $clamp 5828 Glue 5829 }; 5830 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5831 } 5832 case Intrinsic::amdgcn_sin: 5833 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5834 5835 case Intrinsic::amdgcn_cos: 5836 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5837 5838 case Intrinsic::amdgcn_log_clamp: { 5839 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5840 return SDValue(); 5841 5842 DiagnosticInfoUnsupported BadIntrin( 5843 MF.getFunction(), "intrinsic not supported on subtarget", 5844 DL.getDebugLoc()); 5845 DAG.getContext()->diagnose(BadIntrin); 5846 return DAG.getUNDEF(VT); 5847 } 5848 case Intrinsic::amdgcn_ldexp: 5849 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5850 Op.getOperand(1), Op.getOperand(2)); 5851 5852 case Intrinsic::amdgcn_fract: 5853 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5854 5855 case Intrinsic::amdgcn_class: 5856 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5857 Op.getOperand(1), Op.getOperand(2)); 5858 case Intrinsic::amdgcn_div_fmas: 5859 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5860 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5861 Op.getOperand(4)); 5862 5863 case Intrinsic::amdgcn_div_fixup: 5864 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5865 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5866 5867 case Intrinsic::amdgcn_trig_preop: 5868 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5869 Op.getOperand(1), Op.getOperand(2)); 5870 case Intrinsic::amdgcn_div_scale: { 5871 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5872 5873 // Translate to the operands expected by the machine instruction. The 5874 // first parameter must be the same as the first instruction. 5875 SDValue Numerator = Op.getOperand(1); 5876 SDValue Denominator = Op.getOperand(2); 5877 5878 // Note this order is opposite of the machine instruction's operations, 5879 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5880 // intrinsic has the numerator as the first operand to match a normal 5881 // division operation. 5882 5883 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5884 5885 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5886 Denominator, Numerator); 5887 } 5888 case Intrinsic::amdgcn_icmp: { 5889 // There is a Pat that handles this variant, so return it as-is. 5890 if (Op.getOperand(1).getValueType() == MVT::i1 && 5891 Op.getConstantOperandVal(2) == 0 && 5892 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5893 return Op; 5894 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5895 } 5896 case Intrinsic::amdgcn_fcmp: { 5897 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5898 } 5899 case Intrinsic::amdgcn_fmed3: 5900 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5901 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5902 case Intrinsic::amdgcn_fdot2: 5903 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5904 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5905 Op.getOperand(4)); 5906 case Intrinsic::amdgcn_fmul_legacy: 5907 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5908 Op.getOperand(1), Op.getOperand(2)); 5909 case Intrinsic::amdgcn_sffbh: 5910 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5911 case Intrinsic::amdgcn_sbfe: 5912 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5913 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5914 case Intrinsic::amdgcn_ubfe: 5915 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5916 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5917 case Intrinsic::amdgcn_cvt_pkrtz: 5918 case Intrinsic::amdgcn_cvt_pknorm_i16: 5919 case Intrinsic::amdgcn_cvt_pknorm_u16: 5920 case Intrinsic::amdgcn_cvt_pk_i16: 5921 case Intrinsic::amdgcn_cvt_pk_u16: { 5922 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5923 EVT VT = Op.getValueType(); 5924 unsigned Opcode; 5925 5926 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5927 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5928 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5929 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5930 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5931 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5932 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5933 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5934 else 5935 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5936 5937 if (isTypeLegal(VT)) 5938 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5939 5940 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5941 Op.getOperand(1), Op.getOperand(2)); 5942 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5943 } 5944 case Intrinsic::amdgcn_wqm: { 5945 SDValue Src = Op.getOperand(1); 5946 return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src), 5947 0); 5948 } 5949 case Intrinsic::amdgcn_wwm: { 5950 SDValue Src = Op.getOperand(1); 5951 return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src), 5952 0); 5953 } 5954 case Intrinsic::amdgcn_fmad_ftz: 5955 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5956 Op.getOperand(2), Op.getOperand(3)); 5957 5958 case Intrinsic::amdgcn_if_break: 5959 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5960 Op->getOperand(1), Op->getOperand(2)), 0); 5961 5962 case Intrinsic::amdgcn_groupstaticsize: { 5963 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 5964 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 5965 return Op; 5966 5967 const Module *M = MF.getFunction().getParent(); 5968 const GlobalValue *GV = 5969 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 5970 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 5971 SIInstrInfo::MO_ABS32_LO); 5972 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 5973 } 5974 default: 5975 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 5976 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 5977 return lowerImage(Op, ImageDimIntr, DAG); 5978 5979 return Op; 5980 } 5981 } 5982 5983 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 5984 SelectionDAG &DAG) const { 5985 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 5986 SDLoc DL(Op); 5987 5988 switch (IntrID) { 5989 case Intrinsic::amdgcn_ds_ordered_add: 5990 case Intrinsic::amdgcn_ds_ordered_swap: { 5991 MemSDNode *M = cast<MemSDNode>(Op); 5992 SDValue Chain = M->getOperand(0); 5993 SDValue M0 = M->getOperand(2); 5994 SDValue Value = M->getOperand(3); 5995 unsigned IndexOperand = M->getConstantOperandVal(7); 5996 unsigned WaveRelease = M->getConstantOperandVal(8); 5997 unsigned WaveDone = M->getConstantOperandVal(9); 5998 unsigned ShaderType; 5999 unsigned Instruction; 6000 6001 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6002 IndexOperand &= ~0x3f; 6003 unsigned CountDw = 0; 6004 6005 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6006 CountDw = (IndexOperand >> 24) & 0xf; 6007 IndexOperand &= ~(0xf << 24); 6008 6009 if (CountDw < 1 || CountDw > 4) { 6010 report_fatal_error( 6011 "ds_ordered_count: dword count must be between 1 and 4"); 6012 } 6013 } 6014 6015 if (IndexOperand) 6016 report_fatal_error("ds_ordered_count: bad index operand"); 6017 6018 switch (IntrID) { 6019 case Intrinsic::amdgcn_ds_ordered_add: 6020 Instruction = 0; 6021 break; 6022 case Intrinsic::amdgcn_ds_ordered_swap: 6023 Instruction = 1; 6024 break; 6025 } 6026 6027 if (WaveDone && !WaveRelease) 6028 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6029 6030 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6031 case CallingConv::AMDGPU_CS: 6032 case CallingConv::AMDGPU_KERNEL: 6033 ShaderType = 0; 6034 break; 6035 case CallingConv::AMDGPU_PS: 6036 ShaderType = 1; 6037 break; 6038 case CallingConv::AMDGPU_VS: 6039 ShaderType = 2; 6040 break; 6041 case CallingConv::AMDGPU_GS: 6042 ShaderType = 3; 6043 break; 6044 default: 6045 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6046 } 6047 6048 unsigned Offset0 = OrderedCountIndex << 2; 6049 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6050 (Instruction << 4); 6051 6052 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6053 Offset1 |= (CountDw - 1) << 6; 6054 6055 unsigned Offset = Offset0 | (Offset1 << 8); 6056 6057 SDValue Ops[] = { 6058 Chain, 6059 Value, 6060 DAG.getTargetConstant(Offset, DL, MVT::i16), 6061 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6062 }; 6063 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6064 M->getVTList(), Ops, M->getMemoryVT(), 6065 M->getMemOperand()); 6066 } 6067 case Intrinsic::amdgcn_ds_fadd: { 6068 MemSDNode *M = cast<MemSDNode>(Op); 6069 unsigned Opc; 6070 switch (IntrID) { 6071 case Intrinsic::amdgcn_ds_fadd: 6072 Opc = ISD::ATOMIC_LOAD_FADD; 6073 break; 6074 } 6075 6076 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6077 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6078 M->getMemOperand()); 6079 } 6080 case Intrinsic::amdgcn_atomic_inc: 6081 case Intrinsic::amdgcn_atomic_dec: 6082 case Intrinsic::amdgcn_ds_fmin: 6083 case Intrinsic::amdgcn_ds_fmax: { 6084 MemSDNode *M = cast<MemSDNode>(Op); 6085 unsigned Opc; 6086 switch (IntrID) { 6087 case Intrinsic::amdgcn_atomic_inc: 6088 Opc = AMDGPUISD::ATOMIC_INC; 6089 break; 6090 case Intrinsic::amdgcn_atomic_dec: 6091 Opc = AMDGPUISD::ATOMIC_DEC; 6092 break; 6093 case Intrinsic::amdgcn_ds_fmin: 6094 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6095 break; 6096 case Intrinsic::amdgcn_ds_fmax: 6097 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6098 break; 6099 default: 6100 llvm_unreachable("Unknown intrinsic!"); 6101 } 6102 SDValue Ops[] = { 6103 M->getOperand(0), // Chain 6104 M->getOperand(2), // Ptr 6105 M->getOperand(3) // Value 6106 }; 6107 6108 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6109 M->getMemoryVT(), M->getMemOperand()); 6110 } 6111 case Intrinsic::amdgcn_buffer_load: 6112 case Intrinsic::amdgcn_buffer_load_format: { 6113 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6114 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6115 unsigned IdxEn = 1; 6116 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6117 IdxEn = Idx->getZExtValue() != 0; 6118 SDValue Ops[] = { 6119 Op.getOperand(0), // Chain 6120 Op.getOperand(2), // rsrc 6121 Op.getOperand(3), // vindex 6122 SDValue(), // voffset -- will be set by setBufferOffsets 6123 SDValue(), // soffset -- will be set by setBufferOffsets 6124 SDValue(), // offset -- will be set by setBufferOffsets 6125 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6126 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6127 }; 6128 6129 setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6130 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6131 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6132 6133 EVT VT = Op.getValueType(); 6134 EVT IntVT = VT.changeTypeToInteger(); 6135 auto *M = cast<MemSDNode>(Op); 6136 EVT LoadVT = Op.getValueType(); 6137 6138 if (LoadVT.getScalarType() == MVT::f16) 6139 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6140 M, DAG, Ops); 6141 6142 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6143 if (LoadVT.getScalarType() == MVT::i8 || 6144 LoadVT.getScalarType() == MVT::i16) 6145 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6146 6147 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6148 M->getMemOperand(), DAG); 6149 } 6150 case Intrinsic::amdgcn_raw_buffer_load: 6151 case Intrinsic::amdgcn_raw_buffer_load_format: { 6152 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6153 SDValue Ops[] = { 6154 Op.getOperand(0), // Chain 6155 Op.getOperand(2), // rsrc 6156 DAG.getConstant(0, DL, MVT::i32), // vindex 6157 Offsets.first, // voffset 6158 Op.getOperand(4), // soffset 6159 Offsets.second, // offset 6160 Op.getOperand(5), // cachepolicy 6161 DAG.getConstant(0, DL, MVT::i1), // idxen 6162 }; 6163 6164 unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ? 6165 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6166 6167 EVT VT = Op.getValueType(); 6168 EVT IntVT = VT.changeTypeToInteger(); 6169 auto *M = cast<MemSDNode>(Op); 6170 EVT LoadVT = Op.getValueType(); 6171 6172 if (LoadVT.getScalarType() == MVT::f16) 6173 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6174 M, DAG, Ops); 6175 6176 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6177 if (LoadVT.getScalarType() == MVT::i8 || 6178 LoadVT.getScalarType() == MVT::i16) 6179 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6180 6181 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6182 M->getMemOperand(), DAG); 6183 } 6184 case Intrinsic::amdgcn_struct_buffer_load: 6185 case Intrinsic::amdgcn_struct_buffer_load_format: { 6186 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6187 SDValue Ops[] = { 6188 Op.getOperand(0), // Chain 6189 Op.getOperand(2), // rsrc 6190 Op.getOperand(3), // vindex 6191 Offsets.first, // voffset 6192 Op.getOperand(5), // soffset 6193 Offsets.second, // offset 6194 Op.getOperand(6), // cachepolicy 6195 DAG.getConstant(1, DL, MVT::i1), // idxen 6196 }; 6197 6198 unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ? 6199 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6200 6201 EVT VT = Op.getValueType(); 6202 EVT IntVT = VT.changeTypeToInteger(); 6203 auto *M = cast<MemSDNode>(Op); 6204 EVT LoadVT = Op.getValueType(); 6205 6206 if (LoadVT.getScalarType() == MVT::f16) 6207 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6208 M, DAG, Ops); 6209 6210 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6211 if (LoadVT.getScalarType() == MVT::i8 || 6212 LoadVT.getScalarType() == MVT::i16) 6213 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6214 6215 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6216 M->getMemOperand(), DAG); 6217 } 6218 case Intrinsic::amdgcn_tbuffer_load: { 6219 MemSDNode *M = cast<MemSDNode>(Op); 6220 EVT LoadVT = Op.getValueType(); 6221 6222 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6223 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6224 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6225 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6226 unsigned IdxEn = 1; 6227 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6228 IdxEn = Idx->getZExtValue() != 0; 6229 SDValue Ops[] = { 6230 Op.getOperand(0), // Chain 6231 Op.getOperand(2), // rsrc 6232 Op.getOperand(3), // vindex 6233 Op.getOperand(4), // voffset 6234 Op.getOperand(5), // soffset 6235 Op.getOperand(6), // offset 6236 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6237 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6238 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6239 }; 6240 6241 if (LoadVT.getScalarType() == MVT::f16) 6242 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6243 M, DAG, Ops); 6244 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6245 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6246 DAG); 6247 } 6248 case Intrinsic::amdgcn_raw_tbuffer_load: { 6249 MemSDNode *M = cast<MemSDNode>(Op); 6250 EVT LoadVT = Op.getValueType(); 6251 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6252 6253 SDValue Ops[] = { 6254 Op.getOperand(0), // Chain 6255 Op.getOperand(2), // rsrc 6256 DAG.getConstant(0, DL, MVT::i32), // vindex 6257 Offsets.first, // voffset 6258 Op.getOperand(4), // soffset 6259 Offsets.second, // offset 6260 Op.getOperand(5), // format 6261 Op.getOperand(6), // cachepolicy 6262 DAG.getConstant(0, DL, MVT::i1), // idxen 6263 }; 6264 6265 if (LoadVT.getScalarType() == MVT::f16) 6266 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6267 M, DAG, Ops); 6268 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6269 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6270 DAG); 6271 } 6272 case Intrinsic::amdgcn_struct_tbuffer_load: { 6273 MemSDNode *M = cast<MemSDNode>(Op); 6274 EVT LoadVT = Op.getValueType(); 6275 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6276 6277 SDValue Ops[] = { 6278 Op.getOperand(0), // Chain 6279 Op.getOperand(2), // rsrc 6280 Op.getOperand(3), // vindex 6281 Offsets.first, // voffset 6282 Op.getOperand(5), // soffset 6283 Offsets.second, // offset 6284 Op.getOperand(6), // format 6285 Op.getOperand(7), // cachepolicy 6286 DAG.getConstant(1, DL, MVT::i1), // idxen 6287 }; 6288 6289 if (LoadVT.getScalarType() == MVT::f16) 6290 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6291 M, DAG, Ops); 6292 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6293 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6294 DAG); 6295 } 6296 case Intrinsic::amdgcn_buffer_atomic_swap: 6297 case Intrinsic::amdgcn_buffer_atomic_add: 6298 case Intrinsic::amdgcn_buffer_atomic_sub: 6299 case Intrinsic::amdgcn_buffer_atomic_smin: 6300 case Intrinsic::amdgcn_buffer_atomic_umin: 6301 case Intrinsic::amdgcn_buffer_atomic_smax: 6302 case Intrinsic::amdgcn_buffer_atomic_umax: 6303 case Intrinsic::amdgcn_buffer_atomic_and: 6304 case Intrinsic::amdgcn_buffer_atomic_or: 6305 case Intrinsic::amdgcn_buffer_atomic_xor: { 6306 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6307 unsigned IdxEn = 1; 6308 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6309 IdxEn = Idx->getZExtValue() != 0; 6310 SDValue Ops[] = { 6311 Op.getOperand(0), // Chain 6312 Op.getOperand(2), // vdata 6313 Op.getOperand(3), // rsrc 6314 Op.getOperand(4), // vindex 6315 SDValue(), // voffset -- will be set by setBufferOffsets 6316 SDValue(), // soffset -- will be set by setBufferOffsets 6317 SDValue(), // offset -- will be set by setBufferOffsets 6318 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6319 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6320 }; 6321 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6322 EVT VT = Op.getValueType(); 6323 6324 auto *M = cast<MemSDNode>(Op); 6325 unsigned Opcode = 0; 6326 6327 switch (IntrID) { 6328 case Intrinsic::amdgcn_buffer_atomic_swap: 6329 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6330 break; 6331 case Intrinsic::amdgcn_buffer_atomic_add: 6332 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6333 break; 6334 case Intrinsic::amdgcn_buffer_atomic_sub: 6335 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6336 break; 6337 case Intrinsic::amdgcn_buffer_atomic_smin: 6338 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6339 break; 6340 case Intrinsic::amdgcn_buffer_atomic_umin: 6341 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6342 break; 6343 case Intrinsic::amdgcn_buffer_atomic_smax: 6344 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6345 break; 6346 case Intrinsic::amdgcn_buffer_atomic_umax: 6347 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6348 break; 6349 case Intrinsic::amdgcn_buffer_atomic_and: 6350 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6351 break; 6352 case Intrinsic::amdgcn_buffer_atomic_or: 6353 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6354 break; 6355 case Intrinsic::amdgcn_buffer_atomic_xor: 6356 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6357 break; 6358 default: 6359 llvm_unreachable("unhandled atomic opcode"); 6360 } 6361 6362 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6363 M->getMemOperand()); 6364 } 6365 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6366 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6367 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6368 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6369 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6370 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6371 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6372 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6373 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6374 case Intrinsic::amdgcn_raw_buffer_atomic_xor: { 6375 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6376 SDValue Ops[] = { 6377 Op.getOperand(0), // Chain 6378 Op.getOperand(2), // vdata 6379 Op.getOperand(3), // rsrc 6380 DAG.getConstant(0, DL, MVT::i32), // vindex 6381 Offsets.first, // voffset 6382 Op.getOperand(5), // soffset 6383 Offsets.second, // offset 6384 Op.getOperand(6), // cachepolicy 6385 DAG.getConstant(0, DL, MVT::i1), // idxen 6386 }; 6387 EVT VT = Op.getValueType(); 6388 6389 auto *M = cast<MemSDNode>(Op); 6390 unsigned Opcode = 0; 6391 6392 switch (IntrID) { 6393 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6394 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6395 break; 6396 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6397 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6398 break; 6399 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6400 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6401 break; 6402 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6403 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6404 break; 6405 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6406 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6407 break; 6408 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6409 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6410 break; 6411 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6412 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6413 break; 6414 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6415 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6416 break; 6417 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6418 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6419 break; 6420 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6421 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6422 break; 6423 default: 6424 llvm_unreachable("unhandled atomic opcode"); 6425 } 6426 6427 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6428 M->getMemOperand()); 6429 } 6430 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6431 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6432 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6433 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6434 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6435 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6436 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6437 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6438 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6439 case Intrinsic::amdgcn_struct_buffer_atomic_xor: { 6440 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6441 SDValue Ops[] = { 6442 Op.getOperand(0), // Chain 6443 Op.getOperand(2), // vdata 6444 Op.getOperand(3), // rsrc 6445 Op.getOperand(4), // vindex 6446 Offsets.first, // voffset 6447 Op.getOperand(6), // soffset 6448 Offsets.second, // offset 6449 Op.getOperand(7), // cachepolicy 6450 DAG.getConstant(1, DL, MVT::i1), // idxen 6451 }; 6452 EVT VT = Op.getValueType(); 6453 6454 auto *M = cast<MemSDNode>(Op); 6455 unsigned Opcode = 0; 6456 6457 switch (IntrID) { 6458 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6459 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6460 break; 6461 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6462 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6463 break; 6464 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6465 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6466 break; 6467 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6468 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6469 break; 6470 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6471 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6472 break; 6473 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6474 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6475 break; 6476 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6477 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6478 break; 6479 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6480 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6481 break; 6482 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6483 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6484 break; 6485 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6486 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6487 break; 6488 default: 6489 llvm_unreachable("unhandled atomic opcode"); 6490 } 6491 6492 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6493 M->getMemOperand()); 6494 } 6495 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6496 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6497 unsigned IdxEn = 1; 6498 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6499 IdxEn = Idx->getZExtValue() != 0; 6500 SDValue Ops[] = { 6501 Op.getOperand(0), // Chain 6502 Op.getOperand(2), // src 6503 Op.getOperand(3), // cmp 6504 Op.getOperand(4), // rsrc 6505 Op.getOperand(5), // vindex 6506 SDValue(), // voffset -- will be set by setBufferOffsets 6507 SDValue(), // soffset -- will be set by setBufferOffsets 6508 SDValue(), // offset -- will be set by setBufferOffsets 6509 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6510 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6511 }; 6512 setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6513 EVT VT = Op.getValueType(); 6514 auto *M = cast<MemSDNode>(Op); 6515 6516 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6517 Op->getVTList(), Ops, VT, M->getMemOperand()); 6518 } 6519 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6520 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6521 SDValue Ops[] = { 6522 Op.getOperand(0), // Chain 6523 Op.getOperand(2), // src 6524 Op.getOperand(3), // cmp 6525 Op.getOperand(4), // rsrc 6526 DAG.getConstant(0, DL, MVT::i32), // vindex 6527 Offsets.first, // voffset 6528 Op.getOperand(6), // soffset 6529 Offsets.second, // offset 6530 Op.getOperand(7), // cachepolicy 6531 DAG.getConstant(0, DL, MVT::i1), // idxen 6532 }; 6533 EVT VT = Op.getValueType(); 6534 auto *M = cast<MemSDNode>(Op); 6535 6536 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6537 Op->getVTList(), Ops, VT, M->getMemOperand()); 6538 } 6539 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6540 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6541 SDValue Ops[] = { 6542 Op.getOperand(0), // Chain 6543 Op.getOperand(2), // src 6544 Op.getOperand(3), // cmp 6545 Op.getOperand(4), // rsrc 6546 Op.getOperand(5), // vindex 6547 Offsets.first, // voffset 6548 Op.getOperand(7), // soffset 6549 Offsets.second, // offset 6550 Op.getOperand(8), // cachepolicy 6551 DAG.getConstant(1, DL, MVT::i1), // idxen 6552 }; 6553 EVT VT = Op.getValueType(); 6554 auto *M = cast<MemSDNode>(Op); 6555 6556 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6557 Op->getVTList(), Ops, VT, M->getMemOperand()); 6558 } 6559 6560 default: 6561 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6562 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6563 return lowerImage(Op, ImageDimIntr, DAG); 6564 6565 return SDValue(); 6566 } 6567 } 6568 6569 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6570 // dwordx4 if on SI. 6571 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6572 SDVTList VTList, 6573 ArrayRef<SDValue> Ops, EVT MemVT, 6574 MachineMemOperand *MMO, 6575 SelectionDAG &DAG) const { 6576 EVT VT = VTList.VTs[0]; 6577 EVT WidenedVT = VT; 6578 EVT WidenedMemVT = MemVT; 6579 if (!Subtarget->hasDwordx3LoadStores() && 6580 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6581 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6582 WidenedVT.getVectorElementType(), 4); 6583 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6584 WidenedMemVT.getVectorElementType(), 4); 6585 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6586 } 6587 6588 assert(VTList.NumVTs == 2); 6589 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6590 6591 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6592 WidenedMemVT, MMO); 6593 if (WidenedVT != VT) { 6594 auto Extract = DAG.getNode( 6595 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6596 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6597 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6598 } 6599 return NewOp; 6600 } 6601 6602 SDValue SITargetLowering::handleD16VData(SDValue VData, 6603 SelectionDAG &DAG) const { 6604 EVT StoreVT = VData.getValueType(); 6605 6606 // No change for f16 and legal vector D16 types. 6607 if (!StoreVT.isVector()) 6608 return VData; 6609 6610 SDLoc DL(VData); 6611 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6612 6613 if (Subtarget->hasUnpackedD16VMem()) { 6614 // We need to unpack the packed data to store. 6615 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6616 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6617 6618 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6619 StoreVT.getVectorNumElements()); 6620 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6621 return DAG.UnrollVectorOp(ZExt.getNode()); 6622 } 6623 6624 assert(isTypeLegal(StoreVT)); 6625 return VData; 6626 } 6627 6628 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6629 SelectionDAG &DAG) const { 6630 SDLoc DL(Op); 6631 SDValue Chain = Op.getOperand(0); 6632 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6633 MachineFunction &MF = DAG.getMachineFunction(); 6634 6635 switch (IntrinsicID) { 6636 case Intrinsic::amdgcn_exp: { 6637 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6638 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6639 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6640 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6641 6642 const SDValue Ops[] = { 6643 Chain, 6644 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6645 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6646 Op.getOperand(4), // src0 6647 Op.getOperand(5), // src1 6648 Op.getOperand(6), // src2 6649 Op.getOperand(7), // src3 6650 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6651 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6652 }; 6653 6654 unsigned Opc = Done->isNullValue() ? 6655 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6656 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6657 } 6658 case Intrinsic::amdgcn_exp_compr: { 6659 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6660 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6661 SDValue Src0 = Op.getOperand(4); 6662 SDValue Src1 = Op.getOperand(5); 6663 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6664 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6665 6666 SDValue Undef = DAG.getUNDEF(MVT::f32); 6667 const SDValue Ops[] = { 6668 Chain, 6669 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6670 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6671 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6672 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6673 Undef, // src2 6674 Undef, // src3 6675 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6676 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6677 }; 6678 6679 unsigned Opc = Done->isNullValue() ? 6680 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6681 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6682 } 6683 case Intrinsic::amdgcn_s_sendmsg: 6684 case Intrinsic::amdgcn_s_sendmsghalt: { 6685 unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ? 6686 AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT; 6687 Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3)); 6688 SDValue Glue = Chain.getValue(1); 6689 return DAG.getNode(NodeOp, DL, MVT::Other, Chain, 6690 Op.getOperand(2), Glue); 6691 } 6692 case Intrinsic::amdgcn_init_exec: { 6693 return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain, 6694 Op.getOperand(2)); 6695 } 6696 case Intrinsic::amdgcn_init_exec_from_input: { 6697 return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain, 6698 Op.getOperand(2), Op.getOperand(3)); 6699 } 6700 case Intrinsic::amdgcn_s_barrier: { 6701 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6702 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6703 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6704 if (WGSize <= ST.getWavefrontSize()) 6705 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6706 Op.getOperand(0)), 0); 6707 } 6708 return SDValue(); 6709 }; 6710 case Intrinsic::amdgcn_tbuffer_store: { 6711 SDValue VData = Op.getOperand(2); 6712 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6713 if (IsD16) 6714 VData = handleD16VData(VData, DAG); 6715 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6716 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6717 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6718 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6719 unsigned IdxEn = 1; 6720 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6721 IdxEn = Idx->getZExtValue() != 0; 6722 SDValue Ops[] = { 6723 Chain, 6724 VData, // vdata 6725 Op.getOperand(3), // rsrc 6726 Op.getOperand(4), // vindex 6727 Op.getOperand(5), // voffset 6728 Op.getOperand(6), // soffset 6729 Op.getOperand(7), // offset 6730 DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6731 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6732 DAG.getConstant(IdxEn, DL, MVT::i1), // idexen 6733 }; 6734 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6735 AMDGPUISD::TBUFFER_STORE_FORMAT; 6736 MemSDNode *M = cast<MemSDNode>(Op); 6737 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6738 M->getMemoryVT(), M->getMemOperand()); 6739 } 6740 6741 case Intrinsic::amdgcn_struct_tbuffer_store: { 6742 SDValue VData = Op.getOperand(2); 6743 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6744 if (IsD16) 6745 VData = handleD16VData(VData, DAG); 6746 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6747 SDValue Ops[] = { 6748 Chain, 6749 VData, // vdata 6750 Op.getOperand(3), // rsrc 6751 Op.getOperand(4), // vindex 6752 Offsets.first, // voffset 6753 Op.getOperand(6), // soffset 6754 Offsets.second, // offset 6755 Op.getOperand(7), // format 6756 Op.getOperand(8), // cachepolicy 6757 DAG.getConstant(1, DL, MVT::i1), // idexen 6758 }; 6759 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6760 AMDGPUISD::TBUFFER_STORE_FORMAT; 6761 MemSDNode *M = cast<MemSDNode>(Op); 6762 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6763 M->getMemoryVT(), M->getMemOperand()); 6764 } 6765 6766 case Intrinsic::amdgcn_raw_tbuffer_store: { 6767 SDValue VData = Op.getOperand(2); 6768 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6769 if (IsD16) 6770 VData = handleD16VData(VData, DAG); 6771 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6772 SDValue Ops[] = { 6773 Chain, 6774 VData, // vdata 6775 Op.getOperand(3), // rsrc 6776 DAG.getConstant(0, DL, MVT::i32), // vindex 6777 Offsets.first, // voffset 6778 Op.getOperand(5), // soffset 6779 Offsets.second, // offset 6780 Op.getOperand(6), // format 6781 Op.getOperand(7), // cachepolicy 6782 DAG.getConstant(0, DL, MVT::i1), // idexen 6783 }; 6784 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6785 AMDGPUISD::TBUFFER_STORE_FORMAT; 6786 MemSDNode *M = cast<MemSDNode>(Op); 6787 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6788 M->getMemoryVT(), M->getMemOperand()); 6789 } 6790 6791 case Intrinsic::amdgcn_buffer_store: 6792 case Intrinsic::amdgcn_buffer_store_format: { 6793 SDValue VData = Op.getOperand(2); 6794 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6795 if (IsD16) 6796 VData = handleD16VData(VData, DAG); 6797 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6798 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6799 unsigned IdxEn = 1; 6800 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6801 IdxEn = Idx->getZExtValue() != 0; 6802 SDValue Ops[] = { 6803 Chain, 6804 VData, 6805 Op.getOperand(3), // rsrc 6806 Op.getOperand(4), // vindex 6807 SDValue(), // voffset -- will be set by setBufferOffsets 6808 SDValue(), // soffset -- will be set by setBufferOffsets 6809 SDValue(), // offset -- will be set by setBufferOffsets 6810 DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6811 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6812 }; 6813 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6814 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6815 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6816 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6817 MemSDNode *M = cast<MemSDNode>(Op); 6818 6819 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6820 EVT VDataType = VData.getValueType().getScalarType(); 6821 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6822 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6823 6824 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6825 M->getMemoryVT(), M->getMemOperand()); 6826 } 6827 6828 case Intrinsic::amdgcn_raw_buffer_store: 6829 case Intrinsic::amdgcn_raw_buffer_store_format: { 6830 SDValue VData = Op.getOperand(2); 6831 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6832 if (IsD16) 6833 VData = handleD16VData(VData, DAG); 6834 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6835 SDValue Ops[] = { 6836 Chain, 6837 VData, 6838 Op.getOperand(3), // rsrc 6839 DAG.getConstant(0, DL, MVT::i32), // vindex 6840 Offsets.first, // voffset 6841 Op.getOperand(5), // soffset 6842 Offsets.second, // offset 6843 Op.getOperand(6), // cachepolicy 6844 DAG.getConstant(0, DL, MVT::i1), // idxen 6845 }; 6846 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ? 6847 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6848 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6849 MemSDNode *M = cast<MemSDNode>(Op); 6850 6851 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6852 EVT VDataType = VData.getValueType().getScalarType(); 6853 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6854 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6855 6856 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6857 M->getMemoryVT(), M->getMemOperand()); 6858 } 6859 6860 case Intrinsic::amdgcn_struct_buffer_store: 6861 case Intrinsic::amdgcn_struct_buffer_store_format: { 6862 SDValue VData = Op.getOperand(2); 6863 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6864 if (IsD16) 6865 VData = handleD16VData(VData, DAG); 6866 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6867 SDValue Ops[] = { 6868 Chain, 6869 VData, 6870 Op.getOperand(3), // rsrc 6871 Op.getOperand(4), // vindex 6872 Offsets.first, // voffset 6873 Op.getOperand(6), // soffset 6874 Offsets.second, // offset 6875 Op.getOperand(7), // cachepolicy 6876 DAG.getConstant(1, DL, MVT::i1), // idxen 6877 }; 6878 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6879 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6880 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6881 MemSDNode *M = cast<MemSDNode>(Op); 6882 6883 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6884 EVT VDataType = VData.getValueType().getScalarType(); 6885 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6886 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6887 6888 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6889 M->getMemoryVT(), M->getMemOperand()); 6890 } 6891 6892 case Intrinsic::amdgcn_buffer_atomic_fadd: { 6893 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6894 unsigned IdxEn = 1; 6895 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6896 IdxEn = Idx->getZExtValue() != 0; 6897 SDValue Ops[] = { 6898 Chain, 6899 Op.getOperand(2), // vdata 6900 Op.getOperand(3), // rsrc 6901 Op.getOperand(4), // vindex 6902 SDValue(), // voffset -- will be set by setBufferOffsets 6903 SDValue(), // soffset -- will be set by setBufferOffsets 6904 SDValue(), // offset -- will be set by setBufferOffsets 6905 DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6906 DAG.getConstant(IdxEn, DL, MVT::i1), // idxen 6907 }; 6908 setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6909 EVT VT = Op.getOperand(2).getValueType(); 6910 6911 auto *M = cast<MemSDNode>(Op); 6912 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 6913 : AMDGPUISD::BUFFER_ATOMIC_FADD; 6914 6915 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6916 M->getMemOperand()); 6917 } 6918 6919 case Intrinsic::amdgcn_global_atomic_fadd: { 6920 SDValue Ops[] = { 6921 Chain, 6922 Op.getOperand(2), // ptr 6923 Op.getOperand(3) // vdata 6924 }; 6925 EVT VT = Op.getOperand(3).getValueType(); 6926 6927 auto *M = cast<MemSDNode>(Op); 6928 unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD 6929 : AMDGPUISD::ATOMIC_FADD; 6930 6931 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6932 M->getMemOperand()); 6933 } 6934 6935 case Intrinsic::amdgcn_end_cf: 6936 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 6937 Op->getOperand(2), Chain), 0); 6938 6939 default: { 6940 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6941 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6942 return lowerImage(Op, ImageDimIntr, DAG); 6943 6944 return Op; 6945 } 6946 } 6947 } 6948 6949 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 6950 // offset (the offset that is included in bounds checking and swizzling, to be 6951 // split between the instruction's voffset and immoffset fields) and soffset 6952 // (the offset that is excluded from bounds checking and swizzling, to go in 6953 // the instruction's soffset field). This function takes the first kind of 6954 // offset and figures out how to split it between voffset and immoffset. 6955 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 6956 SDValue Offset, SelectionDAG &DAG) const { 6957 SDLoc DL(Offset); 6958 const unsigned MaxImm = 4095; 6959 SDValue N0 = Offset; 6960 ConstantSDNode *C1 = nullptr; 6961 6962 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 6963 N0 = SDValue(); 6964 else if (DAG.isBaseWithConstantOffset(N0)) { 6965 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 6966 N0 = N0.getOperand(0); 6967 } 6968 6969 if (C1) { 6970 unsigned ImmOffset = C1->getZExtValue(); 6971 // If the immediate value is too big for the immoffset field, put the value 6972 // and -4096 into the immoffset field so that the value that is copied/added 6973 // for the voffset field is a multiple of 4096, and it stands more chance 6974 // of being CSEd with the copy/add for another similar load/store. 6975 // However, do not do that rounding down to a multiple of 4096 if that is a 6976 // negative number, as it appears to be illegal to have a negative offset 6977 // in the vgpr, even if adding the immediate offset makes it positive. 6978 unsigned Overflow = ImmOffset & ~MaxImm; 6979 ImmOffset -= Overflow; 6980 if ((int32_t)Overflow < 0) { 6981 Overflow += ImmOffset; 6982 ImmOffset = 0; 6983 } 6984 C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32)); 6985 if (Overflow) { 6986 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 6987 if (!N0) 6988 N0 = OverflowVal; 6989 else { 6990 SDValue Ops[] = { N0, OverflowVal }; 6991 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 6992 } 6993 } 6994 } 6995 if (!N0) 6996 N0 = DAG.getConstant(0, DL, MVT::i32); 6997 if (!C1) 6998 C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32)); 6999 return {N0, SDValue(C1, 0)}; 7000 } 7001 7002 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7003 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7004 // pointed to by Offsets. 7005 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7006 SelectionDAG &DAG, SDValue *Offsets, 7007 unsigned Align) const { 7008 SDLoc DL(CombinedOffset); 7009 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7010 uint32_t Imm = C->getZExtValue(); 7011 uint32_t SOffset, ImmOffset; 7012 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7013 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7014 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7015 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 7016 return; 7017 } 7018 } 7019 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7020 SDValue N0 = CombinedOffset.getOperand(0); 7021 SDValue N1 = CombinedOffset.getOperand(1); 7022 uint32_t SOffset, ImmOffset; 7023 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7024 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7025 Subtarget, Align)) { 7026 Offsets[0] = N0; 7027 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7028 Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32); 7029 return; 7030 } 7031 } 7032 Offsets[0] = CombinedOffset; 7033 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7034 Offsets[2] = DAG.getConstant(0, DL, MVT::i32); 7035 } 7036 7037 // Handle 8 bit and 16 bit buffer loads 7038 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7039 EVT LoadVT, SDLoc DL, 7040 ArrayRef<SDValue> Ops, 7041 MemSDNode *M) const { 7042 EVT IntVT = LoadVT.changeTypeToInteger(); 7043 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7044 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7045 7046 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7047 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7048 Ops, IntVT, 7049 M->getMemOperand()); 7050 SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL, 7051 LoadVT.getScalarType(), BufferLoad); 7052 return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL); 7053 } 7054 7055 // Handle 8 bit and 16 bit buffer stores 7056 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7057 EVT VDataType, SDLoc DL, 7058 SDValue Ops[], 7059 MemSDNode *M) const { 7060 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7061 Ops[1] = BufferStoreExt; 7062 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7063 AMDGPUISD::BUFFER_STORE_SHORT; 7064 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7065 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7066 M->getMemOperand()); 7067 } 7068 7069 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7070 ISD::LoadExtType ExtType, SDValue Op, 7071 const SDLoc &SL, EVT VT) { 7072 if (VT.bitsLT(Op.getValueType())) 7073 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7074 7075 switch (ExtType) { 7076 case ISD::SEXTLOAD: 7077 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7078 case ISD::ZEXTLOAD: 7079 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7080 case ISD::EXTLOAD: 7081 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7082 case ISD::NON_EXTLOAD: 7083 return Op; 7084 } 7085 7086 llvm_unreachable("invalid ext type"); 7087 } 7088 7089 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7090 SelectionDAG &DAG = DCI.DAG; 7091 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7092 return SDValue(); 7093 7094 // FIXME: Constant loads should all be marked invariant. 7095 unsigned AS = Ld->getAddressSpace(); 7096 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7097 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7098 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7099 return SDValue(); 7100 7101 // Don't do this early, since it may interfere with adjacent load merging for 7102 // illegal types. We can avoid losing alignment information for exotic types 7103 // pre-legalize. 7104 EVT MemVT = Ld->getMemoryVT(); 7105 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7106 MemVT.getSizeInBits() >= 32) 7107 return SDValue(); 7108 7109 SDLoc SL(Ld); 7110 7111 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7112 "unexpected vector extload"); 7113 7114 // TODO: Drop only high part of range. 7115 SDValue Ptr = Ld->getBasePtr(); 7116 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7117 MVT::i32, SL, Ld->getChain(), Ptr, 7118 Ld->getOffset(), 7119 Ld->getPointerInfo(), MVT::i32, 7120 Ld->getAlignment(), 7121 Ld->getMemOperand()->getFlags(), 7122 Ld->getAAInfo(), 7123 nullptr); // Drop ranges 7124 7125 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7126 if (MemVT.isFloatingPoint()) { 7127 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7128 "unexpected fp extload"); 7129 TruncVT = MemVT.changeTypeToInteger(); 7130 } 7131 7132 SDValue Cvt = NewLoad; 7133 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7134 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7135 DAG.getValueType(TruncVT)); 7136 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7137 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7138 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7139 } else { 7140 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7141 } 7142 7143 EVT VT = Ld->getValueType(0); 7144 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7145 7146 DCI.AddToWorklist(Cvt.getNode()); 7147 7148 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7149 // the appropriate extension from the 32-bit load. 7150 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7151 DCI.AddToWorklist(Cvt.getNode()); 7152 7153 // Handle conversion back to floating point if necessary. 7154 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7155 7156 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7157 } 7158 7159 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7160 SDLoc DL(Op); 7161 LoadSDNode *Load = cast<LoadSDNode>(Op); 7162 ISD::LoadExtType ExtType = Load->getExtensionType(); 7163 EVT MemVT = Load->getMemoryVT(); 7164 7165 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7166 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7167 return SDValue(); 7168 7169 // FIXME: Copied from PPC 7170 // First, load into 32 bits, then truncate to 1 bit. 7171 7172 SDValue Chain = Load->getChain(); 7173 SDValue BasePtr = Load->getBasePtr(); 7174 MachineMemOperand *MMO = Load->getMemOperand(); 7175 7176 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7177 7178 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7179 BasePtr, RealMemVT, MMO); 7180 7181 if (!MemVT.isVector()) { 7182 SDValue Ops[] = { 7183 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7184 NewLD.getValue(1) 7185 }; 7186 7187 return DAG.getMergeValues(Ops, DL); 7188 } 7189 7190 SmallVector<SDValue, 3> Elts; 7191 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7192 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7193 DAG.getConstant(I, DL, MVT::i32)); 7194 7195 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7196 } 7197 7198 SDValue Ops[] = { 7199 DAG.getBuildVector(MemVT, DL, Elts), 7200 NewLD.getValue(1) 7201 }; 7202 7203 return DAG.getMergeValues(Ops, DL); 7204 } 7205 7206 if (!MemVT.isVector()) 7207 return SDValue(); 7208 7209 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7210 "Custom lowering for non-i32 vectors hasn't been implemented."); 7211 7212 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT, 7213 *Load->getMemOperand())) { 7214 SDValue Ops[2]; 7215 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7216 return DAG.getMergeValues(Ops, DL); 7217 } 7218 7219 unsigned Alignment = Load->getAlignment(); 7220 unsigned AS = Load->getAddressSpace(); 7221 if (Subtarget->hasLDSMisalignedBug() && 7222 AS == AMDGPUAS::FLAT_ADDRESS && 7223 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7224 return SplitVectorLoad(Op, DAG); 7225 } 7226 7227 MachineFunction &MF = DAG.getMachineFunction(); 7228 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7229 // If there is a possibilty that flat instruction access scratch memory 7230 // then we need to use the same legalization rules we use for private. 7231 if (AS == AMDGPUAS::FLAT_ADDRESS) 7232 AS = MFI->hasFlatScratchInit() ? 7233 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7234 7235 unsigned NumElements = MemVT.getVectorNumElements(); 7236 7237 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7238 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7239 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7240 if (MemVT.isPow2VectorType()) 7241 return SDValue(); 7242 if (NumElements == 3) 7243 return WidenVectorLoad(Op, DAG); 7244 return SplitVectorLoad(Op, DAG); 7245 } 7246 // Non-uniform loads will be selected to MUBUF instructions, so they 7247 // have the same legalization requirements as global and private 7248 // loads. 7249 // 7250 } 7251 7252 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7253 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7254 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7255 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7256 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7257 Alignment >= 4 && NumElements < 32) { 7258 if (MemVT.isPow2VectorType()) 7259 return SDValue(); 7260 if (NumElements == 3) 7261 return WidenVectorLoad(Op, DAG); 7262 return SplitVectorLoad(Op, DAG); 7263 } 7264 // Non-uniform loads will be selected to MUBUF instructions, so they 7265 // have the same legalization requirements as global and private 7266 // loads. 7267 // 7268 } 7269 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7270 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7271 AS == AMDGPUAS::GLOBAL_ADDRESS || 7272 AS == AMDGPUAS::FLAT_ADDRESS) { 7273 if (NumElements > 4) 7274 return SplitVectorLoad(Op, DAG); 7275 // v3 loads not supported on SI. 7276 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7277 return WidenVectorLoad(Op, DAG); 7278 // v3 and v4 loads are supported for private and global memory. 7279 return SDValue(); 7280 } 7281 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7282 // Depending on the setting of the private_element_size field in the 7283 // resource descriptor, we can only make private accesses up to a certain 7284 // size. 7285 switch (Subtarget->getMaxPrivateElementSize()) { 7286 case 4: 7287 return scalarizeVectorLoad(Load, DAG); 7288 case 8: 7289 if (NumElements > 2) 7290 return SplitVectorLoad(Op, DAG); 7291 return SDValue(); 7292 case 16: 7293 // Same as global/flat 7294 if (NumElements > 4) 7295 return SplitVectorLoad(Op, DAG); 7296 // v3 loads not supported on SI. 7297 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7298 return WidenVectorLoad(Op, DAG); 7299 return SDValue(); 7300 default: 7301 llvm_unreachable("unsupported private_element_size"); 7302 } 7303 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7304 // Use ds_read_b128 if possible. 7305 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7306 MemVT.getStoreSize() == 16) 7307 return SDValue(); 7308 7309 if (NumElements > 2) 7310 return SplitVectorLoad(Op, DAG); 7311 7312 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7313 // address is negative, then the instruction is incorrectly treated as 7314 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7315 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7316 // load later in the SILoadStoreOptimizer. 7317 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7318 NumElements == 2 && MemVT.getStoreSize() == 8 && 7319 Load->getAlignment() < 8) { 7320 return SplitVectorLoad(Op, DAG); 7321 } 7322 } 7323 return SDValue(); 7324 } 7325 7326 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7327 EVT VT = Op.getValueType(); 7328 assert(VT.getSizeInBits() == 64); 7329 7330 SDLoc DL(Op); 7331 SDValue Cond = Op.getOperand(0); 7332 7333 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7334 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7335 7336 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7337 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7338 7339 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7340 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7341 7342 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7343 7344 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7345 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7346 7347 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7348 7349 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7350 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7351 } 7352 7353 // Catch division cases where we can use shortcuts with rcp and rsq 7354 // instructions. 7355 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7356 SelectionDAG &DAG) const { 7357 SDLoc SL(Op); 7358 SDValue LHS = Op.getOperand(0); 7359 SDValue RHS = Op.getOperand(1); 7360 EVT VT = Op.getValueType(); 7361 const SDNodeFlags Flags = Op->getFlags(); 7362 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7363 7364 if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals()) 7365 return SDValue(); 7366 7367 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7368 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7369 if (CLHS->isExactlyValue(1.0)) { 7370 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7371 // the CI documentation has a worst case error of 1 ulp. 7372 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7373 // use it as long as we aren't trying to use denormals. 7374 // 7375 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7376 7377 // 1.0 / sqrt(x) -> rsq(x) 7378 7379 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7380 // error seems really high at 2^29 ULP. 7381 if (RHS.getOpcode() == ISD::FSQRT) 7382 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7383 7384 // 1.0 / x -> rcp(x) 7385 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7386 } 7387 7388 // Same as for 1.0, but expand the sign out of the constant. 7389 if (CLHS->isExactlyValue(-1.0)) { 7390 // -1.0 / x -> rcp (fneg x) 7391 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7392 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7393 } 7394 } 7395 } 7396 7397 if (Unsafe) { 7398 // Turn into multiply by the reciprocal. 7399 // x / y -> x * (1.0 / y) 7400 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7401 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7402 } 7403 7404 return SDValue(); 7405 } 7406 7407 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7408 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7409 if (GlueChain->getNumValues() <= 1) { 7410 return DAG.getNode(Opcode, SL, VT, A, B); 7411 } 7412 7413 assert(GlueChain->getNumValues() == 3); 7414 7415 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7416 switch (Opcode) { 7417 default: llvm_unreachable("no chain equivalent for opcode"); 7418 case ISD::FMUL: 7419 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7420 break; 7421 } 7422 7423 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7424 GlueChain.getValue(2)); 7425 } 7426 7427 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7428 EVT VT, SDValue A, SDValue B, SDValue C, 7429 SDValue GlueChain) { 7430 if (GlueChain->getNumValues() <= 1) { 7431 return DAG.getNode(Opcode, SL, VT, A, B, C); 7432 } 7433 7434 assert(GlueChain->getNumValues() == 3); 7435 7436 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7437 switch (Opcode) { 7438 default: llvm_unreachable("no chain equivalent for opcode"); 7439 case ISD::FMA: 7440 Opcode = AMDGPUISD::FMA_W_CHAIN; 7441 break; 7442 } 7443 7444 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7445 GlueChain.getValue(2)); 7446 } 7447 7448 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7449 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7450 return FastLowered; 7451 7452 SDLoc SL(Op); 7453 SDValue Src0 = Op.getOperand(0); 7454 SDValue Src1 = Op.getOperand(1); 7455 7456 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7457 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7458 7459 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7460 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7461 7462 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7463 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7464 7465 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7466 } 7467 7468 // Faster 2.5 ULP division that does not support denormals. 7469 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7470 SDLoc SL(Op); 7471 SDValue LHS = Op.getOperand(1); 7472 SDValue RHS = Op.getOperand(2); 7473 7474 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7475 7476 const APFloat K0Val(BitsToFloat(0x6f800000)); 7477 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7478 7479 const APFloat K1Val(BitsToFloat(0x2f800000)); 7480 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7481 7482 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7483 7484 EVT SetCCVT = 7485 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7486 7487 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7488 7489 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7490 7491 // TODO: Should this propagate fast-math-flags? 7492 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7493 7494 // rcp does not support denormals. 7495 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7496 7497 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7498 7499 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7500 } 7501 7502 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7503 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7504 return FastLowered; 7505 7506 SDLoc SL(Op); 7507 SDValue LHS = Op.getOperand(0); 7508 SDValue RHS = Op.getOperand(1); 7509 7510 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7511 7512 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7513 7514 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7515 RHS, RHS, LHS); 7516 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7517 LHS, RHS, LHS); 7518 7519 // Denominator is scaled to not be denormal, so using rcp is ok. 7520 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7521 DenominatorScaled); 7522 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7523 DenominatorScaled); 7524 7525 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7526 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7527 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7528 7529 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7530 7531 if (!Subtarget->hasFP32Denormals()) { 7532 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7533 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7534 SL, MVT::i32); 7535 SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7536 DAG.getEntryNode(), 7537 EnableDenormValue, BitField); 7538 SDValue Ops[3] = { 7539 NegDivScale0, 7540 EnableDenorm.getValue(0), 7541 EnableDenorm.getValue(1) 7542 }; 7543 7544 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7545 } 7546 7547 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7548 ApproxRcp, One, NegDivScale0); 7549 7550 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7551 ApproxRcp, Fma0); 7552 7553 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7554 Fma1, Fma1); 7555 7556 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7557 NumeratorScaled, Mul); 7558 7559 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7560 7561 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7562 NumeratorScaled, Fma3); 7563 7564 if (!Subtarget->hasFP32Denormals()) { 7565 const SDValue DisableDenormValue = 7566 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7567 SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7568 Fma4.getValue(1), 7569 DisableDenormValue, 7570 BitField, 7571 Fma4.getValue(2)); 7572 7573 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7574 DisableDenorm, DAG.getRoot()); 7575 DAG.setRoot(OutputChain); 7576 } 7577 7578 SDValue Scale = NumeratorScaled.getValue(1); 7579 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7580 Fma4, Fma1, Fma3, Scale); 7581 7582 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7583 } 7584 7585 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7586 if (DAG.getTarget().Options.UnsafeFPMath) 7587 return lowerFastUnsafeFDIV(Op, DAG); 7588 7589 SDLoc SL(Op); 7590 SDValue X = Op.getOperand(0); 7591 SDValue Y = Op.getOperand(1); 7592 7593 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7594 7595 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7596 7597 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7598 7599 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7600 7601 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7602 7603 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7604 7605 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7606 7607 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7608 7609 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7610 7611 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7612 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7613 7614 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7615 NegDivScale0, Mul, DivScale1); 7616 7617 SDValue Scale; 7618 7619 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7620 // Workaround a hardware bug on SI where the condition output from div_scale 7621 // is not usable. 7622 7623 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7624 7625 // Figure out if the scale to use for div_fmas. 7626 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7627 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7628 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7629 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7630 7631 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7632 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7633 7634 SDValue Scale0Hi 7635 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7636 SDValue Scale1Hi 7637 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7638 7639 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7640 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7641 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7642 } else { 7643 Scale = DivScale1.getValue(1); 7644 } 7645 7646 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7647 Fma4, Fma3, Mul, Scale); 7648 7649 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7650 } 7651 7652 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7653 EVT VT = Op.getValueType(); 7654 7655 if (VT == MVT::f32) 7656 return LowerFDIV32(Op, DAG); 7657 7658 if (VT == MVT::f64) 7659 return LowerFDIV64(Op, DAG); 7660 7661 if (VT == MVT::f16) 7662 return LowerFDIV16(Op, DAG); 7663 7664 llvm_unreachable("Unexpected type for fdiv"); 7665 } 7666 7667 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7668 SDLoc DL(Op); 7669 StoreSDNode *Store = cast<StoreSDNode>(Op); 7670 EVT VT = Store->getMemoryVT(); 7671 7672 if (VT == MVT::i1) { 7673 return DAG.getTruncStore(Store->getChain(), DL, 7674 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7675 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7676 } 7677 7678 assert(VT.isVector() && 7679 Store->getValue().getValueType().getScalarType() == MVT::i32); 7680 7681 if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT, 7682 *Store->getMemOperand())) { 7683 return expandUnalignedStore(Store, DAG); 7684 } 7685 7686 unsigned AS = Store->getAddressSpace(); 7687 if (Subtarget->hasLDSMisalignedBug() && 7688 AS == AMDGPUAS::FLAT_ADDRESS && 7689 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7690 return SplitVectorStore(Op, DAG); 7691 } 7692 7693 MachineFunction &MF = DAG.getMachineFunction(); 7694 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7695 // If there is a possibilty that flat instruction access scratch memory 7696 // then we need to use the same legalization rules we use for private. 7697 if (AS == AMDGPUAS::FLAT_ADDRESS) 7698 AS = MFI->hasFlatScratchInit() ? 7699 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7700 7701 unsigned NumElements = VT.getVectorNumElements(); 7702 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7703 AS == AMDGPUAS::FLAT_ADDRESS) { 7704 if (NumElements > 4) 7705 return SplitVectorStore(Op, DAG); 7706 // v3 stores not supported on SI. 7707 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7708 return SplitVectorStore(Op, DAG); 7709 return SDValue(); 7710 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7711 switch (Subtarget->getMaxPrivateElementSize()) { 7712 case 4: 7713 return scalarizeVectorStore(Store, DAG); 7714 case 8: 7715 if (NumElements > 2) 7716 return SplitVectorStore(Op, DAG); 7717 return SDValue(); 7718 case 16: 7719 if (NumElements > 4 || NumElements == 3) 7720 return SplitVectorStore(Op, DAG); 7721 return SDValue(); 7722 default: 7723 llvm_unreachable("unsupported private_element_size"); 7724 } 7725 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7726 // Use ds_write_b128 if possible. 7727 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7728 VT.getStoreSize() == 16 && NumElements != 3) 7729 return SDValue(); 7730 7731 if (NumElements > 2) 7732 return SplitVectorStore(Op, DAG); 7733 7734 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7735 // address is negative, then the instruction is incorrectly treated as 7736 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7737 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7738 // store later in the SILoadStoreOptimizer. 7739 if (!Subtarget->hasUsableDSOffset() && 7740 NumElements == 2 && VT.getStoreSize() == 8 && 7741 Store->getAlignment() < 8) { 7742 return SplitVectorStore(Op, DAG); 7743 } 7744 7745 return SDValue(); 7746 } else { 7747 llvm_unreachable("unhandled address space"); 7748 } 7749 } 7750 7751 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7752 SDLoc DL(Op); 7753 EVT VT = Op.getValueType(); 7754 SDValue Arg = Op.getOperand(0); 7755 SDValue TrigVal; 7756 7757 // TODO: Should this propagate fast-math-flags? 7758 7759 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7760 7761 if (Subtarget->hasTrigReducedRange()) { 7762 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7763 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7764 } else { 7765 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7766 } 7767 7768 switch (Op.getOpcode()) { 7769 case ISD::FCOS: 7770 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7771 case ISD::FSIN: 7772 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7773 default: 7774 llvm_unreachable("Wrong trig opcode"); 7775 } 7776 } 7777 7778 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7779 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7780 assert(AtomicNode->isCompareAndSwap()); 7781 unsigned AS = AtomicNode->getAddressSpace(); 7782 7783 // No custom lowering required for local address space 7784 if (!isFlatGlobalAddrSpace(AS)) 7785 return Op; 7786 7787 // Non-local address space requires custom lowering for atomic compare 7788 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7789 SDLoc DL(Op); 7790 SDValue ChainIn = Op.getOperand(0); 7791 SDValue Addr = Op.getOperand(1); 7792 SDValue Old = Op.getOperand(2); 7793 SDValue New = Op.getOperand(3); 7794 EVT VT = Op.getValueType(); 7795 MVT SimpleVT = VT.getSimpleVT(); 7796 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7797 7798 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7799 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7800 7801 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7802 Ops, VT, AtomicNode->getMemOperand()); 7803 } 7804 7805 //===----------------------------------------------------------------------===// 7806 // Custom DAG optimizations 7807 //===----------------------------------------------------------------------===// 7808 7809 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7810 DAGCombinerInfo &DCI) const { 7811 EVT VT = N->getValueType(0); 7812 EVT ScalarVT = VT.getScalarType(); 7813 if (ScalarVT != MVT::f32) 7814 return SDValue(); 7815 7816 SelectionDAG &DAG = DCI.DAG; 7817 SDLoc DL(N); 7818 7819 SDValue Src = N->getOperand(0); 7820 EVT SrcVT = Src.getValueType(); 7821 7822 // TODO: We could try to match extracting the higher bytes, which would be 7823 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7824 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7825 // about in practice. 7826 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7827 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7828 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7829 DCI.AddToWorklist(Cvt.getNode()); 7830 return Cvt; 7831 } 7832 } 7833 7834 return SDValue(); 7835 } 7836 7837 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7838 7839 // This is a variant of 7840 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7841 // 7842 // The normal DAG combiner will do this, but only if the add has one use since 7843 // that would increase the number of instructions. 7844 // 7845 // This prevents us from seeing a constant offset that can be folded into a 7846 // memory instruction's addressing mode. If we know the resulting add offset of 7847 // a pointer can be folded into an addressing offset, we can replace the pointer 7848 // operand with the add of new constant offset. This eliminates one of the uses, 7849 // and may allow the remaining use to also be simplified. 7850 // 7851 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7852 unsigned AddrSpace, 7853 EVT MemVT, 7854 DAGCombinerInfo &DCI) const { 7855 SDValue N0 = N->getOperand(0); 7856 SDValue N1 = N->getOperand(1); 7857 7858 // We only do this to handle cases where it's profitable when there are 7859 // multiple uses of the add, so defer to the standard combine. 7860 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7861 N0->hasOneUse()) 7862 return SDValue(); 7863 7864 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7865 if (!CN1) 7866 return SDValue(); 7867 7868 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7869 if (!CAdd) 7870 return SDValue(); 7871 7872 // If the resulting offset is too large, we can't fold it into the addressing 7873 // mode offset. 7874 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7875 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7876 7877 AddrMode AM; 7878 AM.HasBaseReg = true; 7879 AM.BaseOffs = Offset.getSExtValue(); 7880 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7881 return SDValue(); 7882 7883 SelectionDAG &DAG = DCI.DAG; 7884 SDLoc SL(N); 7885 EVT VT = N->getValueType(0); 7886 7887 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 7888 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 7889 7890 SDNodeFlags Flags; 7891 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 7892 (N0.getOpcode() == ISD::OR || 7893 N0->getFlags().hasNoUnsignedWrap())); 7894 7895 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 7896 } 7897 7898 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 7899 DAGCombinerInfo &DCI) const { 7900 SDValue Ptr = N->getBasePtr(); 7901 SelectionDAG &DAG = DCI.DAG; 7902 SDLoc SL(N); 7903 7904 // TODO: We could also do this for multiplies. 7905 if (Ptr.getOpcode() == ISD::SHL) { 7906 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 7907 N->getMemoryVT(), DCI); 7908 if (NewPtr) { 7909 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 7910 7911 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 7912 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 7913 } 7914 } 7915 7916 return SDValue(); 7917 } 7918 7919 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 7920 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 7921 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 7922 (Opc == ISD::XOR && Val == 0); 7923 } 7924 7925 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 7926 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 7927 // integer combine opportunities since most 64-bit operations are decomposed 7928 // this way. TODO: We won't want this for SALU especially if it is an inline 7929 // immediate. 7930 SDValue SITargetLowering::splitBinaryBitConstantOp( 7931 DAGCombinerInfo &DCI, 7932 const SDLoc &SL, 7933 unsigned Opc, SDValue LHS, 7934 const ConstantSDNode *CRHS) const { 7935 uint64_t Val = CRHS->getZExtValue(); 7936 uint32_t ValLo = Lo_32(Val); 7937 uint32_t ValHi = Hi_32(Val); 7938 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 7939 7940 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 7941 bitOpWithConstantIsReducible(Opc, ValHi)) || 7942 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 7943 // If we need to materialize a 64-bit immediate, it will be split up later 7944 // anyway. Avoid creating the harder to understand 64-bit immediate 7945 // materialization. 7946 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 7947 } 7948 7949 return SDValue(); 7950 } 7951 7952 // Returns true if argument is a boolean value which is not serialized into 7953 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 7954 static bool isBoolSGPR(SDValue V) { 7955 if (V.getValueType() != MVT::i1) 7956 return false; 7957 switch (V.getOpcode()) { 7958 default: break; 7959 case ISD::SETCC: 7960 case ISD::AND: 7961 case ISD::OR: 7962 case ISD::XOR: 7963 case AMDGPUISD::FP_CLASS: 7964 return true; 7965 } 7966 return false; 7967 } 7968 7969 // If a constant has all zeroes or all ones within each byte return it. 7970 // Otherwise return 0. 7971 static uint32_t getConstantPermuteMask(uint32_t C) { 7972 // 0xff for any zero byte in the mask 7973 uint32_t ZeroByteMask = 0; 7974 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 7975 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 7976 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 7977 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 7978 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 7979 if ((NonZeroByteMask & C) != NonZeroByteMask) 7980 return 0; // Partial bytes selected. 7981 return C; 7982 } 7983 7984 // Check if a node selects whole bytes from its operand 0 starting at a byte 7985 // boundary while masking the rest. Returns select mask as in the v_perm_b32 7986 // or -1 if not succeeded. 7987 // Note byte select encoding: 7988 // value 0-3 selects corresponding source byte; 7989 // value 0xc selects zero; 7990 // value 0xff selects 0xff. 7991 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 7992 assert(V.getValueSizeInBits() == 32); 7993 7994 if (V.getNumOperands() != 2) 7995 return ~0; 7996 7997 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 7998 if (!N1) 7999 return ~0; 8000 8001 uint32_t C = N1->getZExtValue(); 8002 8003 switch (V.getOpcode()) { 8004 default: 8005 break; 8006 case ISD::AND: 8007 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8008 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8009 } 8010 break; 8011 8012 case ISD::OR: 8013 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8014 return (0x03020100 & ~ConstMask) | ConstMask; 8015 } 8016 break; 8017 8018 case ISD::SHL: 8019 if (C % 8) 8020 return ~0; 8021 8022 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8023 8024 case ISD::SRL: 8025 if (C % 8) 8026 return ~0; 8027 8028 return uint32_t(0x0c0c0c0c03020100ull >> C); 8029 } 8030 8031 return ~0; 8032 } 8033 8034 SDValue SITargetLowering::performAndCombine(SDNode *N, 8035 DAGCombinerInfo &DCI) const { 8036 if (DCI.isBeforeLegalize()) 8037 return SDValue(); 8038 8039 SelectionDAG &DAG = DCI.DAG; 8040 EVT VT = N->getValueType(0); 8041 SDValue LHS = N->getOperand(0); 8042 SDValue RHS = N->getOperand(1); 8043 8044 8045 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8046 if (VT == MVT::i64 && CRHS) { 8047 if (SDValue Split 8048 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8049 return Split; 8050 } 8051 8052 if (CRHS && VT == MVT::i32) { 8053 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8054 // nb = number of trailing zeroes in mask 8055 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8056 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8057 uint64_t Mask = CRHS->getZExtValue(); 8058 unsigned Bits = countPopulation(Mask); 8059 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8060 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8061 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8062 unsigned Shift = CShift->getZExtValue(); 8063 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8064 unsigned Offset = NB + Shift; 8065 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8066 SDLoc SL(N); 8067 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8068 LHS->getOperand(0), 8069 DAG.getConstant(Offset, SL, MVT::i32), 8070 DAG.getConstant(Bits, SL, MVT::i32)); 8071 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8072 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8073 DAG.getValueType(NarrowVT)); 8074 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8075 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8076 return Shl; 8077 } 8078 } 8079 } 8080 8081 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8082 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8083 isa<ConstantSDNode>(LHS.getOperand(2))) { 8084 uint32_t Sel = getConstantPermuteMask(Mask); 8085 if (!Sel) 8086 return SDValue(); 8087 8088 // Select 0xc for all zero bytes 8089 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8090 SDLoc DL(N); 8091 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8092 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8093 } 8094 } 8095 8096 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8097 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8098 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8099 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8100 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8101 8102 SDValue X = LHS.getOperand(0); 8103 SDValue Y = RHS.getOperand(0); 8104 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8105 return SDValue(); 8106 8107 if (LCC == ISD::SETO) { 8108 if (X != LHS.getOperand(1)) 8109 return SDValue(); 8110 8111 if (RCC == ISD::SETUNE) { 8112 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8113 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8114 return SDValue(); 8115 8116 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8117 SIInstrFlags::N_SUBNORMAL | 8118 SIInstrFlags::N_ZERO | 8119 SIInstrFlags::P_ZERO | 8120 SIInstrFlags::P_SUBNORMAL | 8121 SIInstrFlags::P_NORMAL; 8122 8123 static_assert(((~(SIInstrFlags::S_NAN | 8124 SIInstrFlags::Q_NAN | 8125 SIInstrFlags::N_INFINITY | 8126 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8127 "mask not equal"); 8128 8129 SDLoc DL(N); 8130 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8131 X, DAG.getConstant(Mask, DL, MVT::i32)); 8132 } 8133 } 8134 } 8135 8136 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8137 std::swap(LHS, RHS); 8138 8139 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8140 RHS.hasOneUse()) { 8141 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8142 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8143 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8144 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8145 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8146 (RHS.getOperand(0) == LHS.getOperand(0) && 8147 LHS.getOperand(0) == LHS.getOperand(1))) { 8148 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8149 unsigned NewMask = LCC == ISD::SETO ? 8150 Mask->getZExtValue() & ~OrdMask : 8151 Mask->getZExtValue() & OrdMask; 8152 8153 SDLoc DL(N); 8154 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8155 DAG.getConstant(NewMask, DL, MVT::i32)); 8156 } 8157 } 8158 8159 if (VT == MVT::i32 && 8160 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8161 // and x, (sext cc from i1) => select cc, x, 0 8162 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8163 std::swap(LHS, RHS); 8164 if (isBoolSGPR(RHS.getOperand(0))) 8165 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8166 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8167 } 8168 8169 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8170 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8171 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8172 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8173 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8174 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8175 if (LHSMask != ~0u && RHSMask != ~0u) { 8176 // Canonicalize the expression in an attempt to have fewer unique masks 8177 // and therefore fewer registers used to hold the masks. 8178 if (LHSMask > RHSMask) { 8179 std::swap(LHSMask, RHSMask); 8180 std::swap(LHS, RHS); 8181 } 8182 8183 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8184 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8185 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8186 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8187 8188 // Check of we need to combine values from two sources within a byte. 8189 if (!(LHSUsedLanes & RHSUsedLanes) && 8190 // If we select high and lower word keep it for SDWA. 8191 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8192 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8193 // Each byte in each mask is either selector mask 0-3, or has higher 8194 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8195 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8196 // mask which is not 0xff wins. By anding both masks we have a correct 8197 // result except that 0x0c shall be corrected to give 0x0c only. 8198 uint32_t Mask = LHSMask & RHSMask; 8199 for (unsigned I = 0; I < 32; I += 8) { 8200 uint32_t ByteSel = 0xff << I; 8201 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8202 Mask &= (0x0c << I) & 0xffffffff; 8203 } 8204 8205 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8206 // or 0x0c. 8207 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8208 SDLoc DL(N); 8209 8210 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8211 LHS.getOperand(0), RHS.getOperand(0), 8212 DAG.getConstant(Sel, DL, MVT::i32)); 8213 } 8214 } 8215 } 8216 8217 return SDValue(); 8218 } 8219 8220 SDValue SITargetLowering::performOrCombine(SDNode *N, 8221 DAGCombinerInfo &DCI) const { 8222 SelectionDAG &DAG = DCI.DAG; 8223 SDValue LHS = N->getOperand(0); 8224 SDValue RHS = N->getOperand(1); 8225 8226 EVT VT = N->getValueType(0); 8227 if (VT == MVT::i1) { 8228 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8229 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8230 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8231 SDValue Src = LHS.getOperand(0); 8232 if (Src != RHS.getOperand(0)) 8233 return SDValue(); 8234 8235 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8236 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8237 if (!CLHS || !CRHS) 8238 return SDValue(); 8239 8240 // Only 10 bits are used. 8241 static const uint32_t MaxMask = 0x3ff; 8242 8243 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8244 SDLoc DL(N); 8245 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8246 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8247 } 8248 8249 return SDValue(); 8250 } 8251 8252 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8253 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8254 LHS.getOpcode() == AMDGPUISD::PERM && 8255 isa<ConstantSDNode>(LHS.getOperand(2))) { 8256 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8257 if (!Sel) 8258 return SDValue(); 8259 8260 Sel |= LHS.getConstantOperandVal(2); 8261 SDLoc DL(N); 8262 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8263 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8264 } 8265 8266 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8267 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8268 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8269 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8270 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8271 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8272 if (LHSMask != ~0u && RHSMask != ~0u) { 8273 // Canonicalize the expression in an attempt to have fewer unique masks 8274 // and therefore fewer registers used to hold the masks. 8275 if (LHSMask > RHSMask) { 8276 std::swap(LHSMask, RHSMask); 8277 std::swap(LHS, RHS); 8278 } 8279 8280 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8281 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8282 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8283 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8284 8285 // Check of we need to combine values from two sources within a byte. 8286 if (!(LHSUsedLanes & RHSUsedLanes) && 8287 // If we select high and lower word keep it for SDWA. 8288 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8289 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8290 // Kill zero bytes selected by other mask. Zero value is 0xc. 8291 LHSMask &= ~RHSUsedLanes; 8292 RHSMask &= ~LHSUsedLanes; 8293 // Add 4 to each active LHS lane 8294 LHSMask |= LHSUsedLanes & 0x04040404; 8295 // Combine masks 8296 uint32_t Sel = LHSMask | RHSMask; 8297 SDLoc DL(N); 8298 8299 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8300 LHS.getOperand(0), RHS.getOperand(0), 8301 DAG.getConstant(Sel, DL, MVT::i32)); 8302 } 8303 } 8304 } 8305 8306 if (VT != MVT::i64) 8307 return SDValue(); 8308 8309 // TODO: This could be a generic combine with a predicate for extracting the 8310 // high half of an integer being free. 8311 8312 // (or i64:x, (zero_extend i32:y)) -> 8313 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8314 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8315 RHS.getOpcode() != ISD::ZERO_EXTEND) 8316 std::swap(LHS, RHS); 8317 8318 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8319 SDValue ExtSrc = RHS.getOperand(0); 8320 EVT SrcVT = ExtSrc.getValueType(); 8321 if (SrcVT == MVT::i32) { 8322 SDLoc SL(N); 8323 SDValue LowLHS, HiBits; 8324 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8325 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8326 8327 DCI.AddToWorklist(LowOr.getNode()); 8328 DCI.AddToWorklist(HiBits.getNode()); 8329 8330 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8331 LowOr, HiBits); 8332 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8333 } 8334 } 8335 8336 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8337 if (CRHS) { 8338 if (SDValue Split 8339 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8340 return Split; 8341 } 8342 8343 return SDValue(); 8344 } 8345 8346 SDValue SITargetLowering::performXorCombine(SDNode *N, 8347 DAGCombinerInfo &DCI) const { 8348 EVT VT = N->getValueType(0); 8349 if (VT != MVT::i64) 8350 return SDValue(); 8351 8352 SDValue LHS = N->getOperand(0); 8353 SDValue RHS = N->getOperand(1); 8354 8355 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8356 if (CRHS) { 8357 if (SDValue Split 8358 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8359 return Split; 8360 } 8361 8362 return SDValue(); 8363 } 8364 8365 // Instructions that will be lowered with a final instruction that zeros the 8366 // high result bits. 8367 // XXX - probably only need to list legal operations. 8368 static bool fp16SrcZerosHighBits(unsigned Opc) { 8369 switch (Opc) { 8370 case ISD::FADD: 8371 case ISD::FSUB: 8372 case ISD::FMUL: 8373 case ISD::FDIV: 8374 case ISD::FREM: 8375 case ISD::FMA: 8376 case ISD::FMAD: 8377 case ISD::FCANONICALIZE: 8378 case ISD::FP_ROUND: 8379 case ISD::UINT_TO_FP: 8380 case ISD::SINT_TO_FP: 8381 case ISD::FABS: 8382 // Fabs is lowered to a bit operation, but it's an and which will clear the 8383 // high bits anyway. 8384 case ISD::FSQRT: 8385 case ISD::FSIN: 8386 case ISD::FCOS: 8387 case ISD::FPOWI: 8388 case ISD::FPOW: 8389 case ISD::FLOG: 8390 case ISD::FLOG2: 8391 case ISD::FLOG10: 8392 case ISD::FEXP: 8393 case ISD::FEXP2: 8394 case ISD::FCEIL: 8395 case ISD::FTRUNC: 8396 case ISD::FRINT: 8397 case ISD::FNEARBYINT: 8398 case ISD::FROUND: 8399 case ISD::FFLOOR: 8400 case ISD::FMINNUM: 8401 case ISD::FMAXNUM: 8402 case AMDGPUISD::FRACT: 8403 case AMDGPUISD::CLAMP: 8404 case AMDGPUISD::COS_HW: 8405 case AMDGPUISD::SIN_HW: 8406 case AMDGPUISD::FMIN3: 8407 case AMDGPUISD::FMAX3: 8408 case AMDGPUISD::FMED3: 8409 case AMDGPUISD::FMAD_FTZ: 8410 case AMDGPUISD::RCP: 8411 case AMDGPUISD::RSQ: 8412 case AMDGPUISD::RCP_IFLAG: 8413 case AMDGPUISD::LDEXP: 8414 return true; 8415 default: 8416 // fcopysign, select and others may be lowered to 32-bit bit operations 8417 // which don't zero the high bits. 8418 return false; 8419 } 8420 } 8421 8422 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8423 DAGCombinerInfo &DCI) const { 8424 if (!Subtarget->has16BitInsts() || 8425 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8426 return SDValue(); 8427 8428 EVT VT = N->getValueType(0); 8429 if (VT != MVT::i32) 8430 return SDValue(); 8431 8432 SDValue Src = N->getOperand(0); 8433 if (Src.getValueType() != MVT::i16) 8434 return SDValue(); 8435 8436 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8437 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8438 if (Src.getOpcode() == ISD::BITCAST) { 8439 SDValue BCSrc = Src.getOperand(0); 8440 if (BCSrc.getValueType() == MVT::f16 && 8441 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8442 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8443 } 8444 8445 return SDValue(); 8446 } 8447 8448 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8449 DAGCombinerInfo &DCI) 8450 const { 8451 SDValue Src = N->getOperand(0); 8452 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8453 8454 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8455 VTSign->getVT() == MVT::i8) || 8456 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8457 VTSign->getVT() == MVT::i16)) && 8458 Src.hasOneUse()) { 8459 auto *M = cast<MemSDNode>(Src); 8460 SDValue Ops[] = { 8461 Src.getOperand(0), // Chain 8462 Src.getOperand(1), // rsrc 8463 Src.getOperand(2), // vindex 8464 Src.getOperand(3), // voffset 8465 Src.getOperand(4), // soffset 8466 Src.getOperand(5), // offset 8467 Src.getOperand(6), 8468 Src.getOperand(7) 8469 }; 8470 // replace with BUFFER_LOAD_BYTE/SHORT 8471 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8472 Src.getOperand(0).getValueType()); 8473 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8474 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8475 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8476 ResList, 8477 Ops, M->getMemoryVT(), 8478 M->getMemOperand()); 8479 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8480 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8481 } 8482 return SDValue(); 8483 } 8484 8485 SDValue SITargetLowering::performClassCombine(SDNode *N, 8486 DAGCombinerInfo &DCI) const { 8487 SelectionDAG &DAG = DCI.DAG; 8488 SDValue Mask = N->getOperand(1); 8489 8490 // fp_class x, 0 -> false 8491 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8492 if (CMask->isNullValue()) 8493 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8494 } 8495 8496 if (N->getOperand(0).isUndef()) 8497 return DAG.getUNDEF(MVT::i1); 8498 8499 return SDValue(); 8500 } 8501 8502 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8503 DAGCombinerInfo &DCI) const { 8504 EVT VT = N->getValueType(0); 8505 SDValue N0 = N->getOperand(0); 8506 8507 if (N0.isUndef()) 8508 return N0; 8509 8510 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8511 N0.getOpcode() == ISD::SINT_TO_FP)) { 8512 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8513 N->getFlags()); 8514 } 8515 8516 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8517 } 8518 8519 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8520 unsigned MaxDepth) const { 8521 unsigned Opcode = Op.getOpcode(); 8522 if (Opcode == ISD::FCANONICALIZE) 8523 return true; 8524 8525 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8526 auto F = CFP->getValueAPF(); 8527 if (F.isNaN() && F.isSignaling()) 8528 return false; 8529 return !F.isDenormal() || denormalsEnabledForType(Op.getValueType()); 8530 } 8531 8532 // If source is a result of another standard FP operation it is already in 8533 // canonical form. 8534 if (MaxDepth == 0) 8535 return false; 8536 8537 switch (Opcode) { 8538 // These will flush denorms if required. 8539 case ISD::FADD: 8540 case ISD::FSUB: 8541 case ISD::FMUL: 8542 case ISD::FCEIL: 8543 case ISD::FFLOOR: 8544 case ISD::FMA: 8545 case ISD::FMAD: 8546 case ISD::FSQRT: 8547 case ISD::FDIV: 8548 case ISD::FREM: 8549 case ISD::FP_ROUND: 8550 case ISD::FP_EXTEND: 8551 case AMDGPUISD::FMUL_LEGACY: 8552 case AMDGPUISD::FMAD_FTZ: 8553 case AMDGPUISD::RCP: 8554 case AMDGPUISD::RSQ: 8555 case AMDGPUISD::RSQ_CLAMP: 8556 case AMDGPUISD::RCP_LEGACY: 8557 case AMDGPUISD::RSQ_LEGACY: 8558 case AMDGPUISD::RCP_IFLAG: 8559 case AMDGPUISD::TRIG_PREOP: 8560 case AMDGPUISD::DIV_SCALE: 8561 case AMDGPUISD::DIV_FMAS: 8562 case AMDGPUISD::DIV_FIXUP: 8563 case AMDGPUISD::FRACT: 8564 case AMDGPUISD::LDEXP: 8565 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8566 case AMDGPUISD::CVT_F32_UBYTE0: 8567 case AMDGPUISD::CVT_F32_UBYTE1: 8568 case AMDGPUISD::CVT_F32_UBYTE2: 8569 case AMDGPUISD::CVT_F32_UBYTE3: 8570 return true; 8571 8572 // It can/will be lowered or combined as a bit operation. 8573 // Need to check their input recursively to handle. 8574 case ISD::FNEG: 8575 case ISD::FABS: 8576 case ISD::FCOPYSIGN: 8577 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8578 8579 case ISD::FSIN: 8580 case ISD::FCOS: 8581 case ISD::FSINCOS: 8582 return Op.getValueType().getScalarType() != MVT::f16; 8583 8584 case ISD::FMINNUM: 8585 case ISD::FMAXNUM: 8586 case ISD::FMINNUM_IEEE: 8587 case ISD::FMAXNUM_IEEE: 8588 case AMDGPUISD::CLAMP: 8589 case AMDGPUISD::FMED3: 8590 case AMDGPUISD::FMAX3: 8591 case AMDGPUISD::FMIN3: { 8592 // FIXME: Shouldn't treat the generic operations different based these. 8593 // However, we aren't really required to flush the result from 8594 // minnum/maxnum.. 8595 8596 // snans will be quieted, so we only need to worry about denormals. 8597 if (Subtarget->supportsMinMaxDenormModes() || 8598 denormalsEnabledForType(Op.getValueType())) 8599 return true; 8600 8601 // Flushing may be required. 8602 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8603 // targets need to check their input recursively. 8604 8605 // FIXME: Does this apply with clamp? It's implemented with max. 8606 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8607 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8608 return false; 8609 } 8610 8611 return true; 8612 } 8613 case ISD::SELECT: { 8614 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8615 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8616 } 8617 case ISD::BUILD_VECTOR: { 8618 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8619 SDValue SrcOp = Op.getOperand(i); 8620 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8621 return false; 8622 } 8623 8624 return true; 8625 } 8626 case ISD::EXTRACT_VECTOR_ELT: 8627 case ISD::EXTRACT_SUBVECTOR: { 8628 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8629 } 8630 case ISD::INSERT_VECTOR_ELT: { 8631 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8632 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8633 } 8634 case ISD::UNDEF: 8635 // Could be anything. 8636 return false; 8637 8638 case ISD::BITCAST: { 8639 // Hack round the mess we make when legalizing extract_vector_elt 8640 SDValue Src = Op.getOperand(0); 8641 if (Src.getValueType() == MVT::i16 && 8642 Src.getOpcode() == ISD::TRUNCATE) { 8643 SDValue TruncSrc = Src.getOperand(0); 8644 if (TruncSrc.getValueType() == MVT::i32 && 8645 TruncSrc.getOpcode() == ISD::BITCAST && 8646 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8647 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8648 } 8649 } 8650 8651 return false; 8652 } 8653 case ISD::INTRINSIC_WO_CHAIN: { 8654 unsigned IntrinsicID 8655 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8656 // TODO: Handle more intrinsics 8657 switch (IntrinsicID) { 8658 case Intrinsic::amdgcn_cvt_pkrtz: 8659 case Intrinsic::amdgcn_cubeid: 8660 case Intrinsic::amdgcn_frexp_mant: 8661 case Intrinsic::amdgcn_fdot2: 8662 return true; 8663 default: 8664 break; 8665 } 8666 8667 LLVM_FALLTHROUGH; 8668 } 8669 default: 8670 return denormalsEnabledForType(Op.getValueType()) && 8671 DAG.isKnownNeverSNaN(Op); 8672 } 8673 8674 llvm_unreachable("invalid operation"); 8675 } 8676 8677 // Constant fold canonicalize. 8678 SDValue SITargetLowering::getCanonicalConstantFP( 8679 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8680 // Flush denormals to 0 if not enabled. 8681 if (C.isDenormal() && !denormalsEnabledForType(VT)) 8682 return DAG.getConstantFP(0.0, SL, VT); 8683 8684 if (C.isNaN()) { 8685 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8686 if (C.isSignaling()) { 8687 // Quiet a signaling NaN. 8688 // FIXME: Is this supposed to preserve payload bits? 8689 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8690 } 8691 8692 // Make sure it is the canonical NaN bitpattern. 8693 // 8694 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8695 // immediate? 8696 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8697 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8698 } 8699 8700 // Already canonical. 8701 return DAG.getConstantFP(C, SL, VT); 8702 } 8703 8704 static bool vectorEltWillFoldAway(SDValue Op) { 8705 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8706 } 8707 8708 SDValue SITargetLowering::performFCanonicalizeCombine( 8709 SDNode *N, 8710 DAGCombinerInfo &DCI) const { 8711 SelectionDAG &DAG = DCI.DAG; 8712 SDValue N0 = N->getOperand(0); 8713 EVT VT = N->getValueType(0); 8714 8715 // fcanonicalize undef -> qnan 8716 if (N0.isUndef()) { 8717 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8718 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8719 } 8720 8721 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8722 EVT VT = N->getValueType(0); 8723 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8724 } 8725 8726 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8727 // (fcanonicalize k) 8728 // 8729 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8730 8731 // TODO: This could be better with wider vectors that will be split to v2f16, 8732 // and to consider uses since there aren't that many packed operations. 8733 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8734 isTypeLegal(MVT::v2f16)) { 8735 SDLoc SL(N); 8736 SDValue NewElts[2]; 8737 SDValue Lo = N0.getOperand(0); 8738 SDValue Hi = N0.getOperand(1); 8739 EVT EltVT = Lo.getValueType(); 8740 8741 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8742 for (unsigned I = 0; I != 2; ++I) { 8743 SDValue Op = N0.getOperand(I); 8744 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8745 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8746 CFP->getValueAPF()); 8747 } else if (Op.isUndef()) { 8748 // Handled below based on what the other operand is. 8749 NewElts[I] = Op; 8750 } else { 8751 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8752 } 8753 } 8754 8755 // If one half is undef, and one is constant, perfer a splat vector rather 8756 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8757 // cheaper to use and may be free with a packed operation. 8758 if (NewElts[0].isUndef()) { 8759 if (isa<ConstantFPSDNode>(NewElts[1])) 8760 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8761 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8762 } 8763 8764 if (NewElts[1].isUndef()) { 8765 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8766 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8767 } 8768 8769 return DAG.getBuildVector(VT, SL, NewElts); 8770 } 8771 } 8772 8773 unsigned SrcOpc = N0.getOpcode(); 8774 8775 // If it's free to do so, push canonicalizes further up the source, which may 8776 // find a canonical source. 8777 // 8778 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8779 // sNaNs. 8780 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8781 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8782 if (CRHS && N0.hasOneUse()) { 8783 SDLoc SL(N); 8784 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8785 N0.getOperand(0)); 8786 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8787 DCI.AddToWorklist(Canon0.getNode()); 8788 8789 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8790 } 8791 } 8792 8793 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8794 } 8795 8796 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8797 switch (Opc) { 8798 case ISD::FMAXNUM: 8799 case ISD::FMAXNUM_IEEE: 8800 return AMDGPUISD::FMAX3; 8801 case ISD::SMAX: 8802 return AMDGPUISD::SMAX3; 8803 case ISD::UMAX: 8804 return AMDGPUISD::UMAX3; 8805 case ISD::FMINNUM: 8806 case ISD::FMINNUM_IEEE: 8807 return AMDGPUISD::FMIN3; 8808 case ISD::SMIN: 8809 return AMDGPUISD::SMIN3; 8810 case ISD::UMIN: 8811 return AMDGPUISD::UMIN3; 8812 default: 8813 llvm_unreachable("Not a min/max opcode"); 8814 } 8815 } 8816 8817 SDValue SITargetLowering::performIntMed3ImmCombine( 8818 SelectionDAG &DAG, const SDLoc &SL, 8819 SDValue Op0, SDValue Op1, bool Signed) const { 8820 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8821 if (!K1) 8822 return SDValue(); 8823 8824 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8825 if (!K0) 8826 return SDValue(); 8827 8828 if (Signed) { 8829 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8830 return SDValue(); 8831 } else { 8832 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8833 return SDValue(); 8834 } 8835 8836 EVT VT = K0->getValueType(0); 8837 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8838 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8839 return DAG.getNode(Med3Opc, SL, VT, 8840 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8841 } 8842 8843 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8844 MVT NVT = MVT::i32; 8845 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8846 8847 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8848 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8849 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8850 8851 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8852 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8853 } 8854 8855 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8856 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8857 return C; 8858 8859 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8860 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8861 return C; 8862 } 8863 8864 return nullptr; 8865 } 8866 8867 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8868 const SDLoc &SL, 8869 SDValue Op0, 8870 SDValue Op1) const { 8871 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8872 if (!K1) 8873 return SDValue(); 8874 8875 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8876 if (!K0) 8877 return SDValue(); 8878 8879 // Ordered >= (although NaN inputs should have folded away by now). 8880 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 8881 if (Cmp == APFloat::cmpGreaterThan) 8882 return SDValue(); 8883 8884 const MachineFunction &MF = DAG.getMachineFunction(); 8885 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8886 8887 // TODO: Check IEEE bit enabled? 8888 EVT VT = Op0.getValueType(); 8889 if (Info->getMode().DX10Clamp) { 8890 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 8891 // hardware fmed3 behavior converting to a min. 8892 // FIXME: Should this be allowing -0.0? 8893 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 8894 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 8895 } 8896 8897 // med3 for f16 is only available on gfx9+, and not available for v2f16. 8898 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 8899 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 8900 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 8901 // then give the other result, which is different from med3 with a NaN 8902 // input. 8903 SDValue Var = Op0.getOperand(0); 8904 if (!DAG.isKnownNeverSNaN(Var)) 8905 return SDValue(); 8906 8907 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8908 8909 if ((!K0->hasOneUse() || 8910 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 8911 (!K1->hasOneUse() || 8912 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 8913 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 8914 Var, SDValue(K0, 0), SDValue(K1, 0)); 8915 } 8916 } 8917 8918 return SDValue(); 8919 } 8920 8921 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 8922 DAGCombinerInfo &DCI) const { 8923 SelectionDAG &DAG = DCI.DAG; 8924 8925 EVT VT = N->getValueType(0); 8926 unsigned Opc = N->getOpcode(); 8927 SDValue Op0 = N->getOperand(0); 8928 SDValue Op1 = N->getOperand(1); 8929 8930 // Only do this if the inner op has one use since this will just increases 8931 // register pressure for no benefit. 8932 8933 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 8934 !VT.isVector() && 8935 (VT == MVT::i32 || VT == MVT::f32 || 8936 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 8937 // max(max(a, b), c) -> max3(a, b, c) 8938 // min(min(a, b), c) -> min3(a, b, c) 8939 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 8940 SDLoc DL(N); 8941 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8942 DL, 8943 N->getValueType(0), 8944 Op0.getOperand(0), 8945 Op0.getOperand(1), 8946 Op1); 8947 } 8948 8949 // Try commuted. 8950 // max(a, max(b, c)) -> max3(a, b, c) 8951 // min(a, min(b, c)) -> min3(a, b, c) 8952 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 8953 SDLoc DL(N); 8954 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 8955 DL, 8956 N->getValueType(0), 8957 Op0, 8958 Op1.getOperand(0), 8959 Op1.getOperand(1)); 8960 } 8961 } 8962 8963 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 8964 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 8965 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 8966 return Med3; 8967 } 8968 8969 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 8970 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 8971 return Med3; 8972 } 8973 8974 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 8975 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 8976 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 8977 (Opc == AMDGPUISD::FMIN_LEGACY && 8978 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 8979 (VT == MVT::f32 || VT == MVT::f64 || 8980 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 8981 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 8982 Op0.hasOneUse()) { 8983 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 8984 return Res; 8985 } 8986 8987 return SDValue(); 8988 } 8989 8990 static bool isClampZeroToOne(SDValue A, SDValue B) { 8991 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 8992 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 8993 // FIXME: Should this be allowing -0.0? 8994 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 8995 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 8996 } 8997 } 8998 8999 return false; 9000 } 9001 9002 // FIXME: Should only worry about snans for version with chain. 9003 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9004 DAGCombinerInfo &DCI) const { 9005 EVT VT = N->getValueType(0); 9006 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9007 // NaNs. With a NaN input, the order of the operands may change the result. 9008 9009 SelectionDAG &DAG = DCI.DAG; 9010 SDLoc SL(N); 9011 9012 SDValue Src0 = N->getOperand(0); 9013 SDValue Src1 = N->getOperand(1); 9014 SDValue Src2 = N->getOperand(2); 9015 9016 if (isClampZeroToOne(Src0, Src1)) { 9017 // const_a, const_b, x -> clamp is safe in all cases including signaling 9018 // nans. 9019 // FIXME: Should this be allowing -0.0? 9020 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9021 } 9022 9023 const MachineFunction &MF = DAG.getMachineFunction(); 9024 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9025 9026 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9027 // handling no dx10-clamp? 9028 if (Info->getMode().DX10Clamp) { 9029 // If NaNs is clamped to 0, we are free to reorder the inputs. 9030 9031 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9032 std::swap(Src0, Src1); 9033 9034 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9035 std::swap(Src1, Src2); 9036 9037 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9038 std::swap(Src0, Src1); 9039 9040 if (isClampZeroToOne(Src1, Src2)) 9041 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9042 } 9043 9044 return SDValue(); 9045 } 9046 9047 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9048 DAGCombinerInfo &DCI) const { 9049 SDValue Src0 = N->getOperand(0); 9050 SDValue Src1 = N->getOperand(1); 9051 if (Src0.isUndef() && Src1.isUndef()) 9052 return DCI.DAG.getUNDEF(N->getValueType(0)); 9053 return SDValue(); 9054 } 9055 9056 SDValue SITargetLowering::performExtractVectorEltCombine( 9057 SDNode *N, DAGCombinerInfo &DCI) const { 9058 SDValue Vec = N->getOperand(0); 9059 SelectionDAG &DAG = DCI.DAG; 9060 9061 EVT VecVT = Vec.getValueType(); 9062 EVT EltVT = VecVT.getVectorElementType(); 9063 9064 if ((Vec.getOpcode() == ISD::FNEG || 9065 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9066 SDLoc SL(N); 9067 EVT EltVT = N->getValueType(0); 9068 SDValue Idx = N->getOperand(1); 9069 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9070 Vec.getOperand(0), Idx); 9071 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9072 } 9073 9074 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9075 // => 9076 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9077 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9078 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9079 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9080 SDLoc SL(N); 9081 EVT EltVT = N->getValueType(0); 9082 SDValue Idx = N->getOperand(1); 9083 unsigned Opc = Vec.getOpcode(); 9084 9085 switch(Opc) { 9086 default: 9087 break; 9088 // TODO: Support other binary operations. 9089 case ISD::FADD: 9090 case ISD::FSUB: 9091 case ISD::FMUL: 9092 case ISD::ADD: 9093 case ISD::UMIN: 9094 case ISD::UMAX: 9095 case ISD::SMIN: 9096 case ISD::SMAX: 9097 case ISD::FMAXNUM: 9098 case ISD::FMINNUM: 9099 case ISD::FMAXNUM_IEEE: 9100 case ISD::FMINNUM_IEEE: { 9101 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9102 Vec.getOperand(0), Idx); 9103 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9104 Vec.getOperand(1), Idx); 9105 9106 DCI.AddToWorklist(Elt0.getNode()); 9107 DCI.AddToWorklist(Elt1.getNode()); 9108 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9109 } 9110 } 9111 } 9112 9113 unsigned VecSize = VecVT.getSizeInBits(); 9114 unsigned EltSize = EltVT.getSizeInBits(); 9115 9116 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9117 // This elminates non-constant index and subsequent movrel or scratch access. 9118 // Sub-dword vectors of size 2 dword or less have better implementation. 9119 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9120 // instructions. 9121 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9122 !isa<ConstantSDNode>(N->getOperand(1))) { 9123 SDLoc SL(N); 9124 SDValue Idx = N->getOperand(1); 9125 EVT IdxVT = Idx.getValueType(); 9126 SDValue V; 9127 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9128 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9129 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9130 if (I == 0) 9131 V = Elt; 9132 else 9133 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9134 } 9135 return V; 9136 } 9137 9138 if (!DCI.isBeforeLegalize()) 9139 return SDValue(); 9140 9141 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9142 // elements. This exposes more load reduction opportunities by replacing 9143 // multiple small extract_vector_elements with a single 32-bit extract. 9144 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9145 if (isa<MemSDNode>(Vec) && 9146 EltSize <= 16 && 9147 EltVT.isByteSized() && 9148 VecSize > 32 && 9149 VecSize % 32 == 0 && 9150 Idx) { 9151 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9152 9153 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9154 unsigned EltIdx = BitIndex / 32; 9155 unsigned LeftoverBitIdx = BitIndex % 32; 9156 SDLoc SL(N); 9157 9158 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9159 DCI.AddToWorklist(Cast.getNode()); 9160 9161 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9162 DAG.getConstant(EltIdx, SL, MVT::i32)); 9163 DCI.AddToWorklist(Elt.getNode()); 9164 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9165 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9166 DCI.AddToWorklist(Srl.getNode()); 9167 9168 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9169 DCI.AddToWorklist(Trunc.getNode()); 9170 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9171 } 9172 9173 return SDValue(); 9174 } 9175 9176 SDValue 9177 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9178 DAGCombinerInfo &DCI) const { 9179 SDValue Vec = N->getOperand(0); 9180 SDValue Idx = N->getOperand(2); 9181 EVT VecVT = Vec.getValueType(); 9182 EVT EltVT = VecVT.getVectorElementType(); 9183 unsigned VecSize = VecVT.getSizeInBits(); 9184 unsigned EltSize = EltVT.getSizeInBits(); 9185 9186 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9187 // => BUILD_VECTOR n x select (e, const-idx) 9188 // This elminates non-constant index and subsequent movrel or scratch access. 9189 // Sub-dword vectors of size 2 dword or less have better implementation. 9190 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9191 // instructions. 9192 if (isa<ConstantSDNode>(Idx) || 9193 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9194 return SDValue(); 9195 9196 SelectionDAG &DAG = DCI.DAG; 9197 SDLoc SL(N); 9198 SDValue Ins = N->getOperand(1); 9199 EVT IdxVT = Idx.getValueType(); 9200 9201 SmallVector<SDValue, 16> Ops; 9202 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9203 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9204 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9205 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9206 Ops.push_back(V); 9207 } 9208 9209 return DAG.getBuildVector(VecVT, SL, Ops); 9210 } 9211 9212 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9213 const SDNode *N0, 9214 const SDNode *N1) const { 9215 EVT VT = N0->getValueType(0); 9216 9217 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9218 // support denormals ever. 9219 if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) || 9220 (VT == MVT::f16 && !Subtarget->hasFP16Denormals() && 9221 getSubtarget()->hasMadF16())) && 9222 isOperationLegal(ISD::FMAD, VT)) 9223 return ISD::FMAD; 9224 9225 const TargetOptions &Options = DAG.getTarget().Options; 9226 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9227 (N0->getFlags().hasAllowContract() && 9228 N1->getFlags().hasAllowContract())) && 9229 isFMAFasterThanFMulAndFAdd(VT)) { 9230 return ISD::FMA; 9231 } 9232 9233 return 0; 9234 } 9235 9236 // For a reassociatable opcode perform: 9237 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9238 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9239 SelectionDAG &DAG) const { 9240 EVT VT = N->getValueType(0); 9241 if (VT != MVT::i32 && VT != MVT::i64) 9242 return SDValue(); 9243 9244 unsigned Opc = N->getOpcode(); 9245 SDValue Op0 = N->getOperand(0); 9246 SDValue Op1 = N->getOperand(1); 9247 9248 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9249 return SDValue(); 9250 9251 if (Op0->isDivergent()) 9252 std::swap(Op0, Op1); 9253 9254 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9255 return SDValue(); 9256 9257 SDValue Op2 = Op1.getOperand(1); 9258 Op1 = Op1.getOperand(0); 9259 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9260 return SDValue(); 9261 9262 if (Op1->isDivergent()) 9263 std::swap(Op1, Op2); 9264 9265 // If either operand is constant this will conflict with 9266 // DAGCombiner::ReassociateOps(). 9267 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9268 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9269 return SDValue(); 9270 9271 SDLoc SL(N); 9272 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9273 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9274 } 9275 9276 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9277 EVT VT, 9278 SDValue N0, SDValue N1, SDValue N2, 9279 bool Signed) { 9280 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9281 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9282 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9283 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9284 } 9285 9286 SDValue SITargetLowering::performAddCombine(SDNode *N, 9287 DAGCombinerInfo &DCI) const { 9288 SelectionDAG &DAG = DCI.DAG; 9289 EVT VT = N->getValueType(0); 9290 SDLoc SL(N); 9291 SDValue LHS = N->getOperand(0); 9292 SDValue RHS = N->getOperand(1); 9293 9294 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9295 && Subtarget->hasMad64_32() && 9296 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9297 VT.getScalarSizeInBits() <= 64) { 9298 if (LHS.getOpcode() != ISD::MUL) 9299 std::swap(LHS, RHS); 9300 9301 SDValue MulLHS = LHS.getOperand(0); 9302 SDValue MulRHS = LHS.getOperand(1); 9303 SDValue AddRHS = RHS; 9304 9305 // TODO: Maybe restrict if SGPR inputs. 9306 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9307 numBitsUnsigned(MulRHS, DAG) <= 32) { 9308 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9309 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9310 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9311 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9312 } 9313 9314 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9315 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9316 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9317 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9318 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9319 } 9320 9321 return SDValue(); 9322 } 9323 9324 if (SDValue V = reassociateScalarOps(N, DAG)) { 9325 return V; 9326 } 9327 9328 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9329 return SDValue(); 9330 9331 // add x, zext (setcc) => addcarry x, 0, setcc 9332 // add x, sext (setcc) => subcarry x, 0, setcc 9333 unsigned Opc = LHS.getOpcode(); 9334 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9335 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9336 std::swap(RHS, LHS); 9337 9338 Opc = RHS.getOpcode(); 9339 switch (Opc) { 9340 default: break; 9341 case ISD::ZERO_EXTEND: 9342 case ISD::SIGN_EXTEND: 9343 case ISD::ANY_EXTEND: { 9344 auto Cond = RHS.getOperand(0); 9345 if (!isBoolSGPR(Cond)) 9346 break; 9347 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9348 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9349 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9350 return DAG.getNode(Opc, SL, VTList, Args); 9351 } 9352 case ISD::ADDCARRY: { 9353 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9354 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9355 if (!C || C->getZExtValue() != 0) break; 9356 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9357 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9358 } 9359 } 9360 return SDValue(); 9361 } 9362 9363 SDValue SITargetLowering::performSubCombine(SDNode *N, 9364 DAGCombinerInfo &DCI) const { 9365 SelectionDAG &DAG = DCI.DAG; 9366 EVT VT = N->getValueType(0); 9367 9368 if (VT != MVT::i32) 9369 return SDValue(); 9370 9371 SDLoc SL(N); 9372 SDValue LHS = N->getOperand(0); 9373 SDValue RHS = N->getOperand(1); 9374 9375 if (LHS.getOpcode() == ISD::SUBCARRY) { 9376 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9377 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9378 if (!C || !C->isNullValue()) 9379 return SDValue(); 9380 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9381 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9382 } 9383 return SDValue(); 9384 } 9385 9386 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9387 DAGCombinerInfo &DCI) const { 9388 9389 if (N->getValueType(0) != MVT::i32) 9390 return SDValue(); 9391 9392 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9393 if (!C || C->getZExtValue() != 0) 9394 return SDValue(); 9395 9396 SelectionDAG &DAG = DCI.DAG; 9397 SDValue LHS = N->getOperand(0); 9398 9399 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9400 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9401 unsigned LHSOpc = LHS.getOpcode(); 9402 unsigned Opc = N->getOpcode(); 9403 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9404 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9405 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9406 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9407 } 9408 return SDValue(); 9409 } 9410 9411 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9412 DAGCombinerInfo &DCI) const { 9413 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9414 return SDValue(); 9415 9416 SelectionDAG &DAG = DCI.DAG; 9417 EVT VT = N->getValueType(0); 9418 9419 SDLoc SL(N); 9420 SDValue LHS = N->getOperand(0); 9421 SDValue RHS = N->getOperand(1); 9422 9423 // These should really be instruction patterns, but writing patterns with 9424 // source modiifiers is a pain. 9425 9426 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9427 if (LHS.getOpcode() == ISD::FADD) { 9428 SDValue A = LHS.getOperand(0); 9429 if (A == LHS.getOperand(1)) { 9430 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9431 if (FusedOp != 0) { 9432 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9433 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9434 } 9435 } 9436 } 9437 9438 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9439 if (RHS.getOpcode() == ISD::FADD) { 9440 SDValue A = RHS.getOperand(0); 9441 if (A == RHS.getOperand(1)) { 9442 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9443 if (FusedOp != 0) { 9444 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9445 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9446 } 9447 } 9448 } 9449 9450 return SDValue(); 9451 } 9452 9453 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9454 DAGCombinerInfo &DCI) const { 9455 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9456 return SDValue(); 9457 9458 SelectionDAG &DAG = DCI.DAG; 9459 SDLoc SL(N); 9460 EVT VT = N->getValueType(0); 9461 assert(!VT.isVector()); 9462 9463 // Try to get the fneg to fold into the source modifier. This undoes generic 9464 // DAG combines and folds them into the mad. 9465 // 9466 // Only do this if we are not trying to support denormals. v_mad_f32 does 9467 // not support denormals ever. 9468 SDValue LHS = N->getOperand(0); 9469 SDValue RHS = N->getOperand(1); 9470 if (LHS.getOpcode() == ISD::FADD) { 9471 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9472 SDValue A = LHS.getOperand(0); 9473 if (A == LHS.getOperand(1)) { 9474 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9475 if (FusedOp != 0){ 9476 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9477 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9478 9479 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9480 } 9481 } 9482 } 9483 9484 if (RHS.getOpcode() == ISD::FADD) { 9485 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9486 9487 SDValue A = RHS.getOperand(0); 9488 if (A == RHS.getOperand(1)) { 9489 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9490 if (FusedOp != 0){ 9491 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9492 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9493 } 9494 } 9495 } 9496 9497 return SDValue(); 9498 } 9499 9500 SDValue SITargetLowering::performFMACombine(SDNode *N, 9501 DAGCombinerInfo &DCI) const { 9502 SelectionDAG &DAG = DCI.DAG; 9503 EVT VT = N->getValueType(0); 9504 SDLoc SL(N); 9505 9506 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9507 return SDValue(); 9508 9509 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9510 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9511 SDValue Op1 = N->getOperand(0); 9512 SDValue Op2 = N->getOperand(1); 9513 SDValue FMA = N->getOperand(2); 9514 9515 if (FMA.getOpcode() != ISD::FMA || 9516 Op1.getOpcode() != ISD::FP_EXTEND || 9517 Op2.getOpcode() != ISD::FP_EXTEND) 9518 return SDValue(); 9519 9520 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9521 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9522 // is sufficient to allow generaing fdot2. 9523 const TargetOptions &Options = DAG.getTarget().Options; 9524 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9525 (N->getFlags().hasAllowContract() && 9526 FMA->getFlags().hasAllowContract())) { 9527 Op1 = Op1.getOperand(0); 9528 Op2 = Op2.getOperand(0); 9529 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9530 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9531 return SDValue(); 9532 9533 SDValue Vec1 = Op1.getOperand(0); 9534 SDValue Idx1 = Op1.getOperand(1); 9535 SDValue Vec2 = Op2.getOperand(0); 9536 9537 SDValue FMAOp1 = FMA.getOperand(0); 9538 SDValue FMAOp2 = FMA.getOperand(1); 9539 SDValue FMAAcc = FMA.getOperand(2); 9540 9541 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9542 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9543 return SDValue(); 9544 9545 FMAOp1 = FMAOp1.getOperand(0); 9546 FMAOp2 = FMAOp2.getOperand(0); 9547 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9548 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9549 return SDValue(); 9550 9551 SDValue Vec3 = FMAOp1.getOperand(0); 9552 SDValue Vec4 = FMAOp2.getOperand(0); 9553 SDValue Idx2 = FMAOp1.getOperand(1); 9554 9555 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9556 // Idx1 and Idx2 cannot be the same. 9557 Idx1 == Idx2) 9558 return SDValue(); 9559 9560 if (Vec1 == Vec2 || Vec3 == Vec4) 9561 return SDValue(); 9562 9563 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9564 return SDValue(); 9565 9566 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9567 (Vec1 == Vec4 && Vec2 == Vec3)) { 9568 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9569 DAG.getTargetConstant(0, SL, MVT::i1)); 9570 } 9571 } 9572 return SDValue(); 9573 } 9574 9575 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9576 DAGCombinerInfo &DCI) const { 9577 SelectionDAG &DAG = DCI.DAG; 9578 SDLoc SL(N); 9579 9580 SDValue LHS = N->getOperand(0); 9581 SDValue RHS = N->getOperand(1); 9582 EVT VT = LHS.getValueType(); 9583 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9584 9585 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9586 if (!CRHS) { 9587 CRHS = dyn_cast<ConstantSDNode>(LHS); 9588 if (CRHS) { 9589 std::swap(LHS, RHS); 9590 CC = getSetCCSwappedOperands(CC); 9591 } 9592 } 9593 9594 if (CRHS) { 9595 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9596 isBoolSGPR(LHS.getOperand(0))) { 9597 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9598 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9599 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9600 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9601 if ((CRHS->isAllOnesValue() && 9602 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9603 (CRHS->isNullValue() && 9604 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9605 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9606 DAG.getConstant(-1, SL, MVT::i1)); 9607 if ((CRHS->isAllOnesValue() && 9608 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9609 (CRHS->isNullValue() && 9610 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9611 return LHS.getOperand(0); 9612 } 9613 9614 uint64_t CRHSVal = CRHS->getZExtValue(); 9615 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9616 LHS.getOpcode() == ISD::SELECT && 9617 isa<ConstantSDNode>(LHS.getOperand(1)) && 9618 isa<ConstantSDNode>(LHS.getOperand(2)) && 9619 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9620 isBoolSGPR(LHS.getOperand(0))) { 9621 // Given CT != FT: 9622 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9623 // setcc (select cc, CT, CF), CF, ne => cc 9624 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9625 // setcc (select cc, CT, CF), CT, eq => cc 9626 uint64_t CT = LHS.getConstantOperandVal(1); 9627 uint64_t CF = LHS.getConstantOperandVal(2); 9628 9629 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9630 (CT == CRHSVal && CC == ISD::SETNE)) 9631 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9632 DAG.getConstant(-1, SL, MVT::i1)); 9633 if ((CF == CRHSVal && CC == ISD::SETNE) || 9634 (CT == CRHSVal && CC == ISD::SETEQ)) 9635 return LHS.getOperand(0); 9636 } 9637 } 9638 9639 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9640 VT != MVT::f16)) 9641 return SDValue(); 9642 9643 // Match isinf/isfinite pattern 9644 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9645 // (fcmp one (fabs x), inf) -> (fp_class x, 9646 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9647 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9648 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9649 if (!CRHS) 9650 return SDValue(); 9651 9652 const APFloat &APF = CRHS->getValueAPF(); 9653 if (APF.isInfinity() && !APF.isNegative()) { 9654 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9655 SIInstrFlags::N_INFINITY; 9656 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9657 SIInstrFlags::P_ZERO | 9658 SIInstrFlags::N_NORMAL | 9659 SIInstrFlags::P_NORMAL | 9660 SIInstrFlags::N_SUBNORMAL | 9661 SIInstrFlags::P_SUBNORMAL; 9662 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9663 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9664 DAG.getConstant(Mask, SL, MVT::i32)); 9665 } 9666 } 9667 9668 return SDValue(); 9669 } 9670 9671 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9672 DAGCombinerInfo &DCI) const { 9673 SelectionDAG &DAG = DCI.DAG; 9674 SDLoc SL(N); 9675 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9676 9677 SDValue Src = N->getOperand(0); 9678 SDValue Srl = N->getOperand(0); 9679 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9680 Srl = Srl.getOperand(0); 9681 9682 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9683 if (Srl.getOpcode() == ISD::SRL) { 9684 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9685 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9686 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9687 9688 if (const ConstantSDNode *C = 9689 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9690 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9691 EVT(MVT::i32)); 9692 9693 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9694 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9695 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9696 MVT::f32, Srl); 9697 } 9698 } 9699 } 9700 9701 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9702 9703 KnownBits Known; 9704 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9705 !DCI.isBeforeLegalizeOps()); 9706 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9707 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9708 DCI.CommitTargetLoweringOpt(TLO); 9709 } 9710 9711 return SDValue(); 9712 } 9713 9714 SDValue SITargetLowering::performClampCombine(SDNode *N, 9715 DAGCombinerInfo &DCI) const { 9716 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9717 if (!CSrc) 9718 return SDValue(); 9719 9720 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9721 const APFloat &F = CSrc->getValueAPF(); 9722 APFloat Zero = APFloat::getZero(F.getSemantics()); 9723 APFloat::cmpResult Cmp0 = F.compare(Zero); 9724 if (Cmp0 == APFloat::cmpLessThan || 9725 (Cmp0 == APFloat::cmpUnordered && 9726 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9727 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9728 } 9729 9730 APFloat One(F.getSemantics(), "1.0"); 9731 APFloat::cmpResult Cmp1 = F.compare(One); 9732 if (Cmp1 == APFloat::cmpGreaterThan) 9733 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9734 9735 return SDValue(CSrc, 0); 9736 } 9737 9738 9739 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9740 DAGCombinerInfo &DCI) const { 9741 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9742 return SDValue(); 9743 switch (N->getOpcode()) { 9744 default: 9745 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9746 case ISD::ADD: 9747 return performAddCombine(N, DCI); 9748 case ISD::SUB: 9749 return performSubCombine(N, DCI); 9750 case ISD::ADDCARRY: 9751 case ISD::SUBCARRY: 9752 return performAddCarrySubCarryCombine(N, DCI); 9753 case ISD::FADD: 9754 return performFAddCombine(N, DCI); 9755 case ISD::FSUB: 9756 return performFSubCombine(N, DCI); 9757 case ISD::SETCC: 9758 return performSetCCCombine(N, DCI); 9759 case ISD::FMAXNUM: 9760 case ISD::FMINNUM: 9761 case ISD::FMAXNUM_IEEE: 9762 case ISD::FMINNUM_IEEE: 9763 case ISD::SMAX: 9764 case ISD::SMIN: 9765 case ISD::UMAX: 9766 case ISD::UMIN: 9767 case AMDGPUISD::FMIN_LEGACY: 9768 case AMDGPUISD::FMAX_LEGACY: 9769 return performMinMaxCombine(N, DCI); 9770 case ISD::FMA: 9771 return performFMACombine(N, DCI); 9772 case ISD::LOAD: { 9773 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9774 return Widended; 9775 LLVM_FALLTHROUGH; 9776 } 9777 case ISD::STORE: 9778 case ISD::ATOMIC_LOAD: 9779 case ISD::ATOMIC_STORE: 9780 case ISD::ATOMIC_CMP_SWAP: 9781 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9782 case ISD::ATOMIC_SWAP: 9783 case ISD::ATOMIC_LOAD_ADD: 9784 case ISD::ATOMIC_LOAD_SUB: 9785 case ISD::ATOMIC_LOAD_AND: 9786 case ISD::ATOMIC_LOAD_OR: 9787 case ISD::ATOMIC_LOAD_XOR: 9788 case ISD::ATOMIC_LOAD_NAND: 9789 case ISD::ATOMIC_LOAD_MIN: 9790 case ISD::ATOMIC_LOAD_MAX: 9791 case ISD::ATOMIC_LOAD_UMIN: 9792 case ISD::ATOMIC_LOAD_UMAX: 9793 case ISD::ATOMIC_LOAD_FADD: 9794 case AMDGPUISD::ATOMIC_INC: 9795 case AMDGPUISD::ATOMIC_DEC: 9796 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9797 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9798 if (DCI.isBeforeLegalize()) 9799 break; 9800 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9801 case ISD::AND: 9802 return performAndCombine(N, DCI); 9803 case ISD::OR: 9804 return performOrCombine(N, DCI); 9805 case ISD::XOR: 9806 return performXorCombine(N, DCI); 9807 case ISD::ZERO_EXTEND: 9808 return performZeroExtendCombine(N, DCI); 9809 case ISD::SIGN_EXTEND_INREG: 9810 return performSignExtendInRegCombine(N , DCI); 9811 case AMDGPUISD::FP_CLASS: 9812 return performClassCombine(N, DCI); 9813 case ISD::FCANONICALIZE: 9814 return performFCanonicalizeCombine(N, DCI); 9815 case AMDGPUISD::RCP: 9816 return performRcpCombine(N, DCI); 9817 case AMDGPUISD::FRACT: 9818 case AMDGPUISD::RSQ: 9819 case AMDGPUISD::RCP_LEGACY: 9820 case AMDGPUISD::RSQ_LEGACY: 9821 case AMDGPUISD::RCP_IFLAG: 9822 case AMDGPUISD::RSQ_CLAMP: 9823 case AMDGPUISD::LDEXP: { 9824 SDValue Src = N->getOperand(0); 9825 if (Src.isUndef()) 9826 return Src; 9827 break; 9828 } 9829 case ISD::SINT_TO_FP: 9830 case ISD::UINT_TO_FP: 9831 return performUCharToFloatCombine(N, DCI); 9832 case AMDGPUISD::CVT_F32_UBYTE0: 9833 case AMDGPUISD::CVT_F32_UBYTE1: 9834 case AMDGPUISD::CVT_F32_UBYTE2: 9835 case AMDGPUISD::CVT_F32_UBYTE3: 9836 return performCvtF32UByteNCombine(N, DCI); 9837 case AMDGPUISD::FMED3: 9838 return performFMed3Combine(N, DCI); 9839 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9840 return performCvtPkRTZCombine(N, DCI); 9841 case AMDGPUISD::CLAMP: 9842 return performClampCombine(N, DCI); 9843 case ISD::SCALAR_TO_VECTOR: { 9844 SelectionDAG &DAG = DCI.DAG; 9845 EVT VT = N->getValueType(0); 9846 9847 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9848 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9849 SDLoc SL(N); 9850 SDValue Src = N->getOperand(0); 9851 EVT EltVT = Src.getValueType(); 9852 if (EltVT == MVT::f16) 9853 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 9854 9855 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 9856 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 9857 } 9858 9859 break; 9860 } 9861 case ISD::EXTRACT_VECTOR_ELT: 9862 return performExtractVectorEltCombine(N, DCI); 9863 case ISD::INSERT_VECTOR_ELT: 9864 return performInsertVectorEltCombine(N, DCI); 9865 } 9866 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9867 } 9868 9869 /// Helper function for adjustWritemask 9870 static unsigned SubIdx2Lane(unsigned Idx) { 9871 switch (Idx) { 9872 default: return 0; 9873 case AMDGPU::sub0: return 0; 9874 case AMDGPU::sub1: return 1; 9875 case AMDGPU::sub2: return 2; 9876 case AMDGPU::sub3: return 3; 9877 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 9878 } 9879 } 9880 9881 /// Adjust the writemask of MIMG instructions 9882 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 9883 SelectionDAG &DAG) const { 9884 unsigned Opcode = Node->getMachineOpcode(); 9885 9886 // Subtract 1 because the vdata output is not a MachineSDNode operand. 9887 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 9888 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 9889 return Node; // not implemented for D16 9890 9891 SDNode *Users[5] = { nullptr }; 9892 unsigned Lane = 0; 9893 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 9894 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 9895 unsigned NewDmask = 0; 9896 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 9897 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 9898 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 9899 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 9900 unsigned TFCLane = 0; 9901 bool HasChain = Node->getNumValues() > 1; 9902 9903 if (OldDmask == 0) { 9904 // These are folded out, but on the chance it happens don't assert. 9905 return Node; 9906 } 9907 9908 unsigned OldBitsSet = countPopulation(OldDmask); 9909 // Work out which is the TFE/LWE lane if that is enabled. 9910 if (UsesTFC) { 9911 TFCLane = OldBitsSet; 9912 } 9913 9914 // Try to figure out the used register components 9915 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 9916 I != E; ++I) { 9917 9918 // Don't look at users of the chain. 9919 if (I.getUse().getResNo() != 0) 9920 continue; 9921 9922 // Abort if we can't understand the usage 9923 if (!I->isMachineOpcode() || 9924 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 9925 return Node; 9926 9927 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 9928 // Note that subregs are packed, i.e. Lane==0 is the first bit set 9929 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 9930 // set, etc. 9931 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 9932 9933 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 9934 if (UsesTFC && Lane == TFCLane) { 9935 Users[Lane] = *I; 9936 } else { 9937 // Set which texture component corresponds to the lane. 9938 unsigned Comp; 9939 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 9940 Comp = countTrailingZeros(Dmask); 9941 Dmask &= ~(1 << Comp); 9942 } 9943 9944 // Abort if we have more than one user per component. 9945 if (Users[Lane]) 9946 return Node; 9947 9948 Users[Lane] = *I; 9949 NewDmask |= 1 << Comp; 9950 } 9951 } 9952 9953 // Don't allow 0 dmask, as hardware assumes one channel enabled. 9954 bool NoChannels = !NewDmask; 9955 if (NoChannels) { 9956 if (!UsesTFC) { 9957 // No uses of the result and not using TFC. Then do nothing. 9958 return Node; 9959 } 9960 // If the original dmask has one channel - then nothing to do 9961 if (OldBitsSet == 1) 9962 return Node; 9963 // Use an arbitrary dmask - required for the instruction to work 9964 NewDmask = 1; 9965 } 9966 // Abort if there's no change 9967 if (NewDmask == OldDmask) 9968 return Node; 9969 9970 unsigned BitsSet = countPopulation(NewDmask); 9971 9972 // Check for TFE or LWE - increase the number of channels by one to account 9973 // for the extra return value 9974 // This will need adjustment for D16 if this is also included in 9975 // adjustWriteMask (this function) but at present D16 are excluded. 9976 unsigned NewChannels = BitsSet + UsesTFC; 9977 9978 int NewOpcode = 9979 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 9980 assert(NewOpcode != -1 && 9981 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 9982 "failed to find equivalent MIMG op"); 9983 9984 // Adjust the writemask in the node 9985 SmallVector<SDValue, 12> Ops; 9986 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 9987 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 9988 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 9989 9990 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 9991 9992 MVT ResultVT = NewChannels == 1 ? 9993 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 9994 NewChannels == 5 ? 8 : NewChannels); 9995 SDVTList NewVTList = HasChain ? 9996 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 9997 9998 9999 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10000 NewVTList, Ops); 10001 10002 if (HasChain) { 10003 // Update chain. 10004 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10005 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10006 } 10007 10008 if (NewChannels == 1) { 10009 assert(Node->hasNUsesOfValue(1, 0)); 10010 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10011 SDLoc(Node), Users[Lane]->getValueType(0), 10012 SDValue(NewNode, 0)); 10013 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10014 return nullptr; 10015 } 10016 10017 // Update the users of the node with the new indices 10018 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10019 SDNode *User = Users[i]; 10020 if (!User) { 10021 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10022 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10023 if (i || !NoChannels) 10024 continue; 10025 } else { 10026 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10027 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10028 } 10029 10030 switch (Idx) { 10031 default: break; 10032 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10033 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10034 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10035 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10036 } 10037 } 10038 10039 DAG.RemoveDeadNode(Node); 10040 return nullptr; 10041 } 10042 10043 static bool isFrameIndexOp(SDValue Op) { 10044 if (Op.getOpcode() == ISD::AssertZext) 10045 Op = Op.getOperand(0); 10046 10047 return isa<FrameIndexSDNode>(Op); 10048 } 10049 10050 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10051 /// with frame index operands. 10052 /// LLVM assumes that inputs are to these instructions are registers. 10053 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10054 SelectionDAG &DAG) const { 10055 if (Node->getOpcode() == ISD::CopyToReg) { 10056 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10057 SDValue SrcVal = Node->getOperand(2); 10058 10059 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10060 // to try understanding copies to physical registers. 10061 if (SrcVal.getValueType() == MVT::i1 && 10062 TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) { 10063 SDLoc SL(Node); 10064 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10065 SDValue VReg = DAG.getRegister( 10066 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10067 10068 SDNode *Glued = Node->getGluedNode(); 10069 SDValue ToVReg 10070 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10071 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10072 SDValue ToResultReg 10073 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10074 VReg, ToVReg.getValue(1)); 10075 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10076 DAG.RemoveDeadNode(Node); 10077 return ToResultReg.getNode(); 10078 } 10079 } 10080 10081 SmallVector<SDValue, 8> Ops; 10082 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10083 if (!isFrameIndexOp(Node->getOperand(i))) { 10084 Ops.push_back(Node->getOperand(i)); 10085 continue; 10086 } 10087 10088 SDLoc DL(Node); 10089 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10090 Node->getOperand(i).getValueType(), 10091 Node->getOperand(i)), 0)); 10092 } 10093 10094 return DAG.UpdateNodeOperands(Node, Ops); 10095 } 10096 10097 /// Fold the instructions after selecting them. 10098 /// Returns null if users were already updated. 10099 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10100 SelectionDAG &DAG) const { 10101 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10102 unsigned Opcode = Node->getMachineOpcode(); 10103 10104 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10105 !TII->isGather4(Opcode)) { 10106 return adjustWritemask(Node, DAG); 10107 } 10108 10109 if (Opcode == AMDGPU::INSERT_SUBREG || 10110 Opcode == AMDGPU::REG_SEQUENCE) { 10111 legalizeTargetIndependentNode(Node, DAG); 10112 return Node; 10113 } 10114 10115 switch (Opcode) { 10116 case AMDGPU::V_DIV_SCALE_F32: 10117 case AMDGPU::V_DIV_SCALE_F64: { 10118 // Satisfy the operand register constraint when one of the inputs is 10119 // undefined. Ordinarily each undef value will have its own implicit_def of 10120 // a vreg, so force these to use a single register. 10121 SDValue Src0 = Node->getOperand(0); 10122 SDValue Src1 = Node->getOperand(1); 10123 SDValue Src2 = Node->getOperand(2); 10124 10125 if ((Src0.isMachineOpcode() && 10126 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10127 (Src0 == Src1 || Src0 == Src2)) 10128 break; 10129 10130 MVT VT = Src0.getValueType().getSimpleVT(); 10131 const TargetRegisterClass *RC = 10132 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10133 10134 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10135 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10136 10137 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10138 UndefReg, Src0, SDValue()); 10139 10140 // src0 must be the same register as src1 or src2, even if the value is 10141 // undefined, so make sure we don't violate this constraint. 10142 if (Src0.isMachineOpcode() && 10143 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10144 if (Src1.isMachineOpcode() && 10145 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10146 Src0 = Src1; 10147 else if (Src2.isMachineOpcode() && 10148 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10149 Src0 = Src2; 10150 else { 10151 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10152 Src0 = UndefReg; 10153 Src1 = UndefReg; 10154 } 10155 } else 10156 break; 10157 10158 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10159 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10160 Ops.push_back(Node->getOperand(I)); 10161 10162 Ops.push_back(ImpDef.getValue(1)); 10163 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10164 } 10165 case AMDGPU::V_PERMLANE16_B32: 10166 case AMDGPU::V_PERMLANEX16_B32: { 10167 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10168 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10169 if (!FI->getZExtValue() && !BC->getZExtValue()) 10170 break; 10171 SDValue VDstIn = Node->getOperand(6); 10172 if (VDstIn.isMachineOpcode() 10173 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10174 break; 10175 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10176 SDLoc(Node), MVT::i32); 10177 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10178 SDValue(BC, 0), Node->getOperand(3), 10179 Node->getOperand(4), Node->getOperand(5), 10180 SDValue(ImpDef, 0), Node->getOperand(7) }; 10181 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10182 } 10183 default: 10184 break; 10185 } 10186 10187 return Node; 10188 } 10189 10190 /// Assign the register class depending on the number of 10191 /// bits set in the writemask 10192 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10193 SDNode *Node) const { 10194 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10195 10196 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10197 10198 if (TII->isVOP3(MI.getOpcode())) { 10199 // Make sure constant bus requirements are respected. 10200 TII->legalizeOperandsVOP3(MRI, MI); 10201 10202 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10203 // This saves a chain-copy of registers and better ballance register 10204 // use between vgpr and agpr as agpr tuples tend to be big. 10205 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10206 unsigned Opc = MI.getOpcode(); 10207 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10208 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10209 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10210 if (I == -1) 10211 break; 10212 MachineOperand &Op = MI.getOperand(I); 10213 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10214 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10215 !TargetRegisterInfo::isVirtualRegister(Op.getReg()) || 10216 !TRI->isAGPR(MRI, Op.getReg())) 10217 continue; 10218 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10219 if (!Src || !Src->isCopy() || 10220 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10221 continue; 10222 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10223 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10224 // All uses of agpr64 and agpr32 can also accept vgpr except for 10225 // v_accvgpr_read, but we do not produce agpr reads during selection, 10226 // so no use checks are needed. 10227 MRI.setRegClass(Op.getReg(), NewRC); 10228 } 10229 } 10230 10231 return; 10232 } 10233 10234 // Replace unused atomics with the no return version. 10235 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10236 if (NoRetAtomicOp != -1) { 10237 if (!Node->hasAnyUseOfValue(0)) { 10238 MI.setDesc(TII->get(NoRetAtomicOp)); 10239 MI.RemoveOperand(0); 10240 return; 10241 } 10242 10243 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10244 // instruction, because the return type of these instructions is a vec2 of 10245 // the memory type, so it can be tied to the input operand. 10246 // This means these instructions always have a use, so we need to add a 10247 // special case to check if the atomic has only one extract_subreg use, 10248 // which itself has no uses. 10249 if ((Node->hasNUsesOfValue(1, 0) && 10250 Node->use_begin()->isMachineOpcode() && 10251 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10252 !Node->use_begin()->hasAnyUseOfValue(0))) { 10253 unsigned Def = MI.getOperand(0).getReg(); 10254 10255 // Change this into a noret atomic. 10256 MI.setDesc(TII->get(NoRetAtomicOp)); 10257 MI.RemoveOperand(0); 10258 10259 // If we only remove the def operand from the atomic instruction, the 10260 // extract_subreg will be left with a use of a vreg without a def. 10261 // So we need to insert an implicit_def to avoid machine verifier 10262 // errors. 10263 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10264 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10265 } 10266 return; 10267 } 10268 } 10269 10270 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10271 uint64_t Val) { 10272 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10273 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10274 } 10275 10276 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10277 const SDLoc &DL, 10278 SDValue Ptr) const { 10279 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10280 10281 // Build the half of the subregister with the constants before building the 10282 // full 128-bit register. If we are building multiple resource descriptors, 10283 // this will allow CSEing of the 2-component register. 10284 const SDValue Ops0[] = { 10285 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10286 buildSMovImm32(DAG, DL, 0), 10287 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10288 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10289 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10290 }; 10291 10292 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10293 MVT::v2i32, Ops0), 0); 10294 10295 // Combine the constants and the pointer. 10296 const SDValue Ops1[] = { 10297 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10298 Ptr, 10299 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10300 SubRegHi, 10301 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10302 }; 10303 10304 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10305 } 10306 10307 /// Return a resource descriptor with the 'Add TID' bit enabled 10308 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10309 /// of the resource descriptor) to create an offset, which is added to 10310 /// the resource pointer. 10311 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10312 SDValue Ptr, uint32_t RsrcDword1, 10313 uint64_t RsrcDword2And3) const { 10314 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10315 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10316 if (RsrcDword1) { 10317 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10318 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10319 0); 10320 } 10321 10322 SDValue DataLo = buildSMovImm32(DAG, DL, 10323 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10324 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10325 10326 const SDValue Ops[] = { 10327 DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32), 10328 PtrLo, 10329 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10330 PtrHi, 10331 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10332 DataLo, 10333 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10334 DataHi, 10335 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10336 }; 10337 10338 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10339 } 10340 10341 //===----------------------------------------------------------------------===// 10342 // SI Inline Assembly Support 10343 //===----------------------------------------------------------------------===// 10344 10345 std::pair<unsigned, const TargetRegisterClass *> 10346 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10347 StringRef Constraint, 10348 MVT VT) const { 10349 const TargetRegisterClass *RC = nullptr; 10350 if (Constraint.size() == 1) { 10351 switch (Constraint[0]) { 10352 default: 10353 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10354 case 's': 10355 case 'r': 10356 switch (VT.getSizeInBits()) { 10357 default: 10358 return std::make_pair(0U, nullptr); 10359 case 32: 10360 case 16: 10361 RC = &AMDGPU::SReg_32_XM0RegClass; 10362 break; 10363 case 64: 10364 RC = &AMDGPU::SGPR_64RegClass; 10365 break; 10366 case 96: 10367 RC = &AMDGPU::SReg_96RegClass; 10368 break; 10369 case 128: 10370 RC = &AMDGPU::SReg_128RegClass; 10371 break; 10372 case 160: 10373 RC = &AMDGPU::SReg_160RegClass; 10374 break; 10375 case 256: 10376 RC = &AMDGPU::SReg_256RegClass; 10377 break; 10378 case 512: 10379 RC = &AMDGPU::SReg_512RegClass; 10380 break; 10381 } 10382 break; 10383 case 'v': 10384 switch (VT.getSizeInBits()) { 10385 default: 10386 return std::make_pair(0U, nullptr); 10387 case 32: 10388 case 16: 10389 RC = &AMDGPU::VGPR_32RegClass; 10390 break; 10391 case 64: 10392 RC = &AMDGPU::VReg_64RegClass; 10393 break; 10394 case 96: 10395 RC = &AMDGPU::VReg_96RegClass; 10396 break; 10397 case 128: 10398 RC = &AMDGPU::VReg_128RegClass; 10399 break; 10400 case 160: 10401 RC = &AMDGPU::VReg_160RegClass; 10402 break; 10403 case 256: 10404 RC = &AMDGPU::VReg_256RegClass; 10405 break; 10406 case 512: 10407 RC = &AMDGPU::VReg_512RegClass; 10408 break; 10409 } 10410 break; 10411 case 'a': 10412 switch (VT.getSizeInBits()) { 10413 default: 10414 return std::make_pair(0U, nullptr); 10415 case 32: 10416 case 16: 10417 RC = &AMDGPU::AGPR_32RegClass; 10418 break; 10419 case 64: 10420 RC = &AMDGPU::AReg_64RegClass; 10421 break; 10422 case 128: 10423 RC = &AMDGPU::AReg_128RegClass; 10424 break; 10425 case 512: 10426 RC = &AMDGPU::AReg_512RegClass; 10427 break; 10428 case 1024: 10429 RC = &AMDGPU::AReg_1024RegClass; 10430 // v32 types are not legal but we support them here. 10431 return std::make_pair(0U, RC); 10432 } 10433 break; 10434 } 10435 // We actually support i128, i16 and f16 as inline parameters 10436 // even if they are not reported as legal 10437 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10438 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10439 return std::make_pair(0U, RC); 10440 } 10441 10442 if (Constraint.size() > 1) { 10443 if (Constraint[1] == 'v') { 10444 RC = &AMDGPU::VGPR_32RegClass; 10445 } else if (Constraint[1] == 's') { 10446 RC = &AMDGPU::SGPR_32RegClass; 10447 } else if (Constraint[1] == 'a') { 10448 RC = &AMDGPU::AGPR_32RegClass; 10449 } 10450 10451 if (RC) { 10452 uint32_t Idx; 10453 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10454 if (!Failed && Idx < RC->getNumRegs()) 10455 return std::make_pair(RC->getRegister(Idx), RC); 10456 } 10457 } 10458 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10459 } 10460 10461 SITargetLowering::ConstraintType 10462 SITargetLowering::getConstraintType(StringRef Constraint) const { 10463 if (Constraint.size() == 1) { 10464 switch (Constraint[0]) { 10465 default: break; 10466 case 's': 10467 case 'v': 10468 case 'a': 10469 return C_RegisterClass; 10470 } 10471 } 10472 return TargetLowering::getConstraintType(Constraint); 10473 } 10474 10475 // Figure out which registers should be reserved for stack access. Only after 10476 // the function is legalized do we know all of the non-spill stack objects or if 10477 // calls are present. 10478 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10479 MachineRegisterInfo &MRI = MF.getRegInfo(); 10480 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10481 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10482 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10483 10484 if (Info->isEntryFunction()) { 10485 // Callable functions have fixed registers used for stack access. 10486 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10487 } 10488 10489 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10490 Info->getStackPtrOffsetReg())); 10491 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10492 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10493 10494 // We need to worry about replacing the default register with itself in case 10495 // of MIR testcases missing the MFI. 10496 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10497 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10498 10499 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10500 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10501 10502 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10503 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10504 Info->getScratchWaveOffsetReg()); 10505 } 10506 10507 Info->limitOccupancy(MF); 10508 10509 if (ST.isWave32() && !MF.empty()) { 10510 // Add VCC_HI def because many instructions marked as imp-use VCC where 10511 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10512 // having a use of undef. 10513 10514 const SIInstrInfo *TII = ST.getInstrInfo(); 10515 DebugLoc DL; 10516 10517 MachineBasicBlock &MBB = MF.front(); 10518 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10519 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10520 10521 for (auto &MBB : MF) { 10522 for (auto &MI : MBB) { 10523 TII->fixImplicitOperands(MI); 10524 } 10525 } 10526 } 10527 10528 TargetLoweringBase::finalizeLowering(MF); 10529 } 10530 10531 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10532 KnownBits &Known, 10533 const APInt &DemandedElts, 10534 const SelectionDAG &DAG, 10535 unsigned Depth) const { 10536 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10537 DAG, Depth); 10538 10539 // Set the high bits to zero based on the maximum allowed scratch size per 10540 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10541 // calculation won't overflow, so assume the sign bit is never set. 10542 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10543 } 10544 10545 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10546 const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10547 const unsigned CacheLineAlign = 6; // log2(64) 10548 10549 // Pre-GFX10 target did not benefit from loop alignment 10550 if (!ML || DisableLoopAlignment || 10551 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10552 getSubtarget()->hasInstFwdPrefetchBug()) 10553 return PrefAlign; 10554 10555 // On GFX10 I$ is 4 x 64 bytes cache lines. 10556 // By default prefetcher keeps one cache line behind and reads two ahead. 10557 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10558 // behind and one ahead. 10559 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10560 // If loop fits 64 bytes it always spans no more than two cache lines and 10561 // does not need an alignment. 10562 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10563 // Else if loop is less or equal 192 bytes we need two lines behind. 10564 10565 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10566 const MachineBasicBlock *Header = ML->getHeader(); 10567 if (Header->getAlignment() != PrefAlign) 10568 return Header->getAlignment(); // Already processed. 10569 10570 unsigned LoopSize = 0; 10571 for (const MachineBasicBlock *MBB : ML->blocks()) { 10572 // If inner loop block is aligned assume in average half of the alignment 10573 // size to be added as nops. 10574 if (MBB != Header) 10575 LoopSize += (1 << MBB->getAlignment()) / 2; 10576 10577 for (const MachineInstr &MI : *MBB) { 10578 LoopSize += TII->getInstSizeInBytes(MI); 10579 if (LoopSize > 192) 10580 return PrefAlign; 10581 } 10582 } 10583 10584 if (LoopSize <= 64) 10585 return PrefAlign; 10586 10587 if (LoopSize <= 128) 10588 return CacheLineAlign; 10589 10590 // If any of parent loops is surrounded by prefetch instructions do not 10591 // insert new for inner loop, which would reset parent's settings. 10592 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10593 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10594 auto I = Exit->getFirstNonDebugInstr(); 10595 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10596 return CacheLineAlign; 10597 } 10598 } 10599 10600 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10601 MachineBasicBlock *Exit = ML->getExitBlock(); 10602 10603 if (Pre && Exit) { 10604 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10605 TII->get(AMDGPU::S_INST_PREFETCH)) 10606 .addImm(1); // prefetch 2 lines behind PC 10607 10608 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10609 TII->get(AMDGPU::S_INST_PREFETCH)) 10610 .addImm(2); // prefetch 1 line behind PC 10611 } 10612 10613 return CacheLineAlign; 10614 } 10615 10616 LLVM_ATTRIBUTE_UNUSED 10617 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10618 assert(N->getOpcode() == ISD::CopyFromReg); 10619 do { 10620 // Follow the chain until we find an INLINEASM node. 10621 N = N->getOperand(0).getNode(); 10622 if (N->getOpcode() == ISD::INLINEASM || 10623 N->getOpcode() == ISD::INLINEASM_BR) 10624 return true; 10625 } while (N->getOpcode() == ISD::CopyFromReg); 10626 return false; 10627 } 10628 10629 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10630 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10631 { 10632 switch (N->getOpcode()) { 10633 case ISD::CopyFromReg: 10634 { 10635 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10636 const MachineFunction * MF = FLI->MF; 10637 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10638 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10639 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10640 unsigned Reg = R->getReg(); 10641 if (TRI.isPhysicalRegister(Reg)) 10642 return !TRI.isSGPRReg(MRI, Reg); 10643 10644 if (MRI.isLiveIn(Reg)) { 10645 // workitem.id.x workitem.id.y workitem.id.z 10646 // Any VGPR formal argument is also considered divergent 10647 if (!TRI.isSGPRReg(MRI, Reg)) 10648 return true; 10649 // Formal arguments of non-entry functions 10650 // are conservatively considered divergent 10651 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10652 return true; 10653 return false; 10654 } 10655 const Value *V = FLI->getValueFromVirtualReg(Reg); 10656 if (V) 10657 return KDA->isDivergent(V); 10658 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10659 return !TRI.isSGPRReg(MRI, Reg); 10660 } 10661 break; 10662 case ISD::LOAD: { 10663 const LoadSDNode *L = cast<LoadSDNode>(N); 10664 unsigned AS = L->getAddressSpace(); 10665 // A flat load may access private memory. 10666 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10667 } break; 10668 case ISD::CALLSEQ_END: 10669 return true; 10670 break; 10671 case ISD::INTRINSIC_WO_CHAIN: 10672 { 10673 10674 } 10675 return AMDGPU::isIntrinsicSourceOfDivergence( 10676 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10677 case ISD::INTRINSIC_W_CHAIN: 10678 return AMDGPU::isIntrinsicSourceOfDivergence( 10679 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10680 // In some cases intrinsics that are a source of divergence have been 10681 // lowered to AMDGPUISD so we also need to check those too. 10682 case AMDGPUISD::INTERP_MOV: 10683 case AMDGPUISD::INTERP_P1: 10684 case AMDGPUISD::INTERP_P2: 10685 return true; 10686 } 10687 return false; 10688 } 10689 10690 bool SITargetLowering::denormalsEnabledForType(EVT VT) const { 10691 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10692 case MVT::f32: 10693 return Subtarget->hasFP32Denormals(); 10694 case MVT::f64: 10695 return Subtarget->hasFP64Denormals(); 10696 case MVT::f16: 10697 return Subtarget->hasFP16Denormals(); 10698 default: 10699 return false; 10700 } 10701 } 10702 10703 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10704 const SelectionDAG &DAG, 10705 bool SNaN, 10706 unsigned Depth) const { 10707 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10708 const MachineFunction &MF = DAG.getMachineFunction(); 10709 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10710 10711 if (Info->getMode().DX10Clamp) 10712 return true; // Clamped to 0. 10713 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10714 } 10715 10716 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10717 SNaN, Depth); 10718 } 10719 10720 TargetLowering::AtomicExpansionKind 10721 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10722 switch (RMW->getOperation()) { 10723 case AtomicRMWInst::FAdd: { 10724 Type *Ty = RMW->getType(); 10725 10726 // We don't have a way to support 16-bit atomics now, so just leave them 10727 // as-is. 10728 if (Ty->isHalfTy()) 10729 return AtomicExpansionKind::None; 10730 10731 if (!Ty->isFloatTy()) 10732 return AtomicExpansionKind::CmpXChg; 10733 10734 // TODO: Do have these for flat. Older targets also had them for buffers. 10735 unsigned AS = RMW->getPointerAddressSpace(); 10736 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10737 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10738 } 10739 default: 10740 break; 10741 } 10742 10743 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10744 } 10745