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 "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "SIDefines.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.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/Analysis/LegacyDivergenceAnalysis.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> DisableLoopAlignment( 94 "amdgpu-disable-loop-alignment", 95 cl::desc("Do not align and prefetch loops"), 96 cl::init(false)); 97 98 static bool hasFP32Denormals(const MachineFunction &MF) { 99 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 100 return Info->getMode().allFP32Denormals(); 101 } 102 103 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().allFP64FP16Denormals(); 106 } 107 108 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 109 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 110 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 111 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 112 return AMDGPU::SGPR0 + Reg; 113 } 114 } 115 llvm_unreachable("Cannot allocate sgpr"); 116 } 117 118 SITargetLowering::SITargetLowering(const TargetMachine &TM, 119 const GCNSubtarget &STI) 120 : AMDGPUTargetLowering(TM, STI), 121 Subtarget(&STI) { 122 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 123 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 124 125 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 126 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 127 128 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 129 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 130 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 131 132 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 133 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 134 135 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 136 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 137 138 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 139 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 140 141 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 142 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 143 144 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 145 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 146 147 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 148 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 149 150 if (Subtarget->has16BitInsts()) { 151 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 152 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 153 154 // Unless there are also VOP3P operations, not operations are really legal. 155 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 156 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 157 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 158 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 159 } 160 161 if (Subtarget->hasMAIInsts()) { 162 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 163 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 164 } 165 166 computeRegisterProperties(Subtarget->getRegisterInfo()); 167 168 // The boolean content concept here is too inflexible. Compares only ever 169 // really produce a 1-bit result. Any copy/extend from these will turn into a 170 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 171 // it's what most targets use. 172 setBooleanContents(ZeroOrOneBooleanContent); 173 setBooleanVectorContents(ZeroOrOneBooleanContent); 174 175 // We need to custom lower vector stores from local memory 176 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 177 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 178 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 179 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 180 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 181 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 182 setOperationAction(ISD::LOAD, MVT::i1, Custom); 183 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 184 185 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 186 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 187 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 188 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 189 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 190 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 191 setOperationAction(ISD::STORE, MVT::i1, Custom); 192 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 193 194 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 195 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 197 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 198 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 199 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 200 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 201 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 202 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 203 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 204 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 205 206 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 208 209 setOperationAction(ISD::SELECT, MVT::i1, Promote); 210 setOperationAction(ISD::SELECT, MVT::i64, Custom); 211 setOperationAction(ISD::SELECT, MVT::f64, Promote); 212 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 213 214 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 216 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 217 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 218 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 219 220 setOperationAction(ISD::SETCC, MVT::i1, Promote); 221 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 222 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 224 225 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 227 228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 236 237 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 238 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 239 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 240 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 241 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 242 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 243 244 setOperationAction(ISD::UADDO, MVT::i32, Legal); 245 setOperationAction(ISD::USUBO, MVT::i32, Legal); 246 247 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 248 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 249 250 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 251 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 252 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 253 254 #if 0 255 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 256 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 257 #endif 258 259 // We only support LOAD/STORE and vector manipulation ops for vectors 260 // with > 4 elements. 261 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 262 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 263 MVT::v32i32, MVT::v32f32 }) { 264 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 265 switch (Op) { 266 case ISD::LOAD: 267 case ISD::STORE: 268 case ISD::BUILD_VECTOR: 269 case ISD::BITCAST: 270 case ISD::EXTRACT_VECTOR_ELT: 271 case ISD::INSERT_VECTOR_ELT: 272 case ISD::INSERT_SUBVECTOR: 273 case ISD::EXTRACT_SUBVECTOR: 274 case ISD::SCALAR_TO_VECTOR: 275 break; 276 case ISD::CONCAT_VECTORS: 277 setOperationAction(Op, VT, Custom); 278 break; 279 default: 280 setOperationAction(Op, VT, Expand); 281 break; 282 } 283 } 284 } 285 286 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 287 288 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 289 // is expanded to avoid having two separate loops in case the index is a VGPR. 290 291 // Most operations are naturally 32-bit vector operations. We only support 292 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 293 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 294 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 295 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 296 297 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 298 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 299 300 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 301 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 302 303 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 305 } 306 307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 311 312 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 314 315 // Avoid stack access for these. 316 // TODO: Generalize to more vector types. 317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 321 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 331 332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 336 337 // Deal with vec3 vector operations when widened to vec4. 338 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 342 343 // Deal with vec5 vector operations when widened to vec8. 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 348 349 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 350 // and output demarshalling 351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 353 354 // We can't return success/failure, only the old value, 355 // let LLVM add the comparison 356 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 358 359 if (Subtarget->hasFlatAddressSpace()) { 360 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 361 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 362 } 363 364 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 365 366 // FIXME: This should be narrowed to i32, but that only happens if i64 is 367 // illegal. 368 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 369 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 370 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 371 372 // On SI this is s_memtime and s_memrealtime on VI. 373 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 374 setOperationAction(ISD::TRAP, MVT::Other, Custom); 375 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 376 377 if (Subtarget->has16BitInsts()) { 378 setOperationAction(ISD::FPOW, MVT::f16, Promote); 379 setOperationAction(ISD::FLOG, MVT::f16, Custom); 380 setOperationAction(ISD::FEXP, MVT::f16, Custom); 381 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 382 } 383 384 // v_mad_f32 does not support denormals. We report it as unconditionally 385 // legal, and the context where it is formed will disallow it when fp32 386 // denormals are enabled. 387 setOperationAction(ISD::FMAD, MVT::f32, Legal); 388 389 if (!Subtarget->hasBFI()) { 390 // fcopysign can be done in a single instruction with BFI. 391 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 392 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 393 } 394 395 if (!Subtarget->hasBCNT(32)) 396 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 397 398 if (!Subtarget->hasBCNT(64)) 399 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 400 401 if (Subtarget->hasFFBH()) 402 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 403 404 if (Subtarget->hasFFBL()) 405 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 406 407 // We only really have 32-bit BFE instructions (and 16-bit on VI). 408 // 409 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 410 // effort to match them now. We want this to be false for i64 cases when the 411 // extraction isn't restricted to the upper or lower half. Ideally we would 412 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 413 // span the midpoint are probably relatively rare, so don't worry about them 414 // for now. 415 if (Subtarget->hasBFE()) 416 setHasExtractBitsInsn(true); 417 418 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 419 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 420 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 421 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 422 423 424 // These are really only legal for ieee_mode functions. We should be avoiding 425 // them for functions that don't have ieee_mode enabled, so just say they are 426 // legal. 427 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 428 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 429 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 430 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 431 432 433 if (Subtarget->haveRoundOpsF64()) { 434 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 435 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 436 setOperationAction(ISD::FRINT, MVT::f64, Legal); 437 } else { 438 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 439 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 440 setOperationAction(ISD::FRINT, MVT::f64, Custom); 441 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 442 } 443 444 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 445 446 setOperationAction(ISD::FSIN, MVT::f32, Custom); 447 setOperationAction(ISD::FCOS, MVT::f32, Custom); 448 setOperationAction(ISD::FDIV, MVT::f32, Custom); 449 setOperationAction(ISD::FDIV, MVT::f64, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::Constant, MVT::i16, Legal); 453 454 setOperationAction(ISD::SMIN, MVT::i16, Legal); 455 setOperationAction(ISD::SMAX, MVT::i16, Legal); 456 457 setOperationAction(ISD::UMIN, MVT::i16, Legal); 458 setOperationAction(ISD::UMAX, MVT::i16, Legal); 459 460 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 461 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 462 463 setOperationAction(ISD::ROTR, MVT::i16, Promote); 464 setOperationAction(ISD::ROTL, MVT::i16, Promote); 465 466 setOperationAction(ISD::SDIV, MVT::i16, Promote); 467 setOperationAction(ISD::UDIV, MVT::i16, Promote); 468 setOperationAction(ISD::SREM, MVT::i16, Promote); 469 setOperationAction(ISD::UREM, MVT::i16, Promote); 470 471 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 472 473 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 475 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 477 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 478 479 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 480 481 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 482 483 setOperationAction(ISD::LOAD, MVT::i16, Custom); 484 485 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 486 487 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 488 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 489 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 490 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 491 492 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 493 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 494 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, Custom); 507 setOperationAction(ISD::FSIN, MVT::f16, Custom); 508 509 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 510 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 511 512 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 513 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 514 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 515 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 516 setOperationAction(ISD::FROUND, MVT::f16, Custom); 517 518 // F16 - VOP2 Actions. 519 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 520 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 521 522 setOperationAction(ISD::FDIV, MVT::f16, Custom); 523 524 // F16 - VOP3 Actions. 525 setOperationAction(ISD::FMA, MVT::f16, Legal); 526 if (STI.hasMadF16()) 527 setOperationAction(ISD::FMAD, MVT::f16, Legal); 528 529 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 530 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 531 switch (Op) { 532 case ISD::LOAD: 533 case ISD::STORE: 534 case ISD::BUILD_VECTOR: 535 case ISD::BITCAST: 536 case ISD::EXTRACT_VECTOR_ELT: 537 case ISD::INSERT_VECTOR_ELT: 538 case ISD::INSERT_SUBVECTOR: 539 case ISD::EXTRACT_SUBVECTOR: 540 case ISD::SCALAR_TO_VECTOR: 541 break; 542 case ISD::CONCAT_VECTORS: 543 setOperationAction(Op, VT, Custom); 544 break; 545 default: 546 setOperationAction(Op, VT, Expand); 547 break; 548 } 549 } 550 } 551 552 // v_perm_b32 can handle either of these. 553 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 554 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 555 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 556 557 // XXX - Do these do anything? Vector constants turn into build_vector. 558 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 559 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 560 561 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 562 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 563 564 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 565 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 566 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 567 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 568 569 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 571 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 573 574 setOperationAction(ISD::AND, MVT::v2i16, Promote); 575 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 576 setOperationAction(ISD::OR, MVT::v2i16, Promote); 577 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 578 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 579 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 580 581 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 582 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 583 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 584 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 585 586 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 587 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 588 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 589 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 590 591 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 592 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 593 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 594 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 595 596 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 597 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 598 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 599 600 if (!Subtarget->hasVOP3PInsts()) { 601 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 602 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 603 } 604 605 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 606 // This isn't really legal, but this avoids the legalizer unrolling it (and 607 // allows matching fneg (fabs x) patterns) 608 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 609 610 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 611 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 612 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 613 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 614 615 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 616 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 617 618 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 619 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 620 } 621 622 if (Subtarget->hasVOP3PInsts()) { 623 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 624 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 625 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 626 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 627 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 628 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 629 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 630 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 631 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 632 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 633 634 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 635 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 636 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 637 638 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 639 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 640 641 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 642 643 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 644 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 645 646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 647 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 648 649 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 650 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 651 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 652 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 653 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 654 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 655 656 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 657 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 658 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 659 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 660 661 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 662 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 663 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 664 665 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 666 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 667 668 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 669 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 670 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 671 672 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 673 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 674 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 675 } 676 677 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 678 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 679 680 if (Subtarget->has16BitInsts()) { 681 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 682 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 683 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 684 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 685 } else { 686 // Legalization hack. 687 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 688 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 689 690 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 691 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 692 } 693 694 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 695 setOperationAction(ISD::SELECT, VT, Custom); 696 } 697 698 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 699 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 700 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 701 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 702 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 703 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 704 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 705 706 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 707 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 708 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 709 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 710 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 711 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 712 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 713 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 714 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 715 716 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 717 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 718 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 719 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 720 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 721 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 722 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 723 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 724 725 setTargetDAGCombine(ISD::ADD); 726 setTargetDAGCombine(ISD::ADDCARRY); 727 setTargetDAGCombine(ISD::SUB); 728 setTargetDAGCombine(ISD::SUBCARRY); 729 setTargetDAGCombine(ISD::FADD); 730 setTargetDAGCombine(ISD::FSUB); 731 setTargetDAGCombine(ISD::FMINNUM); 732 setTargetDAGCombine(ISD::FMAXNUM); 733 setTargetDAGCombine(ISD::FMINNUM_IEEE); 734 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 735 setTargetDAGCombine(ISD::FMA); 736 setTargetDAGCombine(ISD::SMIN); 737 setTargetDAGCombine(ISD::SMAX); 738 setTargetDAGCombine(ISD::UMIN); 739 setTargetDAGCombine(ISD::UMAX); 740 setTargetDAGCombine(ISD::SETCC); 741 setTargetDAGCombine(ISD::AND); 742 setTargetDAGCombine(ISD::OR); 743 setTargetDAGCombine(ISD::XOR); 744 setTargetDAGCombine(ISD::SINT_TO_FP); 745 setTargetDAGCombine(ISD::UINT_TO_FP); 746 setTargetDAGCombine(ISD::FCANONICALIZE); 747 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 748 setTargetDAGCombine(ISD::ZERO_EXTEND); 749 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 750 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 751 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 752 753 // All memory operations. Some folding on the pointer operand is done to help 754 // matching the constant offsets in the addressing modes. 755 setTargetDAGCombine(ISD::LOAD); 756 setTargetDAGCombine(ISD::STORE); 757 setTargetDAGCombine(ISD::ATOMIC_LOAD); 758 setTargetDAGCombine(ISD::ATOMIC_STORE); 759 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 760 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 761 setTargetDAGCombine(ISD::ATOMIC_SWAP); 762 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 763 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 764 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 765 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 766 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 767 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 768 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 769 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 770 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 771 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 772 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 773 774 setSchedulingPreference(Sched::RegPressure); 775 } 776 777 const GCNSubtarget *SITargetLowering::getSubtarget() const { 778 return Subtarget; 779 } 780 781 //===----------------------------------------------------------------------===// 782 // TargetLowering queries 783 //===----------------------------------------------------------------------===// 784 785 // v_mad_mix* support a conversion from f16 to f32. 786 // 787 // There is only one special case when denormals are enabled we don't currently, 788 // where this is OK to use. 789 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 790 EVT DestVT, EVT SrcVT) const { 791 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 792 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 793 DestVT.getScalarType() == MVT::f32 && 794 SrcVT.getScalarType() == MVT::f16 && 795 // TODO: This probably only requires no input flushing? 796 !hasFP32Denormals(DAG.getMachineFunction()); 797 } 798 799 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 800 // SI has some legal vector types, but no legal vector operations. Say no 801 // shuffles are legal in order to prefer scalarizing some vector operations. 802 return false; 803 } 804 805 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 806 CallingConv::ID CC, 807 EVT VT) const { 808 if (CC == CallingConv::AMDGPU_KERNEL) 809 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 810 811 if (VT.isVector()) { 812 EVT ScalarVT = VT.getScalarType(); 813 unsigned Size = ScalarVT.getSizeInBits(); 814 if (Size == 32) 815 return ScalarVT.getSimpleVT(); 816 817 if (Size > 32) 818 return MVT::i32; 819 820 if (Size == 16 && Subtarget->has16BitInsts()) 821 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 822 } else if (VT.getSizeInBits() > 32) 823 return MVT::i32; 824 825 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 826 } 827 828 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 829 CallingConv::ID CC, 830 EVT VT) const { 831 if (CC == CallingConv::AMDGPU_KERNEL) 832 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 833 834 if (VT.isVector()) { 835 unsigned NumElts = VT.getVectorNumElements(); 836 EVT ScalarVT = VT.getScalarType(); 837 unsigned Size = ScalarVT.getSizeInBits(); 838 839 if (Size == 32) 840 return NumElts; 841 842 if (Size > 32) 843 return NumElts * ((Size + 31) / 32); 844 845 if (Size == 16 && Subtarget->has16BitInsts()) 846 return (NumElts + 1) / 2; 847 } else if (VT.getSizeInBits() > 32) 848 return (VT.getSizeInBits() + 31) / 32; 849 850 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 851 } 852 853 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 854 LLVMContext &Context, CallingConv::ID CC, 855 EVT VT, EVT &IntermediateVT, 856 unsigned &NumIntermediates, MVT &RegisterVT) const { 857 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 858 unsigned NumElts = VT.getVectorNumElements(); 859 EVT ScalarVT = VT.getScalarType(); 860 unsigned Size = ScalarVT.getSizeInBits(); 861 if (Size == 32) { 862 RegisterVT = ScalarVT.getSimpleVT(); 863 IntermediateVT = RegisterVT; 864 NumIntermediates = NumElts; 865 return NumIntermediates; 866 } 867 868 if (Size > 32) { 869 RegisterVT = MVT::i32; 870 IntermediateVT = RegisterVT; 871 NumIntermediates = NumElts * ((Size + 31) / 32); 872 return NumIntermediates; 873 } 874 875 // FIXME: We should fix the ABI to be the same on targets without 16-bit 876 // support, but unless we can properly handle 3-vectors, it will be still be 877 // inconsistent. 878 if (Size == 16 && Subtarget->has16BitInsts()) { 879 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 880 IntermediateVT = RegisterVT; 881 NumIntermediates = (NumElts + 1) / 2; 882 return NumIntermediates; 883 } 884 } 885 886 return TargetLowering::getVectorTypeBreakdownForCallingConv( 887 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 888 } 889 890 // Peek through TFE struct returns to only use the data size. 891 static EVT memVTFromImageReturn(Type *Ty) { 892 auto *ST = dyn_cast<StructType>(Ty); 893 if (!ST) 894 return EVT::getEVT(Ty, true); 895 896 // Some intrinsics return an aggregate type - special case to work out the 897 // correct memVT. 898 // 899 // Only limited forms of aggregate type currently expected. 900 if (ST->getNumContainedTypes() != 2 || 901 !ST->getContainedType(1)->isIntegerTy(32)) 902 return EVT(); 903 return EVT::getEVT(ST->getContainedType(0)); 904 } 905 906 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 907 const CallInst &CI, 908 MachineFunction &MF, 909 unsigned IntrID) const { 910 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 911 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 912 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 913 (Intrinsic::ID)IntrID); 914 if (Attr.hasFnAttribute(Attribute::ReadNone)) 915 return false; 916 917 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 918 919 if (RsrcIntr->IsImage) { 920 Info.ptrVal = MFI->getImagePSV( 921 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 922 CI.getArgOperand(RsrcIntr->RsrcArg)); 923 Info.align.reset(); 924 } else { 925 Info.ptrVal = MFI->getBufferPSV( 926 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 927 CI.getArgOperand(RsrcIntr->RsrcArg)); 928 } 929 930 Info.flags = MachineMemOperand::MODereferenceable; 931 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 932 Info.opc = ISD::INTRINSIC_W_CHAIN; 933 // TODO: Account for dmask reducing loaded size. 934 Info.memVT = memVTFromImageReturn(CI.getType()); 935 Info.flags |= MachineMemOperand::MOLoad; 936 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 937 Info.opc = ISD::INTRINSIC_VOID; 938 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 939 Info.flags |= MachineMemOperand::MOStore; 940 } else { 941 // Atomic 942 Info.opc = ISD::INTRINSIC_W_CHAIN; 943 Info.memVT = MVT::getVT(CI.getType()); 944 Info.flags = MachineMemOperand::MOLoad | 945 MachineMemOperand::MOStore | 946 MachineMemOperand::MODereferenceable; 947 948 // XXX - Should this be volatile without known ordering? 949 Info.flags |= MachineMemOperand::MOVolatile; 950 } 951 return true; 952 } 953 954 switch (IntrID) { 955 case Intrinsic::amdgcn_atomic_inc: 956 case Intrinsic::amdgcn_atomic_dec: 957 case Intrinsic::amdgcn_ds_ordered_add: 958 case Intrinsic::amdgcn_ds_ordered_swap: 959 case Intrinsic::amdgcn_ds_fadd: 960 case Intrinsic::amdgcn_ds_fmin: 961 case Intrinsic::amdgcn_ds_fmax: { 962 Info.opc = ISD::INTRINSIC_W_CHAIN; 963 Info.memVT = MVT::getVT(CI.getType()); 964 Info.ptrVal = CI.getOperand(0); 965 Info.align.reset(); 966 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 967 968 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 969 if (!Vol->isZero()) 970 Info.flags |= MachineMemOperand::MOVolatile; 971 972 return true; 973 } 974 case Intrinsic::amdgcn_buffer_atomic_fadd: { 975 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 976 977 Info.opc = ISD::INTRINSIC_VOID; 978 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 979 Info.ptrVal = MFI->getBufferPSV( 980 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 981 CI.getArgOperand(1)); 982 Info.align.reset(); 983 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 984 985 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 986 if (!Vol || !Vol->isZero()) 987 Info.flags |= MachineMemOperand::MOVolatile; 988 989 return true; 990 } 991 case Intrinsic::amdgcn_global_atomic_fadd: { 992 Info.opc = ISD::INTRINSIC_VOID; 993 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 994 ->getPointerElementType()); 995 Info.ptrVal = CI.getOperand(0); 996 Info.align.reset(); 997 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 998 999 return true; 1000 } 1001 case Intrinsic::amdgcn_ds_append: 1002 case Intrinsic::amdgcn_ds_consume: { 1003 Info.opc = ISD::INTRINSIC_W_CHAIN; 1004 Info.memVT = MVT::getVT(CI.getType()); 1005 Info.ptrVal = CI.getOperand(0); 1006 Info.align.reset(); 1007 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1008 1009 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1010 if (!Vol->isZero()) 1011 Info.flags |= MachineMemOperand::MOVolatile; 1012 1013 return true; 1014 } 1015 case Intrinsic::amdgcn_ds_gws_init: 1016 case Intrinsic::amdgcn_ds_gws_barrier: 1017 case Intrinsic::amdgcn_ds_gws_sema_v: 1018 case Intrinsic::amdgcn_ds_gws_sema_br: 1019 case Intrinsic::amdgcn_ds_gws_sema_p: 1020 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1021 Info.opc = ISD::INTRINSIC_VOID; 1022 1023 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1024 Info.ptrVal = 1025 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1026 1027 // This is an abstract access, but we need to specify a type and size. 1028 Info.memVT = MVT::i32; 1029 Info.size = 4; 1030 Info.align = Align(4); 1031 1032 Info.flags = MachineMemOperand::MOStore; 1033 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1034 Info.flags = MachineMemOperand::MOLoad; 1035 return true; 1036 } 1037 default: 1038 return false; 1039 } 1040 } 1041 1042 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1043 SmallVectorImpl<Value*> &Ops, 1044 Type *&AccessTy) const { 1045 switch (II->getIntrinsicID()) { 1046 case Intrinsic::amdgcn_atomic_inc: 1047 case Intrinsic::amdgcn_atomic_dec: 1048 case Intrinsic::amdgcn_ds_ordered_add: 1049 case Intrinsic::amdgcn_ds_ordered_swap: 1050 case Intrinsic::amdgcn_ds_fadd: 1051 case Intrinsic::amdgcn_ds_fmin: 1052 case Intrinsic::amdgcn_ds_fmax: { 1053 Value *Ptr = II->getArgOperand(0); 1054 AccessTy = II->getType(); 1055 Ops.push_back(Ptr); 1056 return true; 1057 } 1058 default: 1059 return false; 1060 } 1061 } 1062 1063 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1064 if (!Subtarget->hasFlatInstOffsets()) { 1065 // Flat instructions do not have offsets, and only have the register 1066 // address. 1067 return AM.BaseOffs == 0 && AM.Scale == 0; 1068 } 1069 1070 return AM.Scale == 0 && 1071 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1072 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1073 /*Signed=*/false)); 1074 } 1075 1076 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1077 if (Subtarget->hasFlatGlobalInsts()) 1078 return AM.Scale == 0 && 1079 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1080 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1081 /*Signed=*/true)); 1082 1083 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1084 // Assume the we will use FLAT for all global memory accesses 1085 // on VI. 1086 // FIXME: This assumption is currently wrong. On VI we still use 1087 // MUBUF instructions for the r + i addressing mode. As currently 1088 // implemented, the MUBUF instructions only work on buffer < 4GB. 1089 // It may be possible to support > 4GB buffers with MUBUF instructions, 1090 // by setting the stride value in the resource descriptor which would 1091 // increase the size limit to (stride * 4GB). However, this is risky, 1092 // because it has never been validated. 1093 return isLegalFlatAddressingMode(AM); 1094 } 1095 1096 return isLegalMUBUFAddressingMode(AM); 1097 } 1098 1099 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1100 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1101 // additionally can do r + r + i with addr64. 32-bit has more addressing 1102 // mode options. Depending on the resource constant, it can also do 1103 // (i64 r0) + (i32 r1) * (i14 i). 1104 // 1105 // Private arrays end up using a scratch buffer most of the time, so also 1106 // assume those use MUBUF instructions. Scratch loads / stores are currently 1107 // implemented as mubuf instructions with offen bit set, so slightly 1108 // different than the normal addr64. 1109 if (!isUInt<12>(AM.BaseOffs)) 1110 return false; 1111 1112 // FIXME: Since we can split immediate into soffset and immediate offset, 1113 // would it make sense to allow any immediate? 1114 1115 switch (AM.Scale) { 1116 case 0: // r + i or just i, depending on HasBaseReg. 1117 return true; 1118 case 1: 1119 return true; // We have r + r or r + i. 1120 case 2: 1121 if (AM.HasBaseReg) { 1122 // Reject 2 * r + r. 1123 return false; 1124 } 1125 1126 // Allow 2 * r as r + r 1127 // Or 2 * r + i is allowed as r + r + i. 1128 return true; 1129 default: // Don't allow n * r 1130 return false; 1131 } 1132 } 1133 1134 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1135 const AddrMode &AM, Type *Ty, 1136 unsigned AS, Instruction *I) const { 1137 // No global is ever allowed as a base. 1138 if (AM.BaseGV) 1139 return false; 1140 1141 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1142 return isLegalGlobalAddressingMode(AM); 1143 1144 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1145 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1146 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1147 // If the offset isn't a multiple of 4, it probably isn't going to be 1148 // correctly aligned. 1149 // FIXME: Can we get the real alignment here? 1150 if (AM.BaseOffs % 4 != 0) 1151 return isLegalMUBUFAddressingMode(AM); 1152 1153 // There are no SMRD extloads, so if we have to do a small type access we 1154 // will use a MUBUF load. 1155 // FIXME?: We also need to do this if unaligned, but we don't know the 1156 // alignment here. 1157 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1158 return isLegalGlobalAddressingMode(AM); 1159 1160 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1161 // SMRD instructions have an 8-bit, dword offset on SI. 1162 if (!isUInt<8>(AM.BaseOffs / 4)) 1163 return false; 1164 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1165 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1166 // in 8-bits, it can use a smaller encoding. 1167 if (!isUInt<32>(AM.BaseOffs / 4)) 1168 return false; 1169 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1170 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1171 if (!isUInt<20>(AM.BaseOffs)) 1172 return false; 1173 } else 1174 llvm_unreachable("unhandled generation"); 1175 1176 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1177 return true; 1178 1179 if (AM.Scale == 1 && AM.HasBaseReg) 1180 return true; 1181 1182 return false; 1183 1184 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1185 return isLegalMUBUFAddressingMode(AM); 1186 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1187 AS == AMDGPUAS::REGION_ADDRESS) { 1188 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1189 // field. 1190 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1191 // an 8-bit dword offset but we don't know the alignment here. 1192 if (!isUInt<16>(AM.BaseOffs)) 1193 return false; 1194 1195 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1196 return true; 1197 1198 if (AM.Scale == 1 && AM.HasBaseReg) 1199 return true; 1200 1201 return false; 1202 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1203 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1204 // For an unknown address space, this usually means that this is for some 1205 // reason being used for pure arithmetic, and not based on some addressing 1206 // computation. We don't have instructions that compute pointers with any 1207 // addressing modes, so treat them as having no offset like flat 1208 // instructions. 1209 return isLegalFlatAddressingMode(AM); 1210 } else { 1211 llvm_unreachable("unhandled address space"); 1212 } 1213 } 1214 1215 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1216 const SelectionDAG &DAG) const { 1217 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1218 return (MemVT.getSizeInBits() <= 4 * 32); 1219 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1220 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1221 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1222 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1223 return (MemVT.getSizeInBits() <= 2 * 32); 1224 } 1225 return true; 1226 } 1227 1228 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1229 unsigned Size, unsigned AddrSpace, unsigned Align, 1230 MachineMemOperand::Flags Flags, bool *IsFast) const { 1231 if (IsFast) 1232 *IsFast = false; 1233 1234 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1235 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1236 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1237 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1238 // with adjacent offsets. 1239 bool AlignedBy4 = (Align % 4 == 0); 1240 if (IsFast) 1241 *IsFast = AlignedBy4; 1242 1243 return AlignedBy4; 1244 } 1245 1246 // FIXME: We have to be conservative here and assume that flat operations 1247 // will access scratch. If we had access to the IR function, then we 1248 // could determine if any private memory was used in the function. 1249 if (!Subtarget->hasUnalignedScratchAccess() && 1250 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1251 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1252 bool AlignedBy4 = Align >= 4; 1253 if (IsFast) 1254 *IsFast = AlignedBy4; 1255 1256 return AlignedBy4; 1257 } 1258 1259 if (Subtarget->hasUnalignedBufferAccess()) { 1260 // If we have an uniform constant load, it still requires using a slow 1261 // buffer instruction if unaligned. 1262 if (IsFast) { 1263 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1264 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1265 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1266 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1267 Align >= 4 : Align != 2; 1268 } 1269 1270 return true; 1271 } 1272 1273 // Smaller than dword value must be aligned. 1274 if (Size < 32) 1275 return false; 1276 1277 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1278 // byte-address are ignored, thus forcing Dword alignment. 1279 // This applies to private, global, and constant memory. 1280 if (IsFast) 1281 *IsFast = true; 1282 1283 return Size >= 32 && Align >= 4; 1284 } 1285 1286 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1287 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1288 bool *IsFast) const { 1289 if (IsFast) 1290 *IsFast = false; 1291 1292 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1293 // which isn't a simple VT. 1294 // Until MVT is extended to handle this, simply check for the size and 1295 // rely on the condition below: allow accesses if the size is a multiple of 4. 1296 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1297 VT.getStoreSize() > 16)) { 1298 return false; 1299 } 1300 1301 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1302 Align, Flags, IsFast); 1303 } 1304 1305 EVT SITargetLowering::getOptimalMemOpType( 1306 const MemOp &Op, const AttributeList &FuncAttributes) const { 1307 // FIXME: Should account for address space here. 1308 1309 // The default fallback uses the private pointer size as a guess for a type to 1310 // use. Make sure we switch these to 64-bit accesses. 1311 1312 if (Op.size() >= 16 && 1313 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1314 return MVT::v4i32; 1315 1316 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1317 return MVT::v2i32; 1318 1319 // Use the default. 1320 return MVT::Other; 1321 } 1322 1323 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1324 unsigned DestAS) const { 1325 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1326 } 1327 1328 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1329 const MemSDNode *MemNode = cast<MemSDNode>(N); 1330 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1331 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1332 return I && I->getMetadata("amdgpu.noclobber"); 1333 } 1334 1335 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1336 unsigned DestAS) const { 1337 // Flat -> private/local is a simple truncate. 1338 // Flat -> global is no-op 1339 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1340 return true; 1341 1342 return isNoopAddrSpaceCast(SrcAS, DestAS); 1343 } 1344 1345 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1346 const MemSDNode *MemNode = cast<MemSDNode>(N); 1347 1348 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1349 } 1350 1351 TargetLoweringBase::LegalizeTypeAction 1352 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1353 int NumElts = VT.getVectorNumElements(); 1354 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1355 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1356 return TargetLoweringBase::getPreferredVectorAction(VT); 1357 } 1358 1359 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1360 Type *Ty) const { 1361 // FIXME: Could be smarter if called for vector constants. 1362 return true; 1363 } 1364 1365 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1366 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1367 switch (Op) { 1368 case ISD::LOAD: 1369 case ISD::STORE: 1370 1371 // These operations are done with 32-bit instructions anyway. 1372 case ISD::AND: 1373 case ISD::OR: 1374 case ISD::XOR: 1375 case ISD::SELECT: 1376 // TODO: Extensions? 1377 return true; 1378 default: 1379 return false; 1380 } 1381 } 1382 1383 // SimplifySetCC uses this function to determine whether or not it should 1384 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1385 if (VT == MVT::i1 && Op == ISD::SETCC) 1386 return false; 1387 1388 return TargetLowering::isTypeDesirableForOp(Op, VT); 1389 } 1390 1391 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1392 const SDLoc &SL, 1393 SDValue Chain, 1394 uint64_t Offset) const { 1395 const DataLayout &DL = DAG.getDataLayout(); 1396 MachineFunction &MF = DAG.getMachineFunction(); 1397 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1398 1399 const ArgDescriptor *InputPtrReg; 1400 const TargetRegisterClass *RC; 1401 1402 std::tie(InputPtrReg, RC) 1403 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1404 1405 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1406 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1407 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1408 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1409 1410 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1411 } 1412 1413 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1414 const SDLoc &SL) const { 1415 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1416 FIRST_IMPLICIT); 1417 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1418 } 1419 1420 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1421 const SDLoc &SL, SDValue Val, 1422 bool Signed, 1423 const ISD::InputArg *Arg) const { 1424 // First, if it is a widened vector, narrow it. 1425 if (VT.isVector() && 1426 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1427 EVT NarrowedVT = 1428 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1429 VT.getVectorNumElements()); 1430 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1431 DAG.getConstant(0, SL, MVT::i32)); 1432 } 1433 1434 // Then convert the vector elements or scalar value. 1435 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1436 VT.bitsLT(MemVT)) { 1437 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1438 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1439 } 1440 1441 if (MemVT.isFloatingPoint()) 1442 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1443 else if (Signed) 1444 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1445 else 1446 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1447 1448 return Val; 1449 } 1450 1451 SDValue SITargetLowering::lowerKernargMemParameter( 1452 SelectionDAG &DAG, EVT VT, EVT MemVT, 1453 const SDLoc &SL, SDValue Chain, 1454 uint64_t Offset, unsigned Align, bool Signed, 1455 const ISD::InputArg *Arg) const { 1456 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1457 1458 // Try to avoid using an extload by loading earlier than the argument address, 1459 // and extracting the relevant bits. The load should hopefully be merged with 1460 // the previous argument. 1461 if (MemVT.getStoreSize() < 4 && Align < 4) { 1462 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1463 int64_t AlignDownOffset = alignDown(Offset, 4); 1464 int64_t OffsetDiff = Offset - AlignDownOffset; 1465 1466 EVT IntVT = MemVT.changeTypeToInteger(); 1467 1468 // TODO: If we passed in the base kernel offset we could have a better 1469 // alignment than 4, but we don't really need it. 1470 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1471 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1472 MachineMemOperand::MODereferenceable | 1473 MachineMemOperand::MOInvariant); 1474 1475 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1476 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1477 1478 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1479 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1480 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1481 1482 1483 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1484 } 1485 1486 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1487 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1488 MachineMemOperand::MODereferenceable | 1489 MachineMemOperand::MOInvariant); 1490 1491 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1492 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1493 } 1494 1495 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1496 const SDLoc &SL, SDValue Chain, 1497 const ISD::InputArg &Arg) const { 1498 MachineFunction &MF = DAG.getMachineFunction(); 1499 MachineFrameInfo &MFI = MF.getFrameInfo(); 1500 1501 if (Arg.Flags.isByVal()) { 1502 unsigned Size = Arg.Flags.getByValSize(); 1503 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1504 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1505 } 1506 1507 unsigned ArgOffset = VA.getLocMemOffset(); 1508 unsigned ArgSize = VA.getValVT().getStoreSize(); 1509 1510 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1511 1512 // Create load nodes to retrieve arguments from the stack. 1513 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1514 SDValue ArgValue; 1515 1516 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1517 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1518 MVT MemVT = VA.getValVT(); 1519 1520 switch (VA.getLocInfo()) { 1521 default: 1522 break; 1523 case CCValAssign::BCvt: 1524 MemVT = VA.getLocVT(); 1525 break; 1526 case CCValAssign::SExt: 1527 ExtType = ISD::SEXTLOAD; 1528 break; 1529 case CCValAssign::ZExt: 1530 ExtType = ISD::ZEXTLOAD; 1531 break; 1532 case CCValAssign::AExt: 1533 ExtType = ISD::EXTLOAD; 1534 break; 1535 } 1536 1537 ArgValue = DAG.getExtLoad( 1538 ExtType, SL, VA.getLocVT(), Chain, FIN, 1539 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1540 MemVT); 1541 return ArgValue; 1542 } 1543 1544 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1545 const SIMachineFunctionInfo &MFI, 1546 EVT VT, 1547 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1548 const ArgDescriptor *Reg; 1549 const TargetRegisterClass *RC; 1550 1551 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1552 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1553 } 1554 1555 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1556 CallingConv::ID CallConv, 1557 ArrayRef<ISD::InputArg> Ins, 1558 BitVector &Skipped, 1559 FunctionType *FType, 1560 SIMachineFunctionInfo *Info) { 1561 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1562 const ISD::InputArg *Arg = &Ins[I]; 1563 1564 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1565 "vector type argument should have been split"); 1566 1567 // First check if it's a PS input addr. 1568 if (CallConv == CallingConv::AMDGPU_PS && 1569 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1570 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1571 1572 // Inconveniently only the first part of the split is marked as isSplit, 1573 // so skip to the end. We only want to increment PSInputNum once for the 1574 // entire split argument. 1575 if (Arg->Flags.isSplit()) { 1576 while (!Arg->Flags.isSplitEnd()) { 1577 assert((!Arg->VT.isVector() || 1578 Arg->VT.getScalarSizeInBits() == 16) && 1579 "unexpected vector split in ps argument type"); 1580 if (!SkipArg) 1581 Splits.push_back(*Arg); 1582 Arg = &Ins[++I]; 1583 } 1584 } 1585 1586 if (SkipArg) { 1587 // We can safely skip PS inputs. 1588 Skipped.set(Arg->getOrigArgIndex()); 1589 ++PSInputNum; 1590 continue; 1591 } 1592 1593 Info->markPSInputAllocated(PSInputNum); 1594 if (Arg->Used) 1595 Info->markPSInputEnabled(PSInputNum); 1596 1597 ++PSInputNum; 1598 } 1599 1600 Splits.push_back(*Arg); 1601 } 1602 } 1603 1604 // Allocate special inputs passed in VGPRs. 1605 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1606 MachineFunction &MF, 1607 const SIRegisterInfo &TRI, 1608 SIMachineFunctionInfo &Info) const { 1609 const LLT S32 = LLT::scalar(32); 1610 MachineRegisterInfo &MRI = MF.getRegInfo(); 1611 1612 if (Info.hasWorkItemIDX()) { 1613 Register Reg = AMDGPU::VGPR0; 1614 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1615 1616 CCInfo.AllocateReg(Reg); 1617 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1618 } 1619 1620 if (Info.hasWorkItemIDY()) { 1621 Register Reg = AMDGPU::VGPR1; 1622 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1623 1624 CCInfo.AllocateReg(Reg); 1625 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1626 } 1627 1628 if (Info.hasWorkItemIDZ()) { 1629 Register Reg = AMDGPU::VGPR2; 1630 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1631 1632 CCInfo.AllocateReg(Reg); 1633 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1634 } 1635 } 1636 1637 // Try to allocate a VGPR at the end of the argument list, or if no argument 1638 // VGPRs are left allocating a stack slot. 1639 // If \p Mask is is given it indicates bitfield position in the register. 1640 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1641 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1642 ArgDescriptor Arg = ArgDescriptor()) { 1643 if (Arg.isSet()) 1644 return ArgDescriptor::createArg(Arg, Mask); 1645 1646 ArrayRef<MCPhysReg> ArgVGPRs 1647 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1648 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1649 if (RegIdx == ArgVGPRs.size()) { 1650 // Spill to stack required. 1651 int64_t Offset = CCInfo.AllocateStack(4, 4); 1652 1653 return ArgDescriptor::createStack(Offset, Mask); 1654 } 1655 1656 unsigned Reg = ArgVGPRs[RegIdx]; 1657 Reg = CCInfo.AllocateReg(Reg); 1658 assert(Reg != AMDGPU::NoRegister); 1659 1660 MachineFunction &MF = CCInfo.getMachineFunction(); 1661 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1662 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1663 return ArgDescriptor::createRegister(Reg, Mask); 1664 } 1665 1666 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1667 const TargetRegisterClass *RC, 1668 unsigned NumArgRegs) { 1669 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1670 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1671 if (RegIdx == ArgSGPRs.size()) 1672 report_fatal_error("ran out of SGPRs for arguments"); 1673 1674 unsigned Reg = ArgSGPRs[RegIdx]; 1675 Reg = CCInfo.AllocateReg(Reg); 1676 assert(Reg != AMDGPU::NoRegister); 1677 1678 MachineFunction &MF = CCInfo.getMachineFunction(); 1679 MF.addLiveIn(Reg, RC); 1680 return ArgDescriptor::createRegister(Reg); 1681 } 1682 1683 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1684 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1685 } 1686 1687 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1688 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1689 } 1690 1691 /// Allocate implicit function VGPR arguments at the end of allocated user 1692 /// arguments. 1693 void SITargetLowering::allocateSpecialInputVGPRs( 1694 CCState &CCInfo, MachineFunction &MF, 1695 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1696 const unsigned Mask = 0x3ff; 1697 ArgDescriptor Arg; 1698 1699 if (Info.hasWorkItemIDX()) { 1700 Arg = allocateVGPR32Input(CCInfo, Mask); 1701 Info.setWorkItemIDX(Arg); 1702 } 1703 1704 if (Info.hasWorkItemIDY()) { 1705 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1706 Info.setWorkItemIDY(Arg); 1707 } 1708 1709 if (Info.hasWorkItemIDZ()) 1710 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1711 } 1712 1713 /// Allocate implicit function VGPR arguments in fixed registers. 1714 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1715 CCState &CCInfo, MachineFunction &MF, 1716 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1717 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1718 if (!Reg) 1719 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1720 1721 const unsigned Mask = 0x3ff; 1722 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1723 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1724 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1725 } 1726 1727 void SITargetLowering::allocateSpecialInputSGPRs( 1728 CCState &CCInfo, 1729 MachineFunction &MF, 1730 const SIRegisterInfo &TRI, 1731 SIMachineFunctionInfo &Info) const { 1732 auto &ArgInfo = Info.getArgInfo(); 1733 1734 // TODO: Unify handling with private memory pointers. 1735 1736 if (Info.hasDispatchPtr()) 1737 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1738 1739 if (Info.hasQueuePtr()) 1740 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1741 1742 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1743 // constant offset from the kernarg segment. 1744 if (Info.hasImplicitArgPtr()) 1745 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1746 1747 if (Info.hasDispatchID()) 1748 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1749 1750 // flat_scratch_init is not applicable for non-kernel functions. 1751 1752 if (Info.hasWorkGroupIDX()) 1753 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1754 1755 if (Info.hasWorkGroupIDY()) 1756 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1757 1758 if (Info.hasWorkGroupIDZ()) 1759 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1760 } 1761 1762 // Allocate special inputs passed in user SGPRs. 1763 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1764 MachineFunction &MF, 1765 const SIRegisterInfo &TRI, 1766 SIMachineFunctionInfo &Info) const { 1767 if (Info.hasImplicitBufferPtr()) { 1768 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1769 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1770 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1771 } 1772 1773 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1774 if (Info.hasPrivateSegmentBuffer()) { 1775 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1776 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1777 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1778 } 1779 1780 if (Info.hasDispatchPtr()) { 1781 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1782 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1783 CCInfo.AllocateReg(DispatchPtrReg); 1784 } 1785 1786 if (Info.hasQueuePtr()) { 1787 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1788 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1789 CCInfo.AllocateReg(QueuePtrReg); 1790 } 1791 1792 if (Info.hasKernargSegmentPtr()) { 1793 MachineRegisterInfo &MRI = MF.getRegInfo(); 1794 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1795 CCInfo.AllocateReg(InputPtrReg); 1796 1797 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1798 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1799 } 1800 1801 if (Info.hasDispatchID()) { 1802 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1803 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1804 CCInfo.AllocateReg(DispatchIDReg); 1805 } 1806 1807 if (Info.hasFlatScratchInit()) { 1808 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1809 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1810 CCInfo.AllocateReg(FlatScratchInitReg); 1811 } 1812 1813 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1814 // these from the dispatch pointer. 1815 } 1816 1817 // Allocate special input registers that are initialized per-wave. 1818 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1819 MachineFunction &MF, 1820 SIMachineFunctionInfo &Info, 1821 CallingConv::ID CallConv, 1822 bool IsShader) const { 1823 if (Info.hasWorkGroupIDX()) { 1824 unsigned Reg = Info.addWorkGroupIDX(); 1825 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1826 CCInfo.AllocateReg(Reg); 1827 } 1828 1829 if (Info.hasWorkGroupIDY()) { 1830 unsigned Reg = Info.addWorkGroupIDY(); 1831 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1832 CCInfo.AllocateReg(Reg); 1833 } 1834 1835 if (Info.hasWorkGroupIDZ()) { 1836 unsigned Reg = Info.addWorkGroupIDZ(); 1837 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1838 CCInfo.AllocateReg(Reg); 1839 } 1840 1841 if (Info.hasWorkGroupInfo()) { 1842 unsigned Reg = Info.addWorkGroupInfo(); 1843 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1844 CCInfo.AllocateReg(Reg); 1845 } 1846 1847 if (Info.hasPrivateSegmentWaveByteOffset()) { 1848 // Scratch wave offset passed in system SGPR. 1849 unsigned PrivateSegmentWaveByteOffsetReg; 1850 1851 if (IsShader) { 1852 PrivateSegmentWaveByteOffsetReg = 1853 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1854 1855 // This is true if the scratch wave byte offset doesn't have a fixed 1856 // location. 1857 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1858 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1859 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1860 } 1861 } else 1862 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1863 1864 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1865 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1866 } 1867 } 1868 1869 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1870 MachineFunction &MF, 1871 const SIRegisterInfo &TRI, 1872 SIMachineFunctionInfo &Info) { 1873 // Now that we've figured out where the scratch register inputs are, see if 1874 // should reserve the arguments and use them directly. 1875 MachineFrameInfo &MFI = MF.getFrameInfo(); 1876 bool HasStackObjects = MFI.hasStackObjects(); 1877 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1878 1879 // Record that we know we have non-spill stack objects so we don't need to 1880 // check all stack objects later. 1881 if (HasStackObjects) 1882 Info.setHasNonSpillStackObjects(true); 1883 1884 // Everything live out of a block is spilled with fast regalloc, so it's 1885 // almost certain that spilling will be required. 1886 if (TM.getOptLevel() == CodeGenOpt::None) 1887 HasStackObjects = true; 1888 1889 // For now assume stack access is needed in any callee functions, so we need 1890 // the scratch registers to pass in. 1891 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1892 1893 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1894 // If we have stack objects, we unquestionably need the private buffer 1895 // resource. For the Code Object V2 ABI, this will be the first 4 user 1896 // SGPR inputs. We can reserve those and use them directly. 1897 1898 Register PrivateSegmentBufferReg = 1899 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1900 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1901 } else { 1902 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1903 // We tentatively reserve the last registers (skipping the last registers 1904 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1905 // we'll replace these with the ones immediately after those which were 1906 // really allocated. In the prologue copies will be inserted from the 1907 // argument to these reserved registers. 1908 1909 // Without HSA, relocations are used for the scratch pointer and the 1910 // buffer resource setup is always inserted in the prologue. Scratch wave 1911 // offset is still in an input SGPR. 1912 Info.setScratchRSrcReg(ReservedBufferReg); 1913 } 1914 1915 MachineRegisterInfo &MRI = MF.getRegInfo(); 1916 1917 // For entry functions we have to set up the stack pointer if we use it, 1918 // whereas non-entry functions get this "for free". This means there is no 1919 // intrinsic advantage to using S32 over S34 in cases where we do not have 1920 // calls but do need a frame pointer (i.e. if we are requested to have one 1921 // because frame pointer elimination is disabled). To keep things simple we 1922 // only ever use S32 as the call ABI stack pointer, and so using it does not 1923 // imply we need a separate frame pointer. 1924 // 1925 // Try to use s32 as the SP, but move it if it would interfere with input 1926 // arguments. This won't work with calls though. 1927 // 1928 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1929 // registers. 1930 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1931 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1932 } else { 1933 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1934 1935 if (MFI.hasCalls()) 1936 report_fatal_error("call in graphics shader with too many input SGPRs"); 1937 1938 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1939 if (!MRI.isLiveIn(Reg)) { 1940 Info.setStackPtrOffsetReg(Reg); 1941 break; 1942 } 1943 } 1944 1945 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1946 report_fatal_error("failed to find register for SP"); 1947 } 1948 1949 // hasFP should be accurate for entry functions even before the frame is 1950 // finalized, because it does not rely on the known stack size, only 1951 // properties like whether variable sized objects are present. 1952 if (ST.getFrameLowering()->hasFP(MF)) { 1953 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1954 } 1955 } 1956 1957 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1958 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1959 return !Info->isEntryFunction(); 1960 } 1961 1962 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1963 1964 } 1965 1966 void SITargetLowering::insertCopiesSplitCSR( 1967 MachineBasicBlock *Entry, 1968 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1969 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1970 1971 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1972 if (!IStart) 1973 return; 1974 1975 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1976 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1977 MachineBasicBlock::iterator MBBI = Entry->begin(); 1978 for (const MCPhysReg *I = IStart; *I; ++I) { 1979 const TargetRegisterClass *RC = nullptr; 1980 if (AMDGPU::SReg_64RegClass.contains(*I)) 1981 RC = &AMDGPU::SGPR_64RegClass; 1982 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1983 RC = &AMDGPU::SGPR_32RegClass; 1984 else 1985 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1986 1987 Register NewVR = MRI->createVirtualRegister(RC); 1988 // Create copy from CSR to a virtual register. 1989 Entry->addLiveIn(*I); 1990 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1991 .addReg(*I); 1992 1993 // Insert the copy-back instructions right before the terminator. 1994 for (auto *Exit : Exits) 1995 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 1996 TII->get(TargetOpcode::COPY), *I) 1997 .addReg(NewVR); 1998 } 1999 } 2000 2001 SDValue SITargetLowering::LowerFormalArguments( 2002 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2003 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2004 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2005 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2006 2007 MachineFunction &MF = DAG.getMachineFunction(); 2008 const Function &Fn = MF.getFunction(); 2009 FunctionType *FType = MF.getFunction().getFunctionType(); 2010 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2011 2012 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2013 DiagnosticInfoUnsupported NoGraphicsHSA( 2014 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2015 DAG.getContext()->diagnose(NoGraphicsHSA); 2016 return DAG.getEntryNode(); 2017 } 2018 2019 SmallVector<ISD::InputArg, 16> Splits; 2020 SmallVector<CCValAssign, 16> ArgLocs; 2021 BitVector Skipped(Ins.size()); 2022 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2023 *DAG.getContext()); 2024 2025 bool IsShader = AMDGPU::isShader(CallConv); 2026 bool IsKernel = AMDGPU::isKernel(CallConv); 2027 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2028 2029 if (IsShader) { 2030 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2031 2032 // At least one interpolation mode must be enabled or else the GPU will 2033 // hang. 2034 // 2035 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2036 // set PSInputAddr, the user wants to enable some bits after the compilation 2037 // based on run-time states. Since we can't know what the final PSInputEna 2038 // will look like, so we shouldn't do anything here and the user should take 2039 // responsibility for the correct programming. 2040 // 2041 // Otherwise, the following restrictions apply: 2042 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2043 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2044 // enabled too. 2045 if (CallConv == CallingConv::AMDGPU_PS) { 2046 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2047 ((Info->getPSInputAddr() & 0xF) == 0 && 2048 Info->isPSInputAllocated(11))) { 2049 CCInfo.AllocateReg(AMDGPU::VGPR0); 2050 CCInfo.AllocateReg(AMDGPU::VGPR1); 2051 Info->markPSInputAllocated(0); 2052 Info->markPSInputEnabled(0); 2053 } 2054 if (Subtarget->isAmdPalOS()) { 2055 // For isAmdPalOS, the user does not enable some bits after compilation 2056 // based on run-time states; the register values being generated here are 2057 // the final ones set in hardware. Therefore we need to apply the 2058 // workaround to PSInputAddr and PSInputEnable together. (The case where 2059 // a bit is set in PSInputAddr but not PSInputEnable is where the 2060 // frontend set up an input arg for a particular interpolation mode, but 2061 // nothing uses that input arg. Really we should have an earlier pass 2062 // that removes such an arg.) 2063 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2064 if ((PsInputBits & 0x7F) == 0 || 2065 ((PsInputBits & 0xF) == 0 && 2066 (PsInputBits >> 11 & 1))) 2067 Info->markPSInputEnabled( 2068 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2069 } 2070 } 2071 2072 assert(!Info->hasDispatchPtr() && 2073 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2074 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2075 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2076 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2077 !Info->hasWorkItemIDZ()); 2078 } else if (IsKernel) { 2079 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2080 } else { 2081 Splits.append(Ins.begin(), Ins.end()); 2082 } 2083 2084 if (IsEntryFunc) { 2085 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2086 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2087 } else { 2088 // For the fixed ABI, pass workitem IDs in the last argument register. 2089 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2090 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2091 } 2092 2093 if (IsKernel) { 2094 analyzeFormalArgumentsCompute(CCInfo, Ins); 2095 } else { 2096 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2097 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2098 } 2099 2100 SmallVector<SDValue, 16> Chains; 2101 2102 // FIXME: This is the minimum kernel argument alignment. We should improve 2103 // this to the maximum alignment of the arguments. 2104 // 2105 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2106 // kern arg offset. 2107 const unsigned KernelArgBaseAlign = 16; 2108 2109 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2110 const ISD::InputArg &Arg = Ins[i]; 2111 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2112 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2113 continue; 2114 } 2115 2116 CCValAssign &VA = ArgLocs[ArgIdx++]; 2117 MVT VT = VA.getLocVT(); 2118 2119 if (IsEntryFunc && VA.isMemLoc()) { 2120 VT = Ins[i].VT; 2121 EVT MemVT = VA.getLocVT(); 2122 2123 const uint64_t Offset = VA.getLocMemOffset(); 2124 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2125 2126 SDValue Arg = lowerKernargMemParameter( 2127 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2128 Chains.push_back(Arg.getValue(1)); 2129 2130 auto *ParamTy = 2131 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2132 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2133 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2134 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2135 // On SI local pointers are just offsets into LDS, so they are always 2136 // less than 16-bits. On CI and newer they could potentially be 2137 // real pointers, so we can't guarantee their size. 2138 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2139 DAG.getValueType(MVT::i16)); 2140 } 2141 2142 InVals.push_back(Arg); 2143 continue; 2144 } else if (!IsEntryFunc && VA.isMemLoc()) { 2145 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2146 InVals.push_back(Val); 2147 if (!Arg.Flags.isByVal()) 2148 Chains.push_back(Val.getValue(1)); 2149 continue; 2150 } 2151 2152 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2153 2154 Register Reg = VA.getLocReg(); 2155 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2156 EVT ValVT = VA.getValVT(); 2157 2158 Reg = MF.addLiveIn(Reg, RC); 2159 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2160 2161 if (Arg.Flags.isSRet()) { 2162 // The return object should be reasonably addressable. 2163 2164 // FIXME: This helps when the return is a real sret. If it is a 2165 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2166 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2167 unsigned NumBits 2168 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2169 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2170 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2171 } 2172 2173 // If this is an 8 or 16-bit value, it is really passed promoted 2174 // to 32 bits. Insert an assert[sz]ext to capture this, then 2175 // truncate to the right size. 2176 switch (VA.getLocInfo()) { 2177 case CCValAssign::Full: 2178 break; 2179 case CCValAssign::BCvt: 2180 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2181 break; 2182 case CCValAssign::SExt: 2183 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2184 DAG.getValueType(ValVT)); 2185 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2186 break; 2187 case CCValAssign::ZExt: 2188 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2189 DAG.getValueType(ValVT)); 2190 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2191 break; 2192 case CCValAssign::AExt: 2193 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2194 break; 2195 default: 2196 llvm_unreachable("Unknown loc info!"); 2197 } 2198 2199 InVals.push_back(Val); 2200 } 2201 2202 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2203 // Special inputs come after user arguments. 2204 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2205 } 2206 2207 // Start adding system SGPRs. 2208 if (IsEntryFunc) { 2209 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2210 } else { 2211 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2212 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2213 } 2214 2215 auto &ArgUsageInfo = 2216 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2217 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2218 2219 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2220 Info->setBytesInStackArgArea(StackArgSize); 2221 2222 return Chains.empty() ? Chain : 2223 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2224 } 2225 2226 // TODO: If return values can't fit in registers, we should return as many as 2227 // possible in registers before passing on stack. 2228 bool SITargetLowering::CanLowerReturn( 2229 CallingConv::ID CallConv, 2230 MachineFunction &MF, bool IsVarArg, 2231 const SmallVectorImpl<ISD::OutputArg> &Outs, 2232 LLVMContext &Context) const { 2233 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2234 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2235 // for shaders. Vector types should be explicitly handled by CC. 2236 if (AMDGPU::isEntryFunctionCC(CallConv)) 2237 return true; 2238 2239 SmallVector<CCValAssign, 16> RVLocs; 2240 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2241 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2242 } 2243 2244 SDValue 2245 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2246 bool isVarArg, 2247 const SmallVectorImpl<ISD::OutputArg> &Outs, 2248 const SmallVectorImpl<SDValue> &OutVals, 2249 const SDLoc &DL, SelectionDAG &DAG) const { 2250 MachineFunction &MF = DAG.getMachineFunction(); 2251 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2252 2253 if (AMDGPU::isKernel(CallConv)) { 2254 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2255 OutVals, DL, DAG); 2256 } 2257 2258 bool IsShader = AMDGPU::isShader(CallConv); 2259 2260 Info->setIfReturnsVoid(Outs.empty()); 2261 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2262 2263 // CCValAssign - represent the assignment of the return value to a location. 2264 SmallVector<CCValAssign, 48> RVLocs; 2265 SmallVector<ISD::OutputArg, 48> Splits; 2266 2267 // CCState - Info about the registers and stack slots. 2268 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2269 *DAG.getContext()); 2270 2271 // Analyze outgoing return values. 2272 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2273 2274 SDValue Flag; 2275 SmallVector<SDValue, 48> RetOps; 2276 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2277 2278 // Add return address for callable functions. 2279 if (!Info->isEntryFunction()) { 2280 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2281 SDValue ReturnAddrReg = CreateLiveInRegister( 2282 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2283 2284 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2285 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2286 MVT::i64); 2287 Chain = 2288 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2289 Flag = Chain.getValue(1); 2290 RetOps.push_back(ReturnAddrVirtualReg); 2291 } 2292 2293 // Copy the result values into the output registers. 2294 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2295 ++I, ++RealRVLocIdx) { 2296 CCValAssign &VA = RVLocs[I]; 2297 assert(VA.isRegLoc() && "Can only return in registers!"); 2298 // TODO: Partially return in registers if return values don't fit. 2299 SDValue Arg = OutVals[RealRVLocIdx]; 2300 2301 // Copied from other backends. 2302 switch (VA.getLocInfo()) { 2303 case CCValAssign::Full: 2304 break; 2305 case CCValAssign::BCvt: 2306 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2307 break; 2308 case CCValAssign::SExt: 2309 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2310 break; 2311 case CCValAssign::ZExt: 2312 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2313 break; 2314 case CCValAssign::AExt: 2315 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2316 break; 2317 default: 2318 llvm_unreachable("Unknown loc info!"); 2319 } 2320 2321 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2322 Flag = Chain.getValue(1); 2323 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2324 } 2325 2326 // FIXME: Does sret work properly? 2327 if (!Info->isEntryFunction()) { 2328 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2329 const MCPhysReg *I = 2330 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2331 if (I) { 2332 for (; *I; ++I) { 2333 if (AMDGPU::SReg_64RegClass.contains(*I)) 2334 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2335 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2336 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2337 else 2338 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2339 } 2340 } 2341 } 2342 2343 // Update chain and glue. 2344 RetOps[0] = Chain; 2345 if (Flag.getNode()) 2346 RetOps.push_back(Flag); 2347 2348 unsigned Opc = AMDGPUISD::ENDPGM; 2349 if (!IsWaveEnd) 2350 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2351 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2352 } 2353 2354 SDValue SITargetLowering::LowerCallResult( 2355 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2356 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2357 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2358 SDValue ThisVal) const { 2359 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2360 2361 // Assign locations to each value returned by this call. 2362 SmallVector<CCValAssign, 16> RVLocs; 2363 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2364 *DAG.getContext()); 2365 CCInfo.AnalyzeCallResult(Ins, RetCC); 2366 2367 // Copy all of the result registers out of their specified physreg. 2368 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2369 CCValAssign VA = RVLocs[i]; 2370 SDValue Val; 2371 2372 if (VA.isRegLoc()) { 2373 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2374 Chain = Val.getValue(1); 2375 InFlag = Val.getValue(2); 2376 } else if (VA.isMemLoc()) { 2377 report_fatal_error("TODO: return values in memory"); 2378 } else 2379 llvm_unreachable("unknown argument location type"); 2380 2381 switch (VA.getLocInfo()) { 2382 case CCValAssign::Full: 2383 break; 2384 case CCValAssign::BCvt: 2385 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2386 break; 2387 case CCValAssign::ZExt: 2388 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2389 DAG.getValueType(VA.getValVT())); 2390 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2391 break; 2392 case CCValAssign::SExt: 2393 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2394 DAG.getValueType(VA.getValVT())); 2395 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2396 break; 2397 case CCValAssign::AExt: 2398 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2399 break; 2400 default: 2401 llvm_unreachable("Unknown loc info!"); 2402 } 2403 2404 InVals.push_back(Val); 2405 } 2406 2407 return Chain; 2408 } 2409 2410 // Add code to pass special inputs required depending on used features separate 2411 // from the explicit user arguments present in the IR. 2412 void SITargetLowering::passSpecialInputs( 2413 CallLoweringInfo &CLI, 2414 CCState &CCInfo, 2415 const SIMachineFunctionInfo &Info, 2416 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2417 SmallVectorImpl<SDValue> &MemOpChains, 2418 SDValue Chain) const { 2419 // If we don't have a call site, this was a call inserted by 2420 // legalization. These can never use special inputs. 2421 if (!CLI.CS) 2422 return; 2423 2424 SelectionDAG &DAG = CLI.DAG; 2425 const SDLoc &DL = CLI.DL; 2426 2427 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2428 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2429 2430 const AMDGPUFunctionArgInfo *CalleeArgInfo 2431 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2432 if (const Function *CalleeFunc = CLI.CS.getCalledFunction()) { 2433 auto &ArgUsageInfo = 2434 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2435 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2436 } 2437 2438 // TODO: Unify with private memory register handling. This is complicated by 2439 // the fact that at least in kernels, the input argument is not necessarily 2440 // in the same location as the input. 2441 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2442 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2443 AMDGPUFunctionArgInfo::QUEUE_PTR, 2444 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2445 AMDGPUFunctionArgInfo::DISPATCH_ID, 2446 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2447 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2448 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2449 }; 2450 2451 for (auto InputID : InputRegs) { 2452 const ArgDescriptor *OutgoingArg; 2453 const TargetRegisterClass *ArgRC; 2454 2455 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2456 if (!OutgoingArg) 2457 continue; 2458 2459 const ArgDescriptor *IncomingArg; 2460 const TargetRegisterClass *IncomingArgRC; 2461 std::tie(IncomingArg, IncomingArgRC) 2462 = CallerArgInfo.getPreloadedValue(InputID); 2463 assert(IncomingArgRC == ArgRC); 2464 2465 // All special arguments are ints for now. 2466 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2467 SDValue InputReg; 2468 2469 if (IncomingArg) { 2470 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2471 } else { 2472 // The implicit arg ptr is special because it doesn't have a corresponding 2473 // input for kernels, and is computed from the kernarg segment pointer. 2474 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2475 InputReg = getImplicitArgPtr(DAG, DL); 2476 } 2477 2478 if (OutgoingArg->isRegister()) { 2479 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2480 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2481 report_fatal_error("failed to allocate implicit input argument"); 2482 } else { 2483 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2484 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2485 SpecialArgOffset); 2486 MemOpChains.push_back(ArgStore); 2487 } 2488 } 2489 2490 // Pack workitem IDs into a single register or pass it as is if already 2491 // packed. 2492 const ArgDescriptor *OutgoingArg; 2493 const TargetRegisterClass *ArgRC; 2494 2495 std::tie(OutgoingArg, ArgRC) = 2496 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2497 if (!OutgoingArg) 2498 std::tie(OutgoingArg, ArgRC) = 2499 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2500 if (!OutgoingArg) 2501 std::tie(OutgoingArg, ArgRC) = 2502 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2503 if (!OutgoingArg) 2504 return; 2505 2506 const ArgDescriptor *IncomingArgX 2507 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2508 const ArgDescriptor *IncomingArgY 2509 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2510 const ArgDescriptor *IncomingArgZ 2511 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2512 2513 SDValue InputReg; 2514 SDLoc SL; 2515 2516 // If incoming ids are not packed we need to pack them. 2517 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2518 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2519 2520 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2521 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2522 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2523 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2524 InputReg = InputReg.getNode() ? 2525 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2526 } 2527 2528 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2529 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2530 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2531 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2532 InputReg = InputReg.getNode() ? 2533 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2534 } 2535 2536 if (!InputReg.getNode()) { 2537 // Workitem ids are already packed, any of present incoming arguments 2538 // will carry all required fields. 2539 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2540 IncomingArgX ? *IncomingArgX : 2541 IncomingArgY ? *IncomingArgY : 2542 *IncomingArgZ, ~0u); 2543 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2544 } 2545 2546 if (OutgoingArg->isRegister()) { 2547 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2548 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2549 } else { 2550 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2551 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2552 SpecialArgOffset); 2553 MemOpChains.push_back(ArgStore); 2554 } 2555 } 2556 2557 static bool canGuaranteeTCO(CallingConv::ID CC) { 2558 return CC == CallingConv::Fast; 2559 } 2560 2561 /// Return true if we might ever do TCO for calls with this calling convention. 2562 static bool mayTailCallThisCC(CallingConv::ID CC) { 2563 switch (CC) { 2564 case CallingConv::C: 2565 return true; 2566 default: 2567 return canGuaranteeTCO(CC); 2568 } 2569 } 2570 2571 bool SITargetLowering::isEligibleForTailCallOptimization( 2572 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2573 const SmallVectorImpl<ISD::OutputArg> &Outs, 2574 const SmallVectorImpl<SDValue> &OutVals, 2575 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2576 if (!mayTailCallThisCC(CalleeCC)) 2577 return false; 2578 2579 MachineFunction &MF = DAG.getMachineFunction(); 2580 const Function &CallerF = MF.getFunction(); 2581 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2582 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2583 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2584 2585 // Kernels aren't callable, and don't have a live in return address so it 2586 // doesn't make sense to do a tail call with entry functions. 2587 if (!CallerPreserved) 2588 return false; 2589 2590 bool CCMatch = CallerCC == CalleeCC; 2591 2592 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2593 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2594 return true; 2595 return false; 2596 } 2597 2598 // TODO: Can we handle var args? 2599 if (IsVarArg) 2600 return false; 2601 2602 for (const Argument &Arg : CallerF.args()) { 2603 if (Arg.hasByValAttr()) 2604 return false; 2605 } 2606 2607 LLVMContext &Ctx = *DAG.getContext(); 2608 2609 // Check that the call results are passed in the same way. 2610 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2611 CCAssignFnForCall(CalleeCC, IsVarArg), 2612 CCAssignFnForCall(CallerCC, IsVarArg))) 2613 return false; 2614 2615 // The callee has to preserve all registers the caller needs to preserve. 2616 if (!CCMatch) { 2617 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2618 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2619 return false; 2620 } 2621 2622 // Nothing more to check if the callee is taking no arguments. 2623 if (Outs.empty()) 2624 return true; 2625 2626 SmallVector<CCValAssign, 16> ArgLocs; 2627 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2628 2629 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2630 2631 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2632 // If the stack arguments for this call do not fit into our own save area then 2633 // the call cannot be made tail. 2634 // TODO: Is this really necessary? 2635 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2636 return false; 2637 2638 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2639 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2640 } 2641 2642 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2643 if (!CI->isTailCall()) 2644 return false; 2645 2646 const Function *ParentFn = CI->getParent()->getParent(); 2647 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2648 return false; 2649 return true; 2650 } 2651 2652 // The wave scratch offset register is used as the global base pointer. 2653 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2654 SmallVectorImpl<SDValue> &InVals) const { 2655 SelectionDAG &DAG = CLI.DAG; 2656 const SDLoc &DL = CLI.DL; 2657 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2658 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2659 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2660 SDValue Chain = CLI.Chain; 2661 SDValue Callee = CLI.Callee; 2662 bool &IsTailCall = CLI.IsTailCall; 2663 CallingConv::ID CallConv = CLI.CallConv; 2664 bool IsVarArg = CLI.IsVarArg; 2665 bool IsSibCall = false; 2666 bool IsThisReturn = false; 2667 MachineFunction &MF = DAG.getMachineFunction(); 2668 2669 if (Callee.isUndef() || isNullConstant(Callee)) { 2670 if (!CLI.IsTailCall) { 2671 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2672 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2673 } 2674 2675 return Chain; 2676 } 2677 2678 if (IsVarArg) { 2679 return lowerUnhandledCall(CLI, InVals, 2680 "unsupported call to variadic function "); 2681 } 2682 2683 if (!CLI.CS.getInstruction()) 2684 report_fatal_error("unsupported libcall legalization"); 2685 2686 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && !CLI.CS.getCalledFunction()) { 2687 return lowerUnhandledCall(CLI, InVals, 2688 "unsupported indirect call to function "); 2689 } 2690 2691 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2692 return lowerUnhandledCall(CLI, InVals, 2693 "unsupported required tail call to function "); 2694 } 2695 2696 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2697 // Note the issue is with the CC of the calling function, not of the call 2698 // itself. 2699 return lowerUnhandledCall(CLI, InVals, 2700 "unsupported call from graphics shader of function "); 2701 } 2702 2703 if (IsTailCall) { 2704 IsTailCall = isEligibleForTailCallOptimization( 2705 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2706 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2707 report_fatal_error("failed to perform tail call elimination on a call " 2708 "site marked musttail"); 2709 } 2710 2711 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2712 2713 // A sibling call is one where we're under the usual C ABI and not planning 2714 // to change that but can still do a tail call: 2715 if (!TailCallOpt && IsTailCall) 2716 IsSibCall = true; 2717 2718 if (IsTailCall) 2719 ++NumTailCalls; 2720 } 2721 2722 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2723 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2724 SmallVector<SDValue, 8> MemOpChains; 2725 2726 // Analyze operands of the call, assigning locations to each operand. 2727 SmallVector<CCValAssign, 16> ArgLocs; 2728 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2729 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2730 2731 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2732 // With a fixed ABI, allocate fixed registers before user arguments. 2733 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2734 } 2735 2736 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2737 2738 // Get a count of how many bytes are to be pushed on the stack. 2739 unsigned NumBytes = CCInfo.getNextStackOffset(); 2740 2741 if (IsSibCall) { 2742 // Since we're not changing the ABI to make this a tail call, the memory 2743 // operands are already available in the caller's incoming argument space. 2744 NumBytes = 0; 2745 } 2746 2747 // FPDiff is the byte offset of the call's argument area from the callee's. 2748 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2749 // by this amount for a tail call. In a sibling call it must be 0 because the 2750 // caller will deallocate the entire stack and the callee still expects its 2751 // arguments to begin at SP+0. Completely unused for non-tail calls. 2752 int32_t FPDiff = 0; 2753 MachineFrameInfo &MFI = MF.getFrameInfo(); 2754 2755 // Adjust the stack pointer for the new arguments... 2756 // These operations are automatically eliminated by the prolog/epilog pass 2757 if (!IsSibCall) { 2758 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2759 2760 SmallVector<SDValue, 4> CopyFromChains; 2761 2762 // In the HSA case, this should be an identity copy. 2763 SDValue ScratchRSrcReg 2764 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2765 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2766 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2767 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2768 } 2769 2770 MVT PtrVT = MVT::i32; 2771 2772 // Walk the register/memloc assignments, inserting copies/loads. 2773 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2774 CCValAssign &VA = ArgLocs[i]; 2775 SDValue Arg = OutVals[i]; 2776 2777 // Promote the value if needed. 2778 switch (VA.getLocInfo()) { 2779 case CCValAssign::Full: 2780 break; 2781 case CCValAssign::BCvt: 2782 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2783 break; 2784 case CCValAssign::ZExt: 2785 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2786 break; 2787 case CCValAssign::SExt: 2788 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2789 break; 2790 case CCValAssign::AExt: 2791 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2792 break; 2793 case CCValAssign::FPExt: 2794 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2795 break; 2796 default: 2797 llvm_unreachable("Unknown loc info!"); 2798 } 2799 2800 if (VA.isRegLoc()) { 2801 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2802 } else { 2803 assert(VA.isMemLoc()); 2804 2805 SDValue DstAddr; 2806 MachinePointerInfo DstInfo; 2807 2808 unsigned LocMemOffset = VA.getLocMemOffset(); 2809 int32_t Offset = LocMemOffset; 2810 2811 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2812 MaybeAlign Alignment; 2813 2814 if (IsTailCall) { 2815 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2816 unsigned OpSize = Flags.isByVal() ? 2817 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2818 2819 // FIXME: We can have better than the minimum byval required alignment. 2820 Alignment = 2821 Flags.isByVal() 2822 ? Flags.getNonZeroByValAlign() 2823 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2824 2825 Offset = Offset + FPDiff; 2826 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2827 2828 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2829 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2830 2831 // Make sure any stack arguments overlapping with where we're storing 2832 // are loaded before this eventual operation. Otherwise they'll be 2833 // clobbered. 2834 2835 // FIXME: Why is this really necessary? This seems to just result in a 2836 // lot of code to copy the stack and write them back to the same 2837 // locations, which are supposed to be immutable? 2838 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2839 } else { 2840 DstAddr = PtrOff; 2841 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2842 Alignment = 2843 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2844 } 2845 2846 if (Outs[i].Flags.isByVal()) { 2847 SDValue SizeNode = 2848 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2849 SDValue Cpy = 2850 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2851 Outs[i].Flags.getNonZeroByValAlign(), 2852 /*isVol = */ false, /*AlwaysInline = */ true, 2853 /*isTailCall = */ false, DstInfo, 2854 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2855 2856 MemOpChains.push_back(Cpy); 2857 } else { 2858 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2859 Alignment ? Alignment->value() : 0); 2860 MemOpChains.push_back(Store); 2861 } 2862 } 2863 } 2864 2865 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2866 // Copy special input registers after user input arguments. 2867 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2868 } 2869 2870 if (!MemOpChains.empty()) 2871 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2872 2873 // Build a sequence of copy-to-reg nodes chained together with token chain 2874 // and flag operands which copy the outgoing args into the appropriate regs. 2875 SDValue InFlag; 2876 for (auto &RegToPass : RegsToPass) { 2877 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2878 RegToPass.second, InFlag); 2879 InFlag = Chain.getValue(1); 2880 } 2881 2882 2883 SDValue PhysReturnAddrReg; 2884 if (IsTailCall) { 2885 // Since the return is being combined with the call, we need to pass on the 2886 // return address. 2887 2888 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2889 SDValue ReturnAddrReg = CreateLiveInRegister( 2890 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2891 2892 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2893 MVT::i64); 2894 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2895 InFlag = Chain.getValue(1); 2896 } 2897 2898 // We don't usually want to end the call-sequence here because we would tidy 2899 // the frame up *after* the call, however in the ABI-changing tail-call case 2900 // we've carefully laid out the parameters so that when sp is reset they'll be 2901 // in the correct location. 2902 if (IsTailCall && !IsSibCall) { 2903 Chain = DAG.getCALLSEQ_END(Chain, 2904 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2905 DAG.getTargetConstant(0, DL, MVT::i32), 2906 InFlag, DL); 2907 InFlag = Chain.getValue(1); 2908 } 2909 2910 std::vector<SDValue> Ops; 2911 Ops.push_back(Chain); 2912 Ops.push_back(Callee); 2913 // Add a redundant copy of the callee global which will not be legalized, as 2914 // we need direct access to the callee later. 2915 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 2916 const GlobalValue *GV = GSD->getGlobal(); 2917 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2918 } else { 2919 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 2920 } 2921 2922 if (IsTailCall) { 2923 // Each tail call may have to adjust the stack by a different amount, so 2924 // this information must travel along with the operation for eventual 2925 // consumption by emitEpilogue. 2926 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2927 2928 Ops.push_back(PhysReturnAddrReg); 2929 } 2930 2931 // Add argument registers to the end of the list so that they are known live 2932 // into the call. 2933 for (auto &RegToPass : RegsToPass) { 2934 Ops.push_back(DAG.getRegister(RegToPass.first, 2935 RegToPass.second.getValueType())); 2936 } 2937 2938 // Add a register mask operand representing the call-preserved registers. 2939 2940 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2941 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2942 assert(Mask && "Missing call preserved mask for calling convention"); 2943 Ops.push_back(DAG.getRegisterMask(Mask)); 2944 2945 if (InFlag.getNode()) 2946 Ops.push_back(InFlag); 2947 2948 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2949 2950 // If we're doing a tall call, use a TC_RETURN here rather than an 2951 // actual call instruction. 2952 if (IsTailCall) { 2953 MFI.setHasTailCall(); 2954 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2955 } 2956 2957 // Returns a chain and a flag for retval copy to use. 2958 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2959 Chain = Call.getValue(0); 2960 InFlag = Call.getValue(1); 2961 2962 uint64_t CalleePopBytes = NumBytes; 2963 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2964 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2965 InFlag, DL); 2966 if (!Ins.empty()) 2967 InFlag = Chain.getValue(1); 2968 2969 // Handle result values, copying them out of physregs into vregs that we 2970 // return. 2971 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2972 InVals, IsThisReturn, 2973 IsThisReturn ? OutVals[0] : SDValue()); 2974 } 2975 2976 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 2977 const MachineFunction &MF) const { 2978 Register Reg = StringSwitch<Register>(RegName) 2979 .Case("m0", AMDGPU::M0) 2980 .Case("exec", AMDGPU::EXEC) 2981 .Case("exec_lo", AMDGPU::EXEC_LO) 2982 .Case("exec_hi", AMDGPU::EXEC_HI) 2983 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2984 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2985 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2986 .Default(Register()); 2987 2988 if (Reg == AMDGPU::NoRegister) { 2989 report_fatal_error(Twine("invalid register name \"" 2990 + StringRef(RegName) + "\".")); 2991 2992 } 2993 2994 if (!Subtarget->hasFlatScrRegister() && 2995 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2996 report_fatal_error(Twine("invalid register \"" 2997 + StringRef(RegName) + "\" for subtarget.")); 2998 } 2999 3000 switch (Reg) { 3001 case AMDGPU::M0: 3002 case AMDGPU::EXEC_LO: 3003 case AMDGPU::EXEC_HI: 3004 case AMDGPU::FLAT_SCR_LO: 3005 case AMDGPU::FLAT_SCR_HI: 3006 if (VT.getSizeInBits() == 32) 3007 return Reg; 3008 break; 3009 case AMDGPU::EXEC: 3010 case AMDGPU::FLAT_SCR: 3011 if (VT.getSizeInBits() == 64) 3012 return Reg; 3013 break; 3014 default: 3015 llvm_unreachable("missing register type checking"); 3016 } 3017 3018 report_fatal_error(Twine("invalid type for register \"" 3019 + StringRef(RegName) + "\".")); 3020 } 3021 3022 // If kill is not the last instruction, split the block so kill is always a 3023 // proper terminator. 3024 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3025 MachineBasicBlock *BB) const { 3026 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3027 3028 MachineBasicBlock::iterator SplitPoint(&MI); 3029 ++SplitPoint; 3030 3031 if (SplitPoint == BB->end()) { 3032 // Don't bother with a new block. 3033 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3034 return BB; 3035 } 3036 3037 MachineFunction *MF = BB->getParent(); 3038 MachineBasicBlock *SplitBB 3039 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3040 3041 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3042 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3043 3044 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3045 BB->addSuccessor(SplitBB); 3046 3047 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3048 return SplitBB; 3049 } 3050 3051 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3052 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3053 // be the first instruction in the remainder block. 3054 // 3055 /// \returns { LoopBody, Remainder } 3056 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3057 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3058 MachineFunction *MF = MBB.getParent(); 3059 MachineBasicBlock::iterator I(&MI); 3060 3061 // To insert the loop we need to split the block. Move everything after this 3062 // point to a new block, and insert a new empty block between the two. 3063 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3064 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3065 MachineFunction::iterator MBBI(MBB); 3066 ++MBBI; 3067 3068 MF->insert(MBBI, LoopBB); 3069 MF->insert(MBBI, RemainderBB); 3070 3071 LoopBB->addSuccessor(LoopBB); 3072 LoopBB->addSuccessor(RemainderBB); 3073 3074 // Move the rest of the block into a new block. 3075 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3076 3077 if (InstInLoop) { 3078 auto Next = std::next(I); 3079 3080 // Move instruction to loop body. 3081 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3082 3083 // Move the rest of the block. 3084 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3085 } else { 3086 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3087 } 3088 3089 MBB.addSuccessor(LoopBB); 3090 3091 return std::make_pair(LoopBB, RemainderBB); 3092 } 3093 3094 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3095 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3096 MachineBasicBlock *MBB = MI.getParent(); 3097 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3098 auto I = MI.getIterator(); 3099 auto E = std::next(I); 3100 3101 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3102 .addImm(0); 3103 3104 MIBundleBuilder Bundler(*MBB, I, E); 3105 finalizeBundle(*MBB, Bundler.begin()); 3106 } 3107 3108 MachineBasicBlock * 3109 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3110 MachineBasicBlock *BB) const { 3111 const DebugLoc &DL = MI.getDebugLoc(); 3112 3113 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3114 3115 MachineBasicBlock *LoopBB; 3116 MachineBasicBlock *RemainderBB; 3117 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3118 3119 // Apparently kill flags are only valid if the def is in the same block? 3120 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3121 Src->setIsKill(false); 3122 3123 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3124 3125 MachineBasicBlock::iterator I = LoopBB->end(); 3126 3127 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3128 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3129 3130 // Clear TRAP_STS.MEM_VIOL 3131 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3132 .addImm(0) 3133 .addImm(EncodedReg); 3134 3135 bundleInstWithWaitcnt(MI); 3136 3137 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3138 3139 // Load and check TRAP_STS.MEM_VIOL 3140 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3141 .addImm(EncodedReg); 3142 3143 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3144 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3145 .addReg(Reg, RegState::Kill) 3146 .addImm(0); 3147 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3148 .addMBB(LoopBB); 3149 3150 return RemainderBB; 3151 } 3152 3153 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3154 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3155 // will only do one iteration. In the worst case, this will loop 64 times. 3156 // 3157 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3158 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3159 const SIInstrInfo *TII, 3160 MachineRegisterInfo &MRI, 3161 MachineBasicBlock &OrigBB, 3162 MachineBasicBlock &LoopBB, 3163 const DebugLoc &DL, 3164 const MachineOperand &IdxReg, 3165 unsigned InitReg, 3166 unsigned ResultReg, 3167 unsigned PhiReg, 3168 unsigned InitSaveExecReg, 3169 int Offset, 3170 bool UseGPRIdxMode, 3171 bool IsIndirectSrc) { 3172 MachineFunction *MF = OrigBB.getParent(); 3173 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3174 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3175 MachineBasicBlock::iterator I = LoopBB.begin(); 3176 3177 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3178 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3179 Register NewExec = MRI.createVirtualRegister(BoolRC); 3180 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3181 Register CondReg = MRI.createVirtualRegister(BoolRC); 3182 3183 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3184 .addReg(InitReg) 3185 .addMBB(&OrigBB) 3186 .addReg(ResultReg) 3187 .addMBB(&LoopBB); 3188 3189 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3190 .addReg(InitSaveExecReg) 3191 .addMBB(&OrigBB) 3192 .addReg(NewExec) 3193 .addMBB(&LoopBB); 3194 3195 // Read the next variant <- also loop target. 3196 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3197 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3198 3199 // Compare the just read M0 value to all possible Idx values. 3200 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3201 .addReg(CurrentIdxReg) 3202 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3203 3204 // Update EXEC, save the original EXEC value to VCC. 3205 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3206 : AMDGPU::S_AND_SAVEEXEC_B64), 3207 NewExec) 3208 .addReg(CondReg, RegState::Kill); 3209 3210 MRI.setSimpleHint(NewExec, CondReg); 3211 3212 if (UseGPRIdxMode) { 3213 unsigned IdxReg; 3214 if (Offset == 0) { 3215 IdxReg = CurrentIdxReg; 3216 } else { 3217 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3218 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3219 .addReg(CurrentIdxReg, RegState::Kill) 3220 .addImm(Offset); 3221 } 3222 unsigned IdxMode = IsIndirectSrc ? 3223 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3224 MachineInstr *SetOn = 3225 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3226 .addReg(IdxReg, RegState::Kill) 3227 .addImm(IdxMode); 3228 SetOn->getOperand(3).setIsUndef(); 3229 } else { 3230 // Move index from VCC into M0 3231 if (Offset == 0) { 3232 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3233 .addReg(CurrentIdxReg, RegState::Kill); 3234 } else { 3235 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3236 .addReg(CurrentIdxReg, RegState::Kill) 3237 .addImm(Offset); 3238 } 3239 } 3240 3241 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3242 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3243 MachineInstr *InsertPt = 3244 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3245 : AMDGPU::S_XOR_B64_term), Exec) 3246 .addReg(Exec) 3247 .addReg(NewExec); 3248 3249 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3250 // s_cbranch_scc0? 3251 3252 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3253 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3254 .addMBB(&LoopBB); 3255 3256 return InsertPt->getIterator(); 3257 } 3258 3259 // This has slightly sub-optimal regalloc when the source vector is killed by 3260 // the read. The register allocator does not understand that the kill is 3261 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3262 // subregister from it, using 1 more VGPR than necessary. This was saved when 3263 // this was expanded after register allocation. 3264 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3265 MachineBasicBlock &MBB, 3266 MachineInstr &MI, 3267 unsigned InitResultReg, 3268 unsigned PhiReg, 3269 int Offset, 3270 bool UseGPRIdxMode, 3271 bool IsIndirectSrc) { 3272 MachineFunction *MF = MBB.getParent(); 3273 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3274 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3275 MachineRegisterInfo &MRI = MF->getRegInfo(); 3276 const DebugLoc &DL = MI.getDebugLoc(); 3277 MachineBasicBlock::iterator I(&MI); 3278 3279 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3280 Register DstReg = MI.getOperand(0).getReg(); 3281 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3282 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3283 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3284 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3285 3286 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3287 3288 // Save the EXEC mask 3289 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3290 .addReg(Exec); 3291 3292 MachineBasicBlock *LoopBB; 3293 MachineBasicBlock *RemainderBB; 3294 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3295 3296 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3297 3298 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3299 InitResultReg, DstReg, PhiReg, TmpExec, 3300 Offset, UseGPRIdxMode, IsIndirectSrc); 3301 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3302 MachineFunction::iterator MBBI(LoopBB); 3303 ++MBBI; 3304 MF->insert(MBBI, LandingPad); 3305 LoopBB->removeSuccessor(RemainderBB); 3306 LandingPad->addSuccessor(RemainderBB); 3307 LoopBB->addSuccessor(LandingPad); 3308 MachineBasicBlock::iterator First = LandingPad->begin(); 3309 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3310 .addReg(SaveExec); 3311 3312 return InsPt; 3313 } 3314 3315 // Returns subreg index, offset 3316 static std::pair<unsigned, int> 3317 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3318 const TargetRegisterClass *SuperRC, 3319 unsigned VecReg, 3320 int Offset) { 3321 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3322 3323 // Skip out of bounds offsets, or else we would end up using an undefined 3324 // register. 3325 if (Offset >= NumElts || Offset < 0) 3326 return std::make_pair(AMDGPU::sub0, Offset); 3327 3328 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3329 } 3330 3331 // Return true if the index is an SGPR and was set. 3332 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3333 MachineRegisterInfo &MRI, 3334 MachineInstr &MI, 3335 int Offset, 3336 bool UseGPRIdxMode, 3337 bool IsIndirectSrc) { 3338 MachineBasicBlock *MBB = MI.getParent(); 3339 const DebugLoc &DL = MI.getDebugLoc(); 3340 MachineBasicBlock::iterator I(&MI); 3341 3342 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3343 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3344 3345 assert(Idx->getReg() != AMDGPU::NoRegister); 3346 3347 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3348 return false; 3349 3350 if (UseGPRIdxMode) { 3351 unsigned IdxMode = IsIndirectSrc ? 3352 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3353 if (Offset == 0) { 3354 MachineInstr *SetOn = 3355 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3356 .add(*Idx) 3357 .addImm(IdxMode); 3358 3359 SetOn->getOperand(3).setIsUndef(); 3360 } else { 3361 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3362 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3363 .add(*Idx) 3364 .addImm(Offset); 3365 MachineInstr *SetOn = 3366 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3367 .addReg(Tmp, RegState::Kill) 3368 .addImm(IdxMode); 3369 3370 SetOn->getOperand(3).setIsUndef(); 3371 } 3372 3373 return true; 3374 } 3375 3376 if (Offset == 0) { 3377 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3378 .add(*Idx); 3379 } else { 3380 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3381 .add(*Idx) 3382 .addImm(Offset); 3383 } 3384 3385 return true; 3386 } 3387 3388 // Control flow needs to be inserted if indexing with a VGPR. 3389 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3390 MachineBasicBlock &MBB, 3391 const GCNSubtarget &ST) { 3392 const SIInstrInfo *TII = ST.getInstrInfo(); 3393 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3394 MachineFunction *MF = MBB.getParent(); 3395 MachineRegisterInfo &MRI = MF->getRegInfo(); 3396 3397 Register Dst = MI.getOperand(0).getReg(); 3398 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3399 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3400 3401 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3402 3403 unsigned SubReg; 3404 std::tie(SubReg, Offset) 3405 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3406 3407 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3408 3409 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3410 MachineBasicBlock::iterator I(&MI); 3411 const DebugLoc &DL = MI.getDebugLoc(); 3412 3413 if (UseGPRIdxMode) { 3414 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3415 // to avoid interfering with other uses, so probably requires a new 3416 // optimization pass. 3417 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3418 .addReg(SrcReg, RegState::Undef, SubReg) 3419 .addReg(SrcReg, RegState::Implicit) 3420 .addReg(AMDGPU::M0, RegState::Implicit); 3421 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3422 } else { 3423 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3424 .addReg(SrcReg, RegState::Undef, SubReg) 3425 .addReg(SrcReg, RegState::Implicit); 3426 } 3427 3428 MI.eraseFromParent(); 3429 3430 return &MBB; 3431 } 3432 3433 const DebugLoc &DL = MI.getDebugLoc(); 3434 MachineBasicBlock::iterator I(&MI); 3435 3436 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3437 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3438 3439 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3440 3441 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3442 Offset, UseGPRIdxMode, true); 3443 MachineBasicBlock *LoopBB = InsPt->getParent(); 3444 3445 if (UseGPRIdxMode) { 3446 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3447 .addReg(SrcReg, RegState::Undef, SubReg) 3448 .addReg(SrcReg, RegState::Implicit) 3449 .addReg(AMDGPU::M0, RegState::Implicit); 3450 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3451 } else { 3452 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3453 .addReg(SrcReg, RegState::Undef, SubReg) 3454 .addReg(SrcReg, RegState::Implicit); 3455 } 3456 3457 MI.eraseFromParent(); 3458 3459 return LoopBB; 3460 } 3461 3462 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3463 MachineBasicBlock &MBB, 3464 const GCNSubtarget &ST) { 3465 const SIInstrInfo *TII = ST.getInstrInfo(); 3466 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3467 MachineFunction *MF = MBB.getParent(); 3468 MachineRegisterInfo &MRI = MF->getRegInfo(); 3469 3470 Register Dst = MI.getOperand(0).getReg(); 3471 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3472 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3473 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3474 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3475 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3476 3477 // This can be an immediate, but will be folded later. 3478 assert(Val->getReg()); 3479 3480 unsigned SubReg; 3481 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3482 SrcVec->getReg(), 3483 Offset); 3484 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3485 3486 if (Idx->getReg() == AMDGPU::NoRegister) { 3487 MachineBasicBlock::iterator I(&MI); 3488 const DebugLoc &DL = MI.getDebugLoc(); 3489 3490 assert(Offset == 0); 3491 3492 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3493 .add(*SrcVec) 3494 .add(*Val) 3495 .addImm(SubReg); 3496 3497 MI.eraseFromParent(); 3498 return &MBB; 3499 } 3500 3501 const MCInstrDesc &MovRelDesc 3502 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3503 3504 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3505 MachineBasicBlock::iterator I(&MI); 3506 const DebugLoc &DL = MI.getDebugLoc(); 3507 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3508 .addReg(SrcVec->getReg()) 3509 .add(*Val) 3510 .addImm(SubReg); 3511 if (UseGPRIdxMode) 3512 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3513 3514 MI.eraseFromParent(); 3515 return &MBB; 3516 } 3517 3518 if (Val->isReg()) 3519 MRI.clearKillFlags(Val->getReg()); 3520 3521 const DebugLoc &DL = MI.getDebugLoc(); 3522 3523 Register PhiReg = MRI.createVirtualRegister(VecRC); 3524 3525 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3526 Offset, UseGPRIdxMode, false); 3527 MachineBasicBlock *LoopBB = InsPt->getParent(); 3528 3529 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3530 .addReg(PhiReg) 3531 .add(*Val) 3532 .addImm(AMDGPU::sub0); 3533 if (UseGPRIdxMode) 3534 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3535 3536 MI.eraseFromParent(); 3537 return LoopBB; 3538 } 3539 3540 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3541 MachineInstr &MI, MachineBasicBlock *BB) const { 3542 3543 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3544 MachineFunction *MF = BB->getParent(); 3545 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3546 3547 if (TII->isMIMG(MI)) { 3548 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3549 report_fatal_error("missing mem operand from MIMG instruction"); 3550 } 3551 // Add a memoperand for mimg instructions so that they aren't assumed to 3552 // be ordered memory instuctions. 3553 3554 return BB; 3555 } 3556 3557 switch (MI.getOpcode()) { 3558 case AMDGPU::S_ADD_U64_PSEUDO: 3559 case AMDGPU::S_SUB_U64_PSEUDO: { 3560 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3561 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3562 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3563 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3564 const DebugLoc &DL = MI.getDebugLoc(); 3565 3566 MachineOperand &Dest = MI.getOperand(0); 3567 MachineOperand &Src0 = MI.getOperand(1); 3568 MachineOperand &Src1 = MI.getOperand(2); 3569 3570 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3571 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3572 3573 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3574 Src0, BoolRC, AMDGPU::sub0, 3575 &AMDGPU::SReg_32RegClass); 3576 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3577 Src0, BoolRC, AMDGPU::sub1, 3578 &AMDGPU::SReg_32RegClass); 3579 3580 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3581 Src1, BoolRC, AMDGPU::sub0, 3582 &AMDGPU::SReg_32RegClass); 3583 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3584 Src1, BoolRC, AMDGPU::sub1, 3585 &AMDGPU::SReg_32RegClass); 3586 3587 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3588 3589 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3590 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3591 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3592 .add(Src0Sub0) 3593 .add(Src1Sub0); 3594 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3595 .add(Src0Sub1) 3596 .add(Src1Sub1); 3597 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3598 .addReg(DestSub0) 3599 .addImm(AMDGPU::sub0) 3600 .addReg(DestSub1) 3601 .addImm(AMDGPU::sub1); 3602 MI.eraseFromParent(); 3603 return BB; 3604 } 3605 case AMDGPU::SI_INIT_M0: { 3606 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3607 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3608 .add(MI.getOperand(0)); 3609 MI.eraseFromParent(); 3610 return BB; 3611 } 3612 case AMDGPU::SI_INIT_EXEC: 3613 // This should be before all vector instructions. 3614 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3615 AMDGPU::EXEC) 3616 .addImm(MI.getOperand(0).getImm()); 3617 MI.eraseFromParent(); 3618 return BB; 3619 3620 case AMDGPU::SI_INIT_EXEC_LO: 3621 // This should be before all vector instructions. 3622 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3623 AMDGPU::EXEC_LO) 3624 .addImm(MI.getOperand(0).getImm()); 3625 MI.eraseFromParent(); 3626 return BB; 3627 3628 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3629 // Extract the thread count from an SGPR input and set EXEC accordingly. 3630 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3631 // 3632 // S_BFE_U32 count, input, {shift, 7} 3633 // S_BFM_B64 exec, count, 0 3634 // S_CMP_EQ_U32 count, 64 3635 // S_CMOV_B64 exec, -1 3636 MachineInstr *FirstMI = &*BB->begin(); 3637 MachineRegisterInfo &MRI = MF->getRegInfo(); 3638 Register InputReg = MI.getOperand(0).getReg(); 3639 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3640 bool Found = false; 3641 3642 // Move the COPY of the input reg to the beginning, so that we can use it. 3643 for (auto I = BB->begin(); I != &MI; I++) { 3644 if (I->getOpcode() != TargetOpcode::COPY || 3645 I->getOperand(0).getReg() != InputReg) 3646 continue; 3647 3648 if (I == FirstMI) { 3649 FirstMI = &*++BB->begin(); 3650 } else { 3651 I->removeFromParent(); 3652 BB->insert(FirstMI, &*I); 3653 } 3654 Found = true; 3655 break; 3656 } 3657 assert(Found); 3658 (void)Found; 3659 3660 // This should be before all vector instructions. 3661 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3662 bool isWave32 = getSubtarget()->isWave32(); 3663 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3664 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3665 .addReg(InputReg) 3666 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3667 BuildMI(*BB, FirstMI, DebugLoc(), 3668 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3669 Exec) 3670 .addReg(CountReg) 3671 .addImm(0); 3672 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3673 .addReg(CountReg, RegState::Kill) 3674 .addImm(getSubtarget()->getWavefrontSize()); 3675 BuildMI(*BB, FirstMI, DebugLoc(), 3676 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3677 Exec) 3678 .addImm(-1); 3679 MI.eraseFromParent(); 3680 return BB; 3681 } 3682 3683 case AMDGPU::GET_GROUPSTATICSIZE: { 3684 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3685 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3686 DebugLoc DL = MI.getDebugLoc(); 3687 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3688 .add(MI.getOperand(0)) 3689 .addImm(MFI->getLDSSize()); 3690 MI.eraseFromParent(); 3691 return BB; 3692 } 3693 case AMDGPU::SI_INDIRECT_SRC_V1: 3694 case AMDGPU::SI_INDIRECT_SRC_V2: 3695 case AMDGPU::SI_INDIRECT_SRC_V4: 3696 case AMDGPU::SI_INDIRECT_SRC_V8: 3697 case AMDGPU::SI_INDIRECT_SRC_V16: 3698 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3699 case AMDGPU::SI_INDIRECT_DST_V1: 3700 case AMDGPU::SI_INDIRECT_DST_V2: 3701 case AMDGPU::SI_INDIRECT_DST_V4: 3702 case AMDGPU::SI_INDIRECT_DST_V8: 3703 case AMDGPU::SI_INDIRECT_DST_V16: 3704 return emitIndirectDst(MI, *BB, *getSubtarget()); 3705 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3706 case AMDGPU::SI_KILL_I1_PSEUDO: 3707 return splitKillBlock(MI, BB); 3708 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3709 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3710 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3711 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3712 3713 Register Dst = MI.getOperand(0).getReg(); 3714 Register Src0 = MI.getOperand(1).getReg(); 3715 Register Src1 = MI.getOperand(2).getReg(); 3716 const DebugLoc &DL = MI.getDebugLoc(); 3717 Register SrcCond = MI.getOperand(3).getReg(); 3718 3719 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3720 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3721 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3722 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3723 3724 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3725 .addReg(SrcCond); 3726 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3727 .addImm(0) 3728 .addReg(Src0, 0, AMDGPU::sub0) 3729 .addImm(0) 3730 .addReg(Src1, 0, AMDGPU::sub0) 3731 .addReg(SrcCondCopy); 3732 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3733 .addImm(0) 3734 .addReg(Src0, 0, AMDGPU::sub1) 3735 .addImm(0) 3736 .addReg(Src1, 0, AMDGPU::sub1) 3737 .addReg(SrcCondCopy); 3738 3739 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3740 .addReg(DstLo) 3741 .addImm(AMDGPU::sub0) 3742 .addReg(DstHi) 3743 .addImm(AMDGPU::sub1); 3744 MI.eraseFromParent(); 3745 return BB; 3746 } 3747 case AMDGPU::SI_BR_UNDEF: { 3748 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3749 const DebugLoc &DL = MI.getDebugLoc(); 3750 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3751 .add(MI.getOperand(0)); 3752 Br->getOperand(1).setIsUndef(true); // read undef SCC 3753 MI.eraseFromParent(); 3754 return BB; 3755 } 3756 case AMDGPU::ADJCALLSTACKUP: 3757 case AMDGPU::ADJCALLSTACKDOWN: { 3758 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3759 MachineInstrBuilder MIB(*MF, &MI); 3760 3761 // Add an implicit use of the frame offset reg to prevent the restore copy 3762 // inserted after the call from being reorderd after stack operations in the 3763 // the caller's frame. 3764 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3765 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3766 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3767 return BB; 3768 } 3769 case AMDGPU::SI_CALL_ISEL: { 3770 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3771 const DebugLoc &DL = MI.getDebugLoc(); 3772 3773 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3774 3775 MachineInstrBuilder MIB; 3776 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3777 3778 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3779 MIB.add(MI.getOperand(I)); 3780 3781 MIB.cloneMemRefs(MI); 3782 MI.eraseFromParent(); 3783 return BB; 3784 } 3785 case AMDGPU::V_ADD_I32_e32: 3786 case AMDGPU::V_SUB_I32_e32: 3787 case AMDGPU::V_SUBREV_I32_e32: { 3788 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3789 const DebugLoc &DL = MI.getDebugLoc(); 3790 unsigned Opc = MI.getOpcode(); 3791 3792 bool NeedClampOperand = false; 3793 if (TII->pseudoToMCOpcode(Opc) == -1) { 3794 Opc = AMDGPU::getVOPe64(Opc); 3795 NeedClampOperand = true; 3796 } 3797 3798 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3799 if (TII->isVOP3(*I)) { 3800 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3801 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3802 I.addReg(TRI->getVCC(), RegState::Define); 3803 } 3804 I.add(MI.getOperand(1)) 3805 .add(MI.getOperand(2)); 3806 if (NeedClampOperand) 3807 I.addImm(0); // clamp bit for e64 encoding 3808 3809 TII->legalizeOperands(*I); 3810 3811 MI.eraseFromParent(); 3812 return BB; 3813 } 3814 case AMDGPU::DS_GWS_INIT: 3815 case AMDGPU::DS_GWS_SEMA_V: 3816 case AMDGPU::DS_GWS_SEMA_BR: 3817 case AMDGPU::DS_GWS_SEMA_P: 3818 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3819 case AMDGPU::DS_GWS_BARRIER: 3820 // A s_waitcnt 0 is required to be the instruction immediately following. 3821 if (getSubtarget()->hasGWSAutoReplay()) { 3822 bundleInstWithWaitcnt(MI); 3823 return BB; 3824 } 3825 3826 return emitGWSMemViolTestLoop(MI, BB); 3827 default: 3828 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3829 } 3830 } 3831 3832 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3833 return isTypeLegal(VT.getScalarType()); 3834 } 3835 3836 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3837 // This currently forces unfolding various combinations of fsub into fma with 3838 // free fneg'd operands. As long as we have fast FMA (controlled by 3839 // isFMAFasterThanFMulAndFAdd), we should perform these. 3840 3841 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3842 // most of these combines appear to be cycle neutral but save on instruction 3843 // count / code size. 3844 return true; 3845 } 3846 3847 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3848 EVT VT) const { 3849 if (!VT.isVector()) { 3850 return MVT::i1; 3851 } 3852 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3853 } 3854 3855 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3856 // TODO: Should i16 be used always if legal? For now it would force VALU 3857 // shifts. 3858 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3859 } 3860 3861 // Answering this is somewhat tricky and depends on the specific device which 3862 // have different rates for fma or all f64 operations. 3863 // 3864 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3865 // regardless of which device (although the number of cycles differs between 3866 // devices), so it is always profitable for f64. 3867 // 3868 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3869 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3870 // which we can always do even without fused FP ops since it returns the same 3871 // result as the separate operations and since it is always full 3872 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3873 // however does not support denormals, so we do report fma as faster if we have 3874 // a fast fma device and require denormals. 3875 // 3876 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3877 EVT VT) const { 3878 VT = VT.getScalarType(); 3879 3880 switch (VT.getSimpleVT().SimpleTy) { 3881 case MVT::f32: { 3882 // This is as fast on some subtargets. However, we always have full rate f32 3883 // mad available which returns the same result as the separate operations 3884 // which we should prefer over fma. We can't use this if we want to support 3885 // denormals, so only report this in these cases. 3886 if (hasFP32Denormals(MF)) 3887 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3888 3889 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3890 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3891 } 3892 case MVT::f64: 3893 return true; 3894 case MVT::f16: 3895 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3896 default: 3897 break; 3898 } 3899 3900 return false; 3901 } 3902 3903 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3904 const SDNode *N) const { 3905 // TODO: Check future ftz flag 3906 // v_mad_f32/v_mac_f32 do not support denormals. 3907 EVT VT = N->getValueType(0); 3908 if (VT == MVT::f32) 3909 return !hasFP32Denormals(DAG.getMachineFunction()); 3910 if (VT == MVT::f16) { 3911 return Subtarget->hasMadF16() && 3912 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3913 } 3914 3915 return false; 3916 } 3917 3918 //===----------------------------------------------------------------------===// 3919 // Custom DAG Lowering Operations 3920 //===----------------------------------------------------------------------===// 3921 3922 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3923 // wider vector type is legal. 3924 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3925 SelectionDAG &DAG) const { 3926 unsigned Opc = Op.getOpcode(); 3927 EVT VT = Op.getValueType(); 3928 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 3929 3930 SDValue Lo, Hi; 3931 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3932 3933 SDLoc SL(Op); 3934 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3935 Op->getFlags()); 3936 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3937 Op->getFlags()); 3938 3939 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3940 } 3941 3942 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3943 // wider vector type is legal. 3944 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3945 SelectionDAG &DAG) const { 3946 unsigned Opc = Op.getOpcode(); 3947 EVT VT = Op.getValueType(); 3948 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3949 3950 SDValue Lo0, Hi0; 3951 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3952 SDValue Lo1, Hi1; 3953 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3954 3955 SDLoc SL(Op); 3956 3957 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3958 Op->getFlags()); 3959 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3960 Op->getFlags()); 3961 3962 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3963 } 3964 3965 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 3966 SelectionDAG &DAG) const { 3967 unsigned Opc = Op.getOpcode(); 3968 EVT VT = Op.getValueType(); 3969 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3970 3971 SDValue Lo0, Hi0; 3972 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3973 SDValue Lo1, Hi1; 3974 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3975 SDValue Lo2, Hi2; 3976 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 3977 3978 SDLoc SL(Op); 3979 3980 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 3981 Op->getFlags()); 3982 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 3983 Op->getFlags()); 3984 3985 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3986 } 3987 3988 3989 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3990 switch (Op.getOpcode()) { 3991 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3992 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3993 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 3994 case ISD::LOAD: { 3995 SDValue Result = LowerLOAD(Op, DAG); 3996 assert((!Result.getNode() || 3997 Result.getNode()->getNumValues() == 2) && 3998 "Load should return a value and a chain"); 3999 return Result; 4000 } 4001 4002 case ISD::FSIN: 4003 case ISD::FCOS: 4004 return LowerTrig(Op, DAG); 4005 case ISD::SELECT: return LowerSELECT(Op, DAG); 4006 case ISD::FDIV: return LowerFDIV(Op, DAG); 4007 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4008 case ISD::STORE: return LowerSTORE(Op, DAG); 4009 case ISD::GlobalAddress: { 4010 MachineFunction &MF = DAG.getMachineFunction(); 4011 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4012 return LowerGlobalAddress(MFI, Op, DAG); 4013 } 4014 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4015 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4016 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4017 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4018 case ISD::INSERT_SUBVECTOR: 4019 return lowerINSERT_SUBVECTOR(Op, DAG); 4020 case ISD::INSERT_VECTOR_ELT: 4021 return lowerINSERT_VECTOR_ELT(Op, DAG); 4022 case ISD::EXTRACT_VECTOR_ELT: 4023 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4024 case ISD::VECTOR_SHUFFLE: 4025 return lowerVECTOR_SHUFFLE(Op, DAG); 4026 case ISD::BUILD_VECTOR: 4027 return lowerBUILD_VECTOR(Op, DAG); 4028 case ISD::FP_ROUND: 4029 return lowerFP_ROUND(Op, DAG); 4030 case ISD::TRAP: 4031 return lowerTRAP(Op, DAG); 4032 case ISD::DEBUGTRAP: 4033 return lowerDEBUGTRAP(Op, DAG); 4034 case ISD::FABS: 4035 case ISD::FNEG: 4036 case ISD::FCANONICALIZE: 4037 case ISD::BSWAP: 4038 return splitUnaryVectorOp(Op, DAG); 4039 case ISD::FMINNUM: 4040 case ISD::FMAXNUM: 4041 return lowerFMINNUM_FMAXNUM(Op, DAG); 4042 case ISD::FMA: 4043 return splitTernaryVectorOp(Op, DAG); 4044 case ISD::SHL: 4045 case ISD::SRA: 4046 case ISD::SRL: 4047 case ISD::ADD: 4048 case ISD::SUB: 4049 case ISD::MUL: 4050 case ISD::SMIN: 4051 case ISD::SMAX: 4052 case ISD::UMIN: 4053 case ISD::UMAX: 4054 case ISD::FADD: 4055 case ISD::FMUL: 4056 case ISD::FMINNUM_IEEE: 4057 case ISD::FMAXNUM_IEEE: 4058 return splitBinaryVectorOp(Op, DAG); 4059 } 4060 return SDValue(); 4061 } 4062 4063 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4064 const SDLoc &DL, 4065 SelectionDAG &DAG, bool Unpacked) { 4066 if (!LoadVT.isVector()) 4067 return Result; 4068 4069 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4070 // Truncate to v2i16/v4i16. 4071 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4072 4073 // Workaround legalizer not scalarizing truncate after vector op 4074 // legalization byt not creating intermediate vector trunc. 4075 SmallVector<SDValue, 4> Elts; 4076 DAG.ExtractVectorElements(Result, Elts); 4077 for (SDValue &Elt : Elts) 4078 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4079 4080 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4081 4082 // Bitcast to original type (v2f16/v4f16). 4083 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4084 } 4085 4086 // Cast back to the original packed type. 4087 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4088 } 4089 4090 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4091 MemSDNode *M, 4092 SelectionDAG &DAG, 4093 ArrayRef<SDValue> Ops, 4094 bool IsIntrinsic) const { 4095 SDLoc DL(M); 4096 4097 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4098 EVT LoadVT = M->getValueType(0); 4099 4100 EVT EquivLoadVT = LoadVT; 4101 if (Unpacked && LoadVT.isVector()) { 4102 EquivLoadVT = LoadVT.isVector() ? 4103 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4104 LoadVT.getVectorNumElements()) : LoadVT; 4105 } 4106 4107 // Change from v4f16/v2f16 to EquivLoadVT. 4108 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4109 4110 SDValue Load 4111 = DAG.getMemIntrinsicNode( 4112 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4113 VTList, Ops, M->getMemoryVT(), 4114 M->getMemOperand()); 4115 if (!Unpacked) // Just adjusted the opcode. 4116 return Load; 4117 4118 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4119 4120 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4121 } 4122 4123 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4124 SelectionDAG &DAG, 4125 ArrayRef<SDValue> Ops) const { 4126 SDLoc DL(M); 4127 EVT LoadVT = M->getValueType(0); 4128 EVT EltType = LoadVT.getScalarType(); 4129 EVT IntVT = LoadVT.changeTypeToInteger(); 4130 4131 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4132 4133 unsigned Opc = 4134 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4135 4136 if (IsD16) { 4137 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4138 } 4139 4140 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4141 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4142 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4143 4144 if (isTypeLegal(LoadVT)) { 4145 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4146 M->getMemOperand(), DAG); 4147 } 4148 4149 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4150 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4151 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4152 M->getMemOperand(), DAG); 4153 return DAG.getMergeValues( 4154 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4155 DL); 4156 } 4157 4158 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4159 SDNode *N, SelectionDAG &DAG) { 4160 EVT VT = N->getValueType(0); 4161 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4162 int CondCode = CD->getSExtValue(); 4163 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4164 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4165 return DAG.getUNDEF(VT); 4166 4167 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4168 4169 SDValue LHS = N->getOperand(1); 4170 SDValue RHS = N->getOperand(2); 4171 4172 SDLoc DL(N); 4173 4174 EVT CmpVT = LHS.getValueType(); 4175 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4176 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4177 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4178 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4179 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4180 } 4181 4182 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4183 4184 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4185 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4186 4187 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4188 DAG.getCondCode(CCOpcode)); 4189 if (VT.bitsEq(CCVT)) 4190 return SetCC; 4191 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4192 } 4193 4194 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4195 SDNode *N, SelectionDAG &DAG) { 4196 EVT VT = N->getValueType(0); 4197 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4198 4199 int CondCode = CD->getSExtValue(); 4200 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4201 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4202 return DAG.getUNDEF(VT); 4203 } 4204 4205 SDValue Src0 = N->getOperand(1); 4206 SDValue Src1 = N->getOperand(2); 4207 EVT CmpVT = Src0.getValueType(); 4208 SDLoc SL(N); 4209 4210 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4211 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4212 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4213 } 4214 4215 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4216 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4217 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4218 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4219 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4220 Src1, DAG.getCondCode(CCOpcode)); 4221 if (VT.bitsEq(CCVT)) 4222 return SetCC; 4223 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4224 } 4225 4226 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4227 SmallVectorImpl<SDValue> &Results, 4228 SelectionDAG &DAG) const { 4229 switch (N->getOpcode()) { 4230 case ISD::INSERT_VECTOR_ELT: { 4231 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4232 Results.push_back(Res); 4233 return; 4234 } 4235 case ISD::EXTRACT_VECTOR_ELT: { 4236 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4237 Results.push_back(Res); 4238 return; 4239 } 4240 case ISD::INTRINSIC_WO_CHAIN: { 4241 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4242 switch (IID) { 4243 case Intrinsic::amdgcn_cvt_pkrtz: { 4244 SDValue Src0 = N->getOperand(1); 4245 SDValue Src1 = N->getOperand(2); 4246 SDLoc SL(N); 4247 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4248 Src0, Src1); 4249 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4250 return; 4251 } 4252 case Intrinsic::amdgcn_cvt_pknorm_i16: 4253 case Intrinsic::amdgcn_cvt_pknorm_u16: 4254 case Intrinsic::amdgcn_cvt_pk_i16: 4255 case Intrinsic::amdgcn_cvt_pk_u16: { 4256 SDValue Src0 = N->getOperand(1); 4257 SDValue Src1 = N->getOperand(2); 4258 SDLoc SL(N); 4259 unsigned Opcode; 4260 4261 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4262 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4263 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4264 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4265 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4266 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4267 else 4268 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4269 4270 EVT VT = N->getValueType(0); 4271 if (isTypeLegal(VT)) 4272 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4273 else { 4274 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4275 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4276 } 4277 return; 4278 } 4279 } 4280 break; 4281 } 4282 case ISD::INTRINSIC_W_CHAIN: { 4283 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4284 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4285 // FIXME: Hacky 4286 Results.push_back(Res.getOperand(0)); 4287 Results.push_back(Res.getOperand(1)); 4288 } else { 4289 Results.push_back(Res); 4290 Results.push_back(Res.getValue(1)); 4291 } 4292 return; 4293 } 4294 4295 break; 4296 } 4297 case ISD::SELECT: { 4298 SDLoc SL(N); 4299 EVT VT = N->getValueType(0); 4300 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4301 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4302 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4303 4304 EVT SelectVT = NewVT; 4305 if (NewVT.bitsLT(MVT::i32)) { 4306 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4307 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4308 SelectVT = MVT::i32; 4309 } 4310 4311 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4312 N->getOperand(0), LHS, RHS); 4313 4314 if (NewVT != SelectVT) 4315 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4316 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4317 return; 4318 } 4319 case ISD::FNEG: { 4320 if (N->getValueType(0) != MVT::v2f16) 4321 break; 4322 4323 SDLoc SL(N); 4324 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4325 4326 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4327 BC, 4328 DAG.getConstant(0x80008000, SL, MVT::i32)); 4329 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4330 return; 4331 } 4332 case ISD::FABS: { 4333 if (N->getValueType(0) != MVT::v2f16) 4334 break; 4335 4336 SDLoc SL(N); 4337 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4338 4339 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4340 BC, 4341 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4342 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4343 return; 4344 } 4345 default: 4346 break; 4347 } 4348 } 4349 4350 /// Helper function for LowerBRCOND 4351 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4352 4353 SDNode *Parent = Value.getNode(); 4354 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4355 I != E; ++I) { 4356 4357 if (I.getUse().get() != Value) 4358 continue; 4359 4360 if (I->getOpcode() == Opcode) 4361 return *I; 4362 } 4363 return nullptr; 4364 } 4365 4366 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4367 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4368 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4369 case Intrinsic::amdgcn_if: 4370 return AMDGPUISD::IF; 4371 case Intrinsic::amdgcn_else: 4372 return AMDGPUISD::ELSE; 4373 case Intrinsic::amdgcn_loop: 4374 return AMDGPUISD::LOOP; 4375 case Intrinsic::amdgcn_end_cf: 4376 llvm_unreachable("should not occur"); 4377 default: 4378 return 0; 4379 } 4380 } 4381 4382 // break, if_break, else_break are all only used as inputs to loop, not 4383 // directly as branch conditions. 4384 return 0; 4385 } 4386 4387 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4388 const Triple &TT = getTargetMachine().getTargetTriple(); 4389 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4390 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4391 AMDGPU::shouldEmitConstantsToTextSection(TT); 4392 } 4393 4394 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4395 // FIXME: Either avoid relying on address space here or change the default 4396 // address space for functions to avoid the explicit check. 4397 return (GV->getValueType()->isFunctionTy() || 4398 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4399 !shouldEmitFixup(GV) && 4400 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4401 } 4402 4403 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4404 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4405 } 4406 4407 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4408 if (!GV->hasExternalLinkage()) 4409 return true; 4410 4411 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4412 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4413 } 4414 4415 /// This transforms the control flow intrinsics to get the branch destination as 4416 /// last parameter, also switches branch target with BR if the need arise 4417 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4418 SelectionDAG &DAG) const { 4419 SDLoc DL(BRCOND); 4420 4421 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4422 SDValue Target = BRCOND.getOperand(2); 4423 SDNode *BR = nullptr; 4424 SDNode *SetCC = nullptr; 4425 4426 if (Intr->getOpcode() == ISD::SETCC) { 4427 // As long as we negate the condition everything is fine 4428 SetCC = Intr; 4429 Intr = SetCC->getOperand(0).getNode(); 4430 4431 } else { 4432 // Get the target from BR if we don't negate the condition 4433 BR = findUser(BRCOND, ISD::BR); 4434 Target = BR->getOperand(1); 4435 } 4436 4437 // FIXME: This changes the types of the intrinsics instead of introducing new 4438 // nodes with the correct types. 4439 // e.g. llvm.amdgcn.loop 4440 4441 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4442 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4443 4444 unsigned CFNode = isCFIntrinsic(Intr); 4445 if (CFNode == 0) { 4446 // This is a uniform branch so we don't need to legalize. 4447 return BRCOND; 4448 } 4449 4450 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4451 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4452 4453 assert(!SetCC || 4454 (SetCC->getConstantOperandVal(1) == 1 && 4455 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4456 ISD::SETNE)); 4457 4458 // operands of the new intrinsic call 4459 SmallVector<SDValue, 4> Ops; 4460 if (HaveChain) 4461 Ops.push_back(BRCOND.getOperand(0)); 4462 4463 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4464 Ops.push_back(Target); 4465 4466 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4467 4468 // build the new intrinsic call 4469 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4470 4471 if (!HaveChain) { 4472 SDValue Ops[] = { 4473 SDValue(Result, 0), 4474 BRCOND.getOperand(0) 4475 }; 4476 4477 Result = DAG.getMergeValues(Ops, DL).getNode(); 4478 } 4479 4480 if (BR) { 4481 // Give the branch instruction our target 4482 SDValue Ops[] = { 4483 BR->getOperand(0), 4484 BRCOND.getOperand(2) 4485 }; 4486 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4487 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4488 BR = NewBR.getNode(); 4489 } 4490 4491 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4492 4493 // Copy the intrinsic results to registers 4494 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4495 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4496 if (!CopyToReg) 4497 continue; 4498 4499 Chain = DAG.getCopyToReg( 4500 Chain, DL, 4501 CopyToReg->getOperand(1), 4502 SDValue(Result, i - 1), 4503 SDValue()); 4504 4505 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4506 } 4507 4508 // Remove the old intrinsic from the chain 4509 DAG.ReplaceAllUsesOfValueWith( 4510 SDValue(Intr, Intr->getNumValues() - 1), 4511 Intr->getOperand(0)); 4512 4513 return Chain; 4514 } 4515 4516 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4517 SelectionDAG &DAG) const { 4518 MVT VT = Op.getSimpleValueType(); 4519 SDLoc DL(Op); 4520 // Checking the depth 4521 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4522 return DAG.getConstant(0, DL, VT); 4523 4524 MachineFunction &MF = DAG.getMachineFunction(); 4525 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4526 // Check for kernel and shader functions 4527 if (Info->isEntryFunction()) 4528 return DAG.getConstant(0, DL, VT); 4529 4530 MachineFrameInfo &MFI = MF.getFrameInfo(); 4531 // There is a call to @llvm.returnaddress in this function 4532 MFI.setReturnAddressIsTaken(true); 4533 4534 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4535 // Get the return address reg and mark it as an implicit live-in 4536 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4537 4538 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4539 } 4540 4541 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4542 SDValue Op, 4543 const SDLoc &DL, 4544 EVT VT) const { 4545 return Op.getValueType().bitsLE(VT) ? 4546 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4547 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4548 DAG.getTargetConstant(0, DL, MVT::i32)); 4549 } 4550 4551 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4552 assert(Op.getValueType() == MVT::f16 && 4553 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4554 4555 SDValue Src = Op.getOperand(0); 4556 EVT SrcVT = Src.getValueType(); 4557 if (SrcVT != MVT::f64) 4558 return Op; 4559 4560 SDLoc DL(Op); 4561 4562 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4563 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4564 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4565 } 4566 4567 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4568 SelectionDAG &DAG) const { 4569 EVT VT = Op.getValueType(); 4570 const MachineFunction &MF = DAG.getMachineFunction(); 4571 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4572 bool IsIEEEMode = Info->getMode().IEEE; 4573 4574 // FIXME: Assert during selection that this is only selected for 4575 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4576 // mode functions, but this happens to be OK since it's only done in cases 4577 // where there is known no sNaN. 4578 if (IsIEEEMode) 4579 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4580 4581 if (VT == MVT::v4f16) 4582 return splitBinaryVectorOp(Op, DAG); 4583 return Op; 4584 } 4585 4586 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4587 SDLoc SL(Op); 4588 SDValue Chain = Op.getOperand(0); 4589 4590 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4591 !Subtarget->isTrapHandlerEnabled()) 4592 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4593 4594 MachineFunction &MF = DAG.getMachineFunction(); 4595 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4596 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4597 assert(UserSGPR != AMDGPU::NoRegister); 4598 SDValue QueuePtr = CreateLiveInRegister( 4599 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4600 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4601 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4602 QueuePtr, SDValue()); 4603 SDValue Ops[] = { 4604 ToReg, 4605 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4606 SGPR01, 4607 ToReg.getValue(1) 4608 }; 4609 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4610 } 4611 4612 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4613 SDLoc SL(Op); 4614 SDValue Chain = Op.getOperand(0); 4615 MachineFunction &MF = DAG.getMachineFunction(); 4616 4617 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4618 !Subtarget->isTrapHandlerEnabled()) { 4619 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4620 "debugtrap handler not supported", 4621 Op.getDebugLoc(), 4622 DS_Warning); 4623 LLVMContext &Ctx = MF.getFunction().getContext(); 4624 Ctx.diagnose(NoTrap); 4625 return Chain; 4626 } 4627 4628 SDValue Ops[] = { 4629 Chain, 4630 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4631 }; 4632 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4633 } 4634 4635 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4636 SelectionDAG &DAG) const { 4637 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4638 if (Subtarget->hasApertureRegs()) { 4639 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4640 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4641 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4642 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4643 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4644 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4645 unsigned Encoding = 4646 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4647 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4648 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4649 4650 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4651 SDValue ApertureReg = SDValue( 4652 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4653 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4654 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4655 } 4656 4657 MachineFunction &MF = DAG.getMachineFunction(); 4658 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4659 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4660 assert(UserSGPR != AMDGPU::NoRegister); 4661 4662 SDValue QueuePtr = CreateLiveInRegister( 4663 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4664 4665 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4666 // private_segment_aperture_base_hi. 4667 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4668 4669 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4670 4671 // TODO: Use custom target PseudoSourceValue. 4672 // TODO: We should use the value from the IR intrinsic call, but it might not 4673 // be available and how do we get it? 4674 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4675 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4676 MinAlign(64, StructOffset), 4677 MachineMemOperand::MODereferenceable | 4678 MachineMemOperand::MOInvariant); 4679 } 4680 4681 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4682 SelectionDAG &DAG) const { 4683 SDLoc SL(Op); 4684 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4685 4686 SDValue Src = ASC->getOperand(0); 4687 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4688 4689 const AMDGPUTargetMachine &TM = 4690 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4691 4692 // flat -> local/private 4693 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4694 unsigned DestAS = ASC->getDestAddressSpace(); 4695 4696 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4697 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4698 unsigned NullVal = TM.getNullPointerValue(DestAS); 4699 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4700 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4701 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4702 4703 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4704 NonNull, Ptr, SegmentNullPtr); 4705 } 4706 } 4707 4708 // local/private -> flat 4709 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4710 unsigned SrcAS = ASC->getSrcAddressSpace(); 4711 4712 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4713 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4714 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4715 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4716 4717 SDValue NonNull 4718 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4719 4720 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4721 SDValue CvtPtr 4722 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4723 4724 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4725 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4726 FlatNullPtr); 4727 } 4728 } 4729 4730 // global <-> flat are no-ops and never emitted. 4731 4732 const MachineFunction &MF = DAG.getMachineFunction(); 4733 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4734 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4735 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4736 4737 return DAG.getUNDEF(ASC->getValueType(0)); 4738 } 4739 4740 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4741 // the small vector and inserting them into the big vector. That is better than 4742 // the default expansion of doing it via a stack slot. Even though the use of 4743 // the stack slot would be optimized away afterwards, the stack slot itself 4744 // remains. 4745 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4746 SelectionDAG &DAG) const { 4747 SDValue Vec = Op.getOperand(0); 4748 SDValue Ins = Op.getOperand(1); 4749 SDValue Idx = Op.getOperand(2); 4750 EVT VecVT = Vec.getValueType(); 4751 EVT InsVT = Ins.getValueType(); 4752 EVT EltVT = VecVT.getVectorElementType(); 4753 unsigned InsNumElts = InsVT.getVectorNumElements(); 4754 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4755 SDLoc SL(Op); 4756 4757 for (unsigned I = 0; I != InsNumElts; ++I) { 4758 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4759 DAG.getConstant(I, SL, MVT::i32)); 4760 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4761 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4762 } 4763 return Vec; 4764 } 4765 4766 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4767 SelectionDAG &DAG) const { 4768 SDValue Vec = Op.getOperand(0); 4769 SDValue InsVal = Op.getOperand(1); 4770 SDValue Idx = Op.getOperand(2); 4771 EVT VecVT = Vec.getValueType(); 4772 EVT EltVT = VecVT.getVectorElementType(); 4773 unsigned VecSize = VecVT.getSizeInBits(); 4774 unsigned EltSize = EltVT.getSizeInBits(); 4775 4776 4777 assert(VecSize <= 64); 4778 4779 unsigned NumElts = VecVT.getVectorNumElements(); 4780 SDLoc SL(Op); 4781 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4782 4783 if (NumElts == 4 && EltSize == 16 && KIdx) { 4784 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4785 4786 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4787 DAG.getConstant(0, SL, MVT::i32)); 4788 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4789 DAG.getConstant(1, SL, MVT::i32)); 4790 4791 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4792 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4793 4794 unsigned Idx = KIdx->getZExtValue(); 4795 bool InsertLo = Idx < 2; 4796 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4797 InsertLo ? LoVec : HiVec, 4798 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4799 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4800 4801 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4802 4803 SDValue Concat = InsertLo ? 4804 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4805 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4806 4807 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4808 } 4809 4810 if (isa<ConstantSDNode>(Idx)) 4811 return SDValue(); 4812 4813 MVT IntVT = MVT::getIntegerVT(VecSize); 4814 4815 // Avoid stack access for dynamic indexing. 4816 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4817 4818 // Create a congruent vector with the target value in each element so that 4819 // the required element can be masked and ORed into the target vector. 4820 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4821 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4822 4823 assert(isPowerOf2_32(EltSize)); 4824 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4825 4826 // Convert vector index to bit-index. 4827 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4828 4829 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4830 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4831 DAG.getConstant(0xffff, SL, IntVT), 4832 ScaledIdx); 4833 4834 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4835 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4836 DAG.getNOT(SL, BFM, IntVT), BCVec); 4837 4838 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4839 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4840 } 4841 4842 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4843 SelectionDAG &DAG) const { 4844 SDLoc SL(Op); 4845 4846 EVT ResultVT = Op.getValueType(); 4847 SDValue Vec = Op.getOperand(0); 4848 SDValue Idx = Op.getOperand(1); 4849 EVT VecVT = Vec.getValueType(); 4850 unsigned VecSize = VecVT.getSizeInBits(); 4851 EVT EltVT = VecVT.getVectorElementType(); 4852 assert(VecSize <= 64); 4853 4854 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4855 4856 // Make sure we do any optimizations that will make it easier to fold 4857 // source modifiers before obscuring it with bit operations. 4858 4859 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4860 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4861 return Combined; 4862 4863 unsigned EltSize = EltVT.getSizeInBits(); 4864 assert(isPowerOf2_32(EltSize)); 4865 4866 MVT IntVT = MVT::getIntegerVT(VecSize); 4867 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4868 4869 // Convert vector index to bit-index (* EltSize) 4870 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4871 4872 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4873 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4874 4875 if (ResultVT == MVT::f16) { 4876 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4877 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4878 } 4879 4880 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4881 } 4882 4883 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4884 assert(Elt % 2 == 0); 4885 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4886 } 4887 4888 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4889 SelectionDAG &DAG) const { 4890 SDLoc SL(Op); 4891 EVT ResultVT = Op.getValueType(); 4892 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4893 4894 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4895 EVT EltVT = PackVT.getVectorElementType(); 4896 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4897 4898 // vector_shuffle <0,1,6,7> lhs, rhs 4899 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4900 // 4901 // vector_shuffle <6,7,2,3> lhs, rhs 4902 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4903 // 4904 // vector_shuffle <6,7,0,1> lhs, rhs 4905 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4906 4907 // Avoid scalarizing when both halves are reading from consecutive elements. 4908 SmallVector<SDValue, 4> Pieces; 4909 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4910 if (elementPairIsContiguous(SVN->getMask(), I)) { 4911 const int Idx = SVN->getMaskElt(I); 4912 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4913 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4914 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4915 PackVT, SVN->getOperand(VecIdx), 4916 DAG.getConstant(EltIdx, SL, MVT::i32)); 4917 Pieces.push_back(SubVec); 4918 } else { 4919 const int Idx0 = SVN->getMaskElt(I); 4920 const int Idx1 = SVN->getMaskElt(I + 1); 4921 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4922 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4923 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4924 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4925 4926 SDValue Vec0 = SVN->getOperand(VecIdx0); 4927 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4928 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4929 4930 SDValue Vec1 = SVN->getOperand(VecIdx1); 4931 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4932 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4933 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4934 } 4935 } 4936 4937 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4938 } 4939 4940 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4941 SelectionDAG &DAG) const { 4942 SDLoc SL(Op); 4943 EVT VT = Op.getValueType(); 4944 4945 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4946 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4947 4948 // Turn into pair of packed build_vectors. 4949 // TODO: Special case for constants that can be materialized with s_mov_b64. 4950 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4951 { Op.getOperand(0), Op.getOperand(1) }); 4952 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4953 { Op.getOperand(2), Op.getOperand(3) }); 4954 4955 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4956 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4957 4958 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4959 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4960 } 4961 4962 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4963 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4964 4965 SDValue Lo = Op.getOperand(0); 4966 SDValue Hi = Op.getOperand(1); 4967 4968 // Avoid adding defined bits with the zero_extend. 4969 if (Hi.isUndef()) { 4970 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4971 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4972 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4973 } 4974 4975 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4976 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4977 4978 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4979 DAG.getConstant(16, SL, MVT::i32)); 4980 if (Lo.isUndef()) 4981 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4982 4983 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4984 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4985 4986 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4987 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4988 } 4989 4990 bool 4991 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4992 // We can fold offsets for anything that doesn't require a GOT relocation. 4993 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4994 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4995 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4996 !shouldEmitGOTReloc(GA->getGlobal()); 4997 } 4998 4999 static SDValue 5000 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5001 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5002 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5003 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5004 // lowered to the following code sequence: 5005 // 5006 // For constant address space: 5007 // s_getpc_b64 s[0:1] 5008 // s_add_u32 s0, s0, $symbol 5009 // s_addc_u32 s1, s1, 0 5010 // 5011 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5012 // a fixup or relocation is emitted to replace $symbol with a literal 5013 // constant, which is a pc-relative offset from the encoding of the $symbol 5014 // operand to the global variable. 5015 // 5016 // For global address space: 5017 // s_getpc_b64 s[0:1] 5018 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5019 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5020 // 5021 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5022 // fixups or relocations are emitted to replace $symbol@*@lo and 5023 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5024 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5025 // operand to the global variable. 5026 // 5027 // What we want here is an offset from the value returned by s_getpc 5028 // (which is the address of the s_add_u32 instruction) to the global 5029 // variable, but since the encoding of $symbol starts 4 bytes after the start 5030 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5031 // small. This requires us to add 4 to the global variable offset in order to 5032 // compute the correct address. 5033 SDValue PtrLo = 5034 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5035 SDValue PtrHi; 5036 if (GAFlags == SIInstrInfo::MO_NONE) { 5037 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5038 } else { 5039 PtrHi = 5040 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5041 } 5042 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5043 } 5044 5045 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5046 SDValue Op, 5047 SelectionDAG &DAG) const { 5048 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5049 const GlobalValue *GV = GSD->getGlobal(); 5050 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5051 shouldUseLDSConstAddress(GV)) || 5052 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5053 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5054 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5055 5056 SDLoc DL(GSD); 5057 EVT PtrVT = Op.getValueType(); 5058 5059 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5060 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5061 SIInstrInfo::MO_ABS32_LO); 5062 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5063 } 5064 5065 if (shouldEmitFixup(GV)) 5066 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5067 else if (shouldEmitPCReloc(GV)) 5068 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5069 SIInstrInfo::MO_REL32); 5070 5071 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5072 SIInstrInfo::MO_GOTPCREL32); 5073 5074 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5075 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5076 const DataLayout &DataLayout = DAG.getDataLayout(); 5077 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5078 MachinePointerInfo PtrInfo 5079 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5080 5081 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5082 MachineMemOperand::MODereferenceable | 5083 MachineMemOperand::MOInvariant); 5084 } 5085 5086 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5087 const SDLoc &DL, SDValue V) const { 5088 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5089 // the destination register. 5090 // 5091 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5092 // so we will end up with redundant moves to m0. 5093 // 5094 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5095 5096 // A Null SDValue creates a glue result. 5097 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5098 V, Chain); 5099 return SDValue(M0, 0); 5100 } 5101 5102 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5103 SDValue Op, 5104 MVT VT, 5105 unsigned Offset) const { 5106 SDLoc SL(Op); 5107 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5108 DAG.getEntryNode(), Offset, 4, false); 5109 // The local size values will have the hi 16-bits as zero. 5110 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5111 DAG.getValueType(VT)); 5112 } 5113 5114 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5115 EVT VT) { 5116 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5117 "non-hsa intrinsic with hsa target", 5118 DL.getDebugLoc()); 5119 DAG.getContext()->diagnose(BadIntrin); 5120 return DAG.getUNDEF(VT); 5121 } 5122 5123 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5124 EVT VT) { 5125 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5126 "intrinsic not supported on subtarget", 5127 DL.getDebugLoc()); 5128 DAG.getContext()->diagnose(BadIntrin); 5129 return DAG.getUNDEF(VT); 5130 } 5131 5132 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5133 ArrayRef<SDValue> Elts) { 5134 assert(!Elts.empty()); 5135 MVT Type; 5136 unsigned NumElts; 5137 5138 if (Elts.size() == 1) { 5139 Type = MVT::f32; 5140 NumElts = 1; 5141 } else if (Elts.size() == 2) { 5142 Type = MVT::v2f32; 5143 NumElts = 2; 5144 } else if (Elts.size() == 3) { 5145 Type = MVT::v3f32; 5146 NumElts = 3; 5147 } else if (Elts.size() <= 4) { 5148 Type = MVT::v4f32; 5149 NumElts = 4; 5150 } else if (Elts.size() <= 8) { 5151 Type = MVT::v8f32; 5152 NumElts = 8; 5153 } else { 5154 assert(Elts.size() <= 16); 5155 Type = MVT::v16f32; 5156 NumElts = 16; 5157 } 5158 5159 SmallVector<SDValue, 16> VecElts(NumElts); 5160 for (unsigned i = 0; i < Elts.size(); ++i) { 5161 SDValue Elt = Elts[i]; 5162 if (Elt.getValueType() != MVT::f32) 5163 Elt = DAG.getBitcast(MVT::f32, Elt); 5164 VecElts[i] = Elt; 5165 } 5166 for (unsigned i = Elts.size(); i < NumElts; ++i) 5167 VecElts[i] = DAG.getUNDEF(MVT::f32); 5168 5169 if (NumElts == 1) 5170 return VecElts[0]; 5171 return DAG.getBuildVector(Type, DL, VecElts); 5172 } 5173 5174 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5175 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5176 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5177 5178 uint64_t Value = CachePolicyConst->getZExtValue(); 5179 SDLoc DL(CachePolicy); 5180 if (GLC) { 5181 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5182 Value &= ~(uint64_t)0x1; 5183 } 5184 if (SLC) { 5185 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5186 Value &= ~(uint64_t)0x2; 5187 } 5188 if (DLC) { 5189 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5190 Value &= ~(uint64_t)0x4; 5191 } 5192 5193 return Value == 0; 5194 } 5195 5196 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5197 SDValue Src, int ExtraElts) { 5198 EVT SrcVT = Src.getValueType(); 5199 5200 SmallVector<SDValue, 8> Elts; 5201 5202 if (SrcVT.isVector()) 5203 DAG.ExtractVectorElements(Src, Elts); 5204 else 5205 Elts.push_back(Src); 5206 5207 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5208 while (ExtraElts--) 5209 Elts.push_back(Undef); 5210 5211 return DAG.getBuildVector(CastVT, DL, Elts); 5212 } 5213 5214 // Re-construct the required return value for a image load intrinsic. 5215 // This is more complicated due to the optional use TexFailCtrl which means the required 5216 // return type is an aggregate 5217 static SDValue constructRetValue(SelectionDAG &DAG, 5218 MachineSDNode *Result, 5219 ArrayRef<EVT> ResultTypes, 5220 bool IsTexFail, bool Unpacked, bool IsD16, 5221 int DMaskPop, int NumVDataDwords, 5222 const SDLoc &DL, LLVMContext &Context) { 5223 // Determine the required return type. This is the same regardless of IsTexFail flag 5224 EVT ReqRetVT = ResultTypes[0]; 5225 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5226 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5227 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5228 5229 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5230 DMaskPop : (DMaskPop + 1) / 2; 5231 5232 MVT DataDwordVT = NumDataDwords == 1 ? 5233 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5234 5235 MVT MaskPopVT = MaskPopDwords == 1 ? 5236 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5237 5238 SDValue Data(Result, 0); 5239 SDValue TexFail; 5240 5241 if (IsTexFail) { 5242 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5243 if (MaskPopVT.isVector()) { 5244 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5245 SDValue(Result, 0), ZeroIdx); 5246 } else { 5247 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5248 SDValue(Result, 0), ZeroIdx); 5249 } 5250 5251 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5252 SDValue(Result, 0), 5253 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5254 } 5255 5256 if (DataDwordVT.isVector()) 5257 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5258 NumDataDwords - MaskPopDwords); 5259 5260 if (IsD16) 5261 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5262 5263 if (!ReqRetVT.isVector()) 5264 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5265 5266 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5267 5268 if (TexFail) 5269 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5270 5271 if (Result->getNumValues() == 1) 5272 return Data; 5273 5274 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5275 } 5276 5277 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5278 SDValue *LWE, bool &IsTexFail) { 5279 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5280 5281 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5282 if (Value) { 5283 IsTexFail = true; 5284 } 5285 5286 SDLoc DL(TexFailCtrlConst); 5287 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5288 Value &= ~(uint64_t)0x1; 5289 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5290 Value &= ~(uint64_t)0x2; 5291 5292 return Value == 0; 5293 } 5294 5295 SDValue SITargetLowering::lowerImage(SDValue Op, 5296 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5297 SelectionDAG &DAG) const { 5298 SDLoc DL(Op); 5299 MachineFunction &MF = DAG.getMachineFunction(); 5300 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5301 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5302 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5303 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5304 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5305 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5306 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5307 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5308 unsigned IntrOpcode = Intr->BaseOpcode; 5309 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5310 5311 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5312 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5313 bool IsD16 = false; 5314 bool IsA16 = false; 5315 SDValue VData; 5316 int NumVDataDwords; 5317 bool AdjustRetType = false; 5318 5319 unsigned AddrIdx; // Index of first address argument 5320 unsigned DMask; 5321 unsigned DMaskLanes = 0; 5322 5323 if (BaseOpcode->Atomic) { 5324 VData = Op.getOperand(2); 5325 5326 bool Is64Bit = VData.getValueType() == MVT::i64; 5327 if (BaseOpcode->AtomicX2) { 5328 SDValue VData2 = Op.getOperand(3); 5329 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5330 {VData, VData2}); 5331 if (Is64Bit) 5332 VData = DAG.getBitcast(MVT::v4i32, VData); 5333 5334 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5335 DMask = Is64Bit ? 0xf : 0x3; 5336 NumVDataDwords = Is64Bit ? 4 : 2; 5337 AddrIdx = 4; 5338 } else { 5339 DMask = Is64Bit ? 0x3 : 0x1; 5340 NumVDataDwords = Is64Bit ? 2 : 1; 5341 AddrIdx = 3; 5342 } 5343 } else { 5344 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5345 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5346 DMask = DMaskConst->getZExtValue(); 5347 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5348 5349 if (BaseOpcode->Store) { 5350 VData = Op.getOperand(2); 5351 5352 MVT StoreVT = VData.getSimpleValueType(); 5353 if (StoreVT.getScalarType() == MVT::f16) { 5354 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5355 return Op; // D16 is unsupported for this instruction 5356 5357 IsD16 = true; 5358 VData = handleD16VData(VData, DAG); 5359 } 5360 5361 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5362 } else { 5363 // Work out the num dwords based on the dmask popcount and underlying type 5364 // and whether packing is supported. 5365 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5366 if (LoadVT.getScalarType() == MVT::f16) { 5367 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5368 return Op; // D16 is unsupported for this instruction 5369 5370 IsD16 = true; 5371 } 5372 5373 // Confirm that the return type is large enough for the dmask specified 5374 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5375 (!LoadVT.isVector() && DMaskLanes > 1)) 5376 return Op; 5377 5378 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5379 NumVDataDwords = (DMaskLanes + 1) / 2; 5380 else 5381 NumVDataDwords = DMaskLanes; 5382 5383 AdjustRetType = true; 5384 } 5385 5386 AddrIdx = DMaskIdx + 1; 5387 } 5388 5389 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5390 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5391 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5392 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5393 NumCoords + NumLCM; 5394 unsigned NumMIVAddrs = NumVAddrs; 5395 5396 SmallVector<SDValue, 4> VAddrs; 5397 5398 // Optimize _L to _LZ when _L is zero 5399 if (LZMappingInfo) { 5400 if (auto ConstantLod = 5401 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5402 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5403 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5404 NumMIVAddrs--; // remove 'lod' 5405 } 5406 } 5407 } 5408 5409 // Optimize _mip away, when 'lod' is zero 5410 if (MIPMappingInfo) { 5411 if (auto ConstantLod = 5412 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5413 if (ConstantLod->isNullValue()) { 5414 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5415 NumMIVAddrs--; // remove 'lod' 5416 } 5417 } 5418 } 5419 5420 // Check for 16 bit addresses and pack if true. 5421 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5422 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5423 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5424 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5425 // Illegal to use a16 images 5426 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5427 return Op; 5428 5429 IsA16 = true; 5430 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5431 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5432 SDValue AddrLo; 5433 // Push back extra arguments. 5434 if (i < DimIdx) { 5435 AddrLo = Op.getOperand(i); 5436 } else { 5437 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5438 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5439 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5440 ((NumGradients / 2) % 2 == 1 && 5441 (i == DimIdx + (NumGradients / 2) - 1 || 5442 i == DimIdx + NumGradients - 1))) { 5443 AddrLo = Op.getOperand(i); 5444 if (AddrLo.getValueType() != MVT::i16) 5445 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5446 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5447 } else { 5448 AddrLo = DAG.getBuildVector(VectorVT, DL, 5449 {Op.getOperand(i), Op.getOperand(i + 1)}); 5450 i++; 5451 } 5452 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5453 } 5454 VAddrs.push_back(AddrLo); 5455 } 5456 } else { 5457 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5458 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5459 } 5460 5461 // If the register allocator cannot place the address registers contiguously 5462 // without introducing moves, then using the non-sequential address encoding 5463 // is always preferable, since it saves VALU instructions and is usually a 5464 // wash in terms of code size or even better. 5465 // 5466 // However, we currently have no way of hinting to the register allocator that 5467 // MIMG addresses should be placed contiguously when it is possible to do so, 5468 // so force non-NSA for the common 2-address case as a heuristic. 5469 // 5470 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5471 // allocation when possible. 5472 bool UseNSA = 5473 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5474 SDValue VAddr; 5475 if (!UseNSA) 5476 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5477 5478 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5479 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5480 unsigned CtrlIdx; // Index of texfailctrl argument 5481 SDValue Unorm; 5482 if (!BaseOpcode->Sampler) { 5483 Unorm = True; 5484 CtrlIdx = AddrIdx + NumVAddrs + 1; 5485 } else { 5486 auto UnormConst = 5487 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5488 5489 Unorm = UnormConst->getZExtValue() ? True : False; 5490 CtrlIdx = AddrIdx + NumVAddrs + 3; 5491 } 5492 5493 SDValue TFE; 5494 SDValue LWE; 5495 SDValue TexFail = Op.getOperand(CtrlIdx); 5496 bool IsTexFail = false; 5497 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5498 return Op; 5499 5500 if (IsTexFail) { 5501 if (!DMaskLanes) { 5502 // Expecting to get an error flag since TFC is on - and dmask is 0 5503 // Force dmask to be at least 1 otherwise the instruction will fail 5504 DMask = 0x1; 5505 DMaskLanes = 1; 5506 NumVDataDwords = 1; 5507 } 5508 NumVDataDwords += 1; 5509 AdjustRetType = true; 5510 } 5511 5512 // Has something earlier tagged that the return type needs adjusting 5513 // This happens if the instruction is a load or has set TexFailCtrl flags 5514 if (AdjustRetType) { 5515 // NumVDataDwords reflects the true number of dwords required in the return type 5516 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5517 // This is a no-op load. This can be eliminated 5518 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5519 if (isa<MemSDNode>(Op)) 5520 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5521 return Undef; 5522 } 5523 5524 EVT NewVT = NumVDataDwords > 1 ? 5525 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5526 : MVT::i32; 5527 5528 ResultTypes[0] = NewVT; 5529 if (ResultTypes.size() == 3) { 5530 // Original result was aggregate type used for TexFailCtrl results 5531 // The actual instruction returns as a vector type which has now been 5532 // created. Remove the aggregate result. 5533 ResultTypes.erase(&ResultTypes[1]); 5534 } 5535 } 5536 5537 SDValue GLC; 5538 SDValue SLC; 5539 SDValue DLC; 5540 if (BaseOpcode->Atomic) { 5541 GLC = True; // TODO no-return optimization 5542 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5543 IsGFX10 ? &DLC : nullptr)) 5544 return Op; 5545 } else { 5546 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5547 IsGFX10 ? &DLC : nullptr)) 5548 return Op; 5549 } 5550 5551 SmallVector<SDValue, 26> Ops; 5552 if (BaseOpcode->Store || BaseOpcode->Atomic) 5553 Ops.push_back(VData); // vdata 5554 if (UseNSA) { 5555 for (const SDValue &Addr : VAddrs) 5556 Ops.push_back(Addr); 5557 } else { 5558 Ops.push_back(VAddr); 5559 } 5560 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5561 if (BaseOpcode->Sampler) 5562 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5563 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5564 if (IsGFX10) 5565 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5566 Ops.push_back(Unorm); 5567 if (IsGFX10) 5568 Ops.push_back(DLC); 5569 Ops.push_back(GLC); 5570 Ops.push_back(SLC); 5571 Ops.push_back(IsA16 && // r128, a16 for gfx9 5572 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5573 if (IsGFX10) 5574 Ops.push_back(IsA16 ? True : False); 5575 Ops.push_back(TFE); 5576 Ops.push_back(LWE); 5577 if (!IsGFX10) 5578 Ops.push_back(DimInfo->DA ? True : False); 5579 if (BaseOpcode->HasD16) 5580 Ops.push_back(IsD16 ? True : False); 5581 if (isa<MemSDNode>(Op)) 5582 Ops.push_back(Op.getOperand(0)); // chain 5583 5584 int NumVAddrDwords = 5585 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5586 int Opcode = -1; 5587 5588 if (IsGFX10) { 5589 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5590 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5591 : AMDGPU::MIMGEncGfx10Default, 5592 NumVDataDwords, NumVAddrDwords); 5593 } else { 5594 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5595 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5596 NumVDataDwords, NumVAddrDwords); 5597 if (Opcode == -1) 5598 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5599 NumVDataDwords, NumVAddrDwords); 5600 } 5601 assert(Opcode != -1); 5602 5603 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5604 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5605 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5606 DAG.setNodeMemRefs(NewNode, {MemRef}); 5607 } 5608 5609 if (BaseOpcode->AtomicX2) { 5610 SmallVector<SDValue, 1> Elt; 5611 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5612 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5613 } else if (!BaseOpcode->Store) { 5614 return constructRetValue(DAG, NewNode, 5615 OrigResultTypes, IsTexFail, 5616 Subtarget->hasUnpackedD16VMem(), IsD16, 5617 DMaskLanes, NumVDataDwords, DL, 5618 *DAG.getContext()); 5619 } 5620 5621 return SDValue(NewNode, 0); 5622 } 5623 5624 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5625 SDValue Offset, SDValue CachePolicy, 5626 SelectionDAG &DAG) const { 5627 MachineFunction &MF = DAG.getMachineFunction(); 5628 5629 const DataLayout &DataLayout = DAG.getDataLayout(); 5630 unsigned Align = 5631 DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5632 5633 MachineMemOperand *MMO = MF.getMachineMemOperand( 5634 MachinePointerInfo(), 5635 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5636 MachineMemOperand::MOInvariant, 5637 VT.getStoreSize(), Align); 5638 5639 if (!Offset->isDivergent()) { 5640 SDValue Ops[] = { 5641 Rsrc, 5642 Offset, // Offset 5643 CachePolicy 5644 }; 5645 5646 // Widen vec3 load to vec4. 5647 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5648 EVT WidenedVT = 5649 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5650 auto WidenedOp = DAG.getMemIntrinsicNode( 5651 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5652 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5653 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5654 DAG.getVectorIdxConstant(0, DL)); 5655 return Subvector; 5656 } 5657 5658 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5659 DAG.getVTList(VT), Ops, VT, MMO); 5660 } 5661 5662 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5663 // assume that the buffer is unswizzled. 5664 SmallVector<SDValue, 4> Loads; 5665 unsigned NumLoads = 1; 5666 MVT LoadVT = VT.getSimpleVT(); 5667 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5668 assert((LoadVT.getScalarType() == MVT::i32 || 5669 LoadVT.getScalarType() == MVT::f32)); 5670 5671 if (NumElts == 8 || NumElts == 16) { 5672 NumLoads = NumElts / 4; 5673 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5674 } 5675 5676 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5677 SDValue Ops[] = { 5678 DAG.getEntryNode(), // Chain 5679 Rsrc, // rsrc 5680 DAG.getConstant(0, DL, MVT::i32), // vindex 5681 {}, // voffset 5682 {}, // soffset 5683 {}, // offset 5684 CachePolicy, // cachepolicy 5685 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5686 }; 5687 5688 // Use the alignment to ensure that the required offsets will fit into the 5689 // immediate offsets. 5690 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5691 5692 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5693 for (unsigned i = 0; i < NumLoads; ++i) { 5694 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5695 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5696 LoadVT, MMO, DAG)); 5697 } 5698 5699 if (NumElts == 8 || NumElts == 16) 5700 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5701 5702 return Loads[0]; 5703 } 5704 5705 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5706 SelectionDAG &DAG) const { 5707 MachineFunction &MF = DAG.getMachineFunction(); 5708 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5709 5710 EVT VT = Op.getValueType(); 5711 SDLoc DL(Op); 5712 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5713 5714 // TODO: Should this propagate fast-math-flags? 5715 5716 switch (IntrinsicID) { 5717 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5718 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5719 return emitNonHSAIntrinsicError(DAG, DL, VT); 5720 return getPreloadedValue(DAG, *MFI, VT, 5721 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5722 } 5723 case Intrinsic::amdgcn_dispatch_ptr: 5724 case Intrinsic::amdgcn_queue_ptr: { 5725 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5726 DiagnosticInfoUnsupported BadIntrin( 5727 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5728 DL.getDebugLoc()); 5729 DAG.getContext()->diagnose(BadIntrin); 5730 return DAG.getUNDEF(VT); 5731 } 5732 5733 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5734 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5735 return getPreloadedValue(DAG, *MFI, VT, RegID); 5736 } 5737 case Intrinsic::amdgcn_implicitarg_ptr: { 5738 if (MFI->isEntryFunction()) 5739 return getImplicitArgPtr(DAG, DL); 5740 return getPreloadedValue(DAG, *MFI, VT, 5741 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5742 } 5743 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5744 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 5745 // This only makes sense to call in a kernel, so just lower to null. 5746 return DAG.getConstant(0, DL, VT); 5747 } 5748 5749 return getPreloadedValue(DAG, *MFI, VT, 5750 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5751 } 5752 case Intrinsic::amdgcn_dispatch_id: { 5753 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5754 } 5755 case Intrinsic::amdgcn_rcp: 5756 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5757 case Intrinsic::amdgcn_rsq: 5758 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5759 case Intrinsic::amdgcn_rsq_legacy: 5760 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5761 return emitRemovedIntrinsicError(DAG, DL, VT); 5762 5763 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5764 case Intrinsic::amdgcn_rcp_legacy: 5765 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5766 return emitRemovedIntrinsicError(DAG, DL, VT); 5767 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5768 case Intrinsic::amdgcn_rsq_clamp: { 5769 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5770 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5771 5772 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5773 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5774 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5775 5776 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5777 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5778 DAG.getConstantFP(Max, DL, VT)); 5779 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5780 DAG.getConstantFP(Min, DL, VT)); 5781 } 5782 case Intrinsic::r600_read_ngroups_x: 5783 if (Subtarget->isAmdHsaOS()) 5784 return emitNonHSAIntrinsicError(DAG, DL, VT); 5785 5786 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5787 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5788 case Intrinsic::r600_read_ngroups_y: 5789 if (Subtarget->isAmdHsaOS()) 5790 return emitNonHSAIntrinsicError(DAG, DL, VT); 5791 5792 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5793 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5794 case Intrinsic::r600_read_ngroups_z: 5795 if (Subtarget->isAmdHsaOS()) 5796 return emitNonHSAIntrinsicError(DAG, DL, VT); 5797 5798 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5799 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5800 case Intrinsic::r600_read_global_size_x: 5801 if (Subtarget->isAmdHsaOS()) 5802 return emitNonHSAIntrinsicError(DAG, DL, VT); 5803 5804 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5805 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5806 case Intrinsic::r600_read_global_size_y: 5807 if (Subtarget->isAmdHsaOS()) 5808 return emitNonHSAIntrinsicError(DAG, DL, VT); 5809 5810 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5811 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5812 case Intrinsic::r600_read_global_size_z: 5813 if (Subtarget->isAmdHsaOS()) 5814 return emitNonHSAIntrinsicError(DAG, DL, VT); 5815 5816 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5817 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5818 case Intrinsic::r600_read_local_size_x: 5819 if (Subtarget->isAmdHsaOS()) 5820 return emitNonHSAIntrinsicError(DAG, DL, VT); 5821 5822 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5823 SI::KernelInputOffsets::LOCAL_SIZE_X); 5824 case Intrinsic::r600_read_local_size_y: 5825 if (Subtarget->isAmdHsaOS()) 5826 return emitNonHSAIntrinsicError(DAG, DL, VT); 5827 5828 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5829 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5830 case Intrinsic::r600_read_local_size_z: 5831 if (Subtarget->isAmdHsaOS()) 5832 return emitNonHSAIntrinsicError(DAG, DL, VT); 5833 5834 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5835 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5836 case Intrinsic::amdgcn_workgroup_id_x: 5837 return getPreloadedValue(DAG, *MFI, VT, 5838 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5839 case Intrinsic::amdgcn_workgroup_id_y: 5840 return getPreloadedValue(DAG, *MFI, VT, 5841 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5842 case Intrinsic::amdgcn_workgroup_id_z: 5843 return getPreloadedValue(DAG, *MFI, VT, 5844 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5845 case Intrinsic::amdgcn_workitem_id_x: 5846 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5847 SDLoc(DAG.getEntryNode()), 5848 MFI->getArgInfo().WorkItemIDX); 5849 case Intrinsic::amdgcn_workitem_id_y: 5850 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5851 SDLoc(DAG.getEntryNode()), 5852 MFI->getArgInfo().WorkItemIDY); 5853 case Intrinsic::amdgcn_workitem_id_z: 5854 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5855 SDLoc(DAG.getEntryNode()), 5856 MFI->getArgInfo().WorkItemIDZ); 5857 case Intrinsic::amdgcn_wavefrontsize: 5858 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5859 SDLoc(Op), MVT::i32); 5860 case Intrinsic::amdgcn_s_buffer_load: { 5861 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5862 SDValue GLC; 5863 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5864 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5865 IsGFX10 ? &DLC : nullptr)) 5866 return Op; 5867 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5868 DAG); 5869 } 5870 case Intrinsic::amdgcn_fdiv_fast: 5871 return lowerFDIV_FAST(Op, DAG); 5872 case Intrinsic::amdgcn_sin: 5873 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5874 5875 case Intrinsic::amdgcn_cos: 5876 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5877 5878 case Intrinsic::amdgcn_mul_u24: 5879 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5880 case Intrinsic::amdgcn_mul_i24: 5881 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5882 5883 case Intrinsic::amdgcn_log_clamp: { 5884 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5885 return SDValue(); 5886 5887 DiagnosticInfoUnsupported BadIntrin( 5888 MF.getFunction(), "intrinsic not supported on subtarget", 5889 DL.getDebugLoc()); 5890 DAG.getContext()->diagnose(BadIntrin); 5891 return DAG.getUNDEF(VT); 5892 } 5893 case Intrinsic::amdgcn_ldexp: 5894 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5895 Op.getOperand(1), Op.getOperand(2)); 5896 5897 case Intrinsic::amdgcn_fract: 5898 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5899 5900 case Intrinsic::amdgcn_class: 5901 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5902 Op.getOperand(1), Op.getOperand(2)); 5903 case Intrinsic::amdgcn_div_fmas: 5904 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5905 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5906 Op.getOperand(4)); 5907 5908 case Intrinsic::amdgcn_div_fixup: 5909 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5910 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5911 5912 case Intrinsic::amdgcn_trig_preop: 5913 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5914 Op.getOperand(1), Op.getOperand(2)); 5915 case Intrinsic::amdgcn_div_scale: { 5916 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5917 5918 // Translate to the operands expected by the machine instruction. The 5919 // first parameter must be the same as the first instruction. 5920 SDValue Numerator = Op.getOperand(1); 5921 SDValue Denominator = Op.getOperand(2); 5922 5923 // Note this order is opposite of the machine instruction's operations, 5924 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5925 // intrinsic has the numerator as the first operand to match a normal 5926 // division operation. 5927 5928 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5929 5930 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5931 Denominator, Numerator); 5932 } 5933 case Intrinsic::amdgcn_icmp: { 5934 // There is a Pat that handles this variant, so return it as-is. 5935 if (Op.getOperand(1).getValueType() == MVT::i1 && 5936 Op.getConstantOperandVal(2) == 0 && 5937 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5938 return Op; 5939 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5940 } 5941 case Intrinsic::amdgcn_fcmp: { 5942 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5943 } 5944 case Intrinsic::amdgcn_fmed3: 5945 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5946 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5947 case Intrinsic::amdgcn_fdot2: 5948 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5949 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5950 Op.getOperand(4)); 5951 case Intrinsic::amdgcn_fmul_legacy: 5952 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5953 Op.getOperand(1), Op.getOperand(2)); 5954 case Intrinsic::amdgcn_sffbh: 5955 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5956 case Intrinsic::amdgcn_sbfe: 5957 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5958 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5959 case Intrinsic::amdgcn_ubfe: 5960 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5961 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5962 case Intrinsic::amdgcn_cvt_pkrtz: 5963 case Intrinsic::amdgcn_cvt_pknorm_i16: 5964 case Intrinsic::amdgcn_cvt_pknorm_u16: 5965 case Intrinsic::amdgcn_cvt_pk_i16: 5966 case Intrinsic::amdgcn_cvt_pk_u16: { 5967 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5968 EVT VT = Op.getValueType(); 5969 unsigned Opcode; 5970 5971 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5972 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5973 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5974 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5975 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5976 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5977 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5978 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5979 else 5980 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5981 5982 if (isTypeLegal(VT)) 5983 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5984 5985 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5986 Op.getOperand(1), Op.getOperand(2)); 5987 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5988 } 5989 case Intrinsic::amdgcn_fmad_ftz: 5990 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5991 Op.getOperand(2), Op.getOperand(3)); 5992 5993 case Intrinsic::amdgcn_if_break: 5994 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5995 Op->getOperand(1), Op->getOperand(2)), 0); 5996 5997 case Intrinsic::amdgcn_groupstaticsize: { 5998 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 5999 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6000 return Op; 6001 6002 const Module *M = MF.getFunction().getParent(); 6003 const GlobalValue *GV = 6004 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6005 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6006 SIInstrInfo::MO_ABS32_LO); 6007 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6008 } 6009 case Intrinsic::amdgcn_is_shared: 6010 case Intrinsic::amdgcn_is_private: { 6011 SDLoc SL(Op); 6012 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6013 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6014 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6015 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6016 Op.getOperand(1)); 6017 6018 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6019 DAG.getConstant(1, SL, MVT::i32)); 6020 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6021 } 6022 case Intrinsic::amdgcn_alignbit: 6023 return DAG.getNode(ISD::FSHR, DL, VT, 6024 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6025 default: 6026 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6027 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6028 return lowerImage(Op, ImageDimIntr, DAG); 6029 6030 return Op; 6031 } 6032 } 6033 6034 // This function computes an appropriate offset to pass to 6035 // MachineMemOperand::setOffset() based on the offset inputs to 6036 // an intrinsic. If any of the offsets are non-contstant or 6037 // if VIndex is non-zero then this function returns 0. Otherwise, 6038 // it returns the sum of VOffset, SOffset, and Offset. 6039 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6040 SDValue SOffset, 6041 SDValue Offset, 6042 SDValue VIndex = SDValue()) { 6043 6044 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6045 !isa<ConstantSDNode>(Offset)) 6046 return 0; 6047 6048 if (VIndex) { 6049 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6050 return 0; 6051 } 6052 6053 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6054 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6055 cast<ConstantSDNode>(Offset)->getSExtValue(); 6056 } 6057 6058 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6059 switch (MF.getFunction().getCallingConv()) { 6060 case CallingConv::AMDGPU_PS: 6061 return 1; 6062 case CallingConv::AMDGPU_VS: 6063 return 2; 6064 case CallingConv::AMDGPU_GS: 6065 return 3; 6066 case CallingConv::AMDGPU_HS: 6067 case CallingConv::AMDGPU_LS: 6068 case CallingConv::AMDGPU_ES: 6069 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6070 case CallingConv::AMDGPU_CS: 6071 case CallingConv::AMDGPU_KERNEL: 6072 case CallingConv::C: 6073 case CallingConv::Fast: 6074 default: 6075 // Assume other calling conventions are various compute callable functions 6076 return 0; 6077 } 6078 } 6079 6080 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6081 SelectionDAG &DAG) const { 6082 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6083 SDLoc DL(Op); 6084 6085 switch (IntrID) { 6086 case Intrinsic::amdgcn_ds_ordered_add: 6087 case Intrinsic::amdgcn_ds_ordered_swap: { 6088 MemSDNode *M = cast<MemSDNode>(Op); 6089 SDValue Chain = M->getOperand(0); 6090 SDValue M0 = M->getOperand(2); 6091 SDValue Value = M->getOperand(3); 6092 unsigned IndexOperand = M->getConstantOperandVal(7); 6093 unsigned WaveRelease = M->getConstantOperandVal(8); 6094 unsigned WaveDone = M->getConstantOperandVal(9); 6095 6096 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6097 IndexOperand &= ~0x3f; 6098 unsigned CountDw = 0; 6099 6100 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6101 CountDw = (IndexOperand >> 24) & 0xf; 6102 IndexOperand &= ~(0xf << 24); 6103 6104 if (CountDw < 1 || CountDw > 4) { 6105 report_fatal_error( 6106 "ds_ordered_count: dword count must be between 1 and 4"); 6107 } 6108 } 6109 6110 if (IndexOperand) 6111 report_fatal_error("ds_ordered_count: bad index operand"); 6112 6113 if (WaveDone && !WaveRelease) 6114 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6115 6116 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6117 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6118 unsigned Offset0 = OrderedCountIndex << 2; 6119 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6120 (Instruction << 4); 6121 6122 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6123 Offset1 |= (CountDw - 1) << 6; 6124 6125 unsigned Offset = Offset0 | (Offset1 << 8); 6126 6127 SDValue Ops[] = { 6128 Chain, 6129 Value, 6130 DAG.getTargetConstant(Offset, DL, MVT::i16), 6131 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6132 }; 6133 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6134 M->getVTList(), Ops, M->getMemoryVT(), 6135 M->getMemOperand()); 6136 } 6137 case Intrinsic::amdgcn_ds_fadd: { 6138 MemSDNode *M = cast<MemSDNode>(Op); 6139 unsigned Opc; 6140 switch (IntrID) { 6141 case Intrinsic::amdgcn_ds_fadd: 6142 Opc = ISD::ATOMIC_LOAD_FADD; 6143 break; 6144 } 6145 6146 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6147 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6148 M->getMemOperand()); 6149 } 6150 case Intrinsic::amdgcn_atomic_inc: 6151 case Intrinsic::amdgcn_atomic_dec: 6152 case Intrinsic::amdgcn_ds_fmin: 6153 case Intrinsic::amdgcn_ds_fmax: { 6154 MemSDNode *M = cast<MemSDNode>(Op); 6155 unsigned Opc; 6156 switch (IntrID) { 6157 case Intrinsic::amdgcn_atomic_inc: 6158 Opc = AMDGPUISD::ATOMIC_INC; 6159 break; 6160 case Intrinsic::amdgcn_atomic_dec: 6161 Opc = AMDGPUISD::ATOMIC_DEC; 6162 break; 6163 case Intrinsic::amdgcn_ds_fmin: 6164 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6165 break; 6166 case Intrinsic::amdgcn_ds_fmax: 6167 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6168 break; 6169 default: 6170 llvm_unreachable("Unknown intrinsic!"); 6171 } 6172 SDValue Ops[] = { 6173 M->getOperand(0), // Chain 6174 M->getOperand(2), // Ptr 6175 M->getOperand(3) // Value 6176 }; 6177 6178 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6179 M->getMemoryVT(), M->getMemOperand()); 6180 } 6181 case Intrinsic::amdgcn_buffer_load: 6182 case Intrinsic::amdgcn_buffer_load_format: { 6183 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6184 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6185 unsigned IdxEn = 1; 6186 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6187 IdxEn = Idx->getZExtValue() != 0; 6188 SDValue Ops[] = { 6189 Op.getOperand(0), // Chain 6190 Op.getOperand(2), // rsrc 6191 Op.getOperand(3), // vindex 6192 SDValue(), // voffset -- will be set by setBufferOffsets 6193 SDValue(), // soffset -- will be set by setBufferOffsets 6194 SDValue(), // offset -- will be set by setBufferOffsets 6195 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6196 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6197 }; 6198 6199 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6200 // We don't know the offset if vindex is non-zero, so clear it. 6201 if (IdxEn) 6202 Offset = 0; 6203 6204 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6205 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6206 6207 EVT VT = Op.getValueType(); 6208 EVT IntVT = VT.changeTypeToInteger(); 6209 auto *M = cast<MemSDNode>(Op); 6210 M->getMemOperand()->setOffset(Offset); 6211 EVT LoadVT = Op.getValueType(); 6212 6213 if (LoadVT.getScalarType() == MVT::f16) 6214 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6215 M, DAG, Ops); 6216 6217 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6218 if (LoadVT.getScalarType() == MVT::i8 || 6219 LoadVT.getScalarType() == MVT::i16) 6220 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6221 6222 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6223 M->getMemOperand(), DAG); 6224 } 6225 case Intrinsic::amdgcn_raw_buffer_load: 6226 case Intrinsic::amdgcn_raw_buffer_load_format: { 6227 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6228 6229 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6230 SDValue Ops[] = { 6231 Op.getOperand(0), // Chain 6232 Op.getOperand(2), // rsrc 6233 DAG.getConstant(0, DL, MVT::i32), // vindex 6234 Offsets.first, // voffset 6235 Op.getOperand(4), // soffset 6236 Offsets.second, // offset 6237 Op.getOperand(5), // cachepolicy, swizzled buffer 6238 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6239 }; 6240 6241 auto *M = cast<MemSDNode>(Op); 6242 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6243 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6244 } 6245 case Intrinsic::amdgcn_struct_buffer_load: 6246 case Intrinsic::amdgcn_struct_buffer_load_format: { 6247 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6248 6249 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6250 SDValue Ops[] = { 6251 Op.getOperand(0), // Chain 6252 Op.getOperand(2), // rsrc 6253 Op.getOperand(3), // vindex 6254 Offsets.first, // voffset 6255 Op.getOperand(5), // soffset 6256 Offsets.second, // offset 6257 Op.getOperand(6), // cachepolicy, swizzled buffer 6258 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6259 }; 6260 6261 auto *M = cast<MemSDNode>(Op); 6262 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6263 Ops[2])); 6264 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6265 } 6266 case Intrinsic::amdgcn_tbuffer_load: { 6267 MemSDNode *M = cast<MemSDNode>(Op); 6268 EVT LoadVT = Op.getValueType(); 6269 6270 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6271 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6272 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6273 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6274 unsigned IdxEn = 1; 6275 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6276 IdxEn = Idx->getZExtValue() != 0; 6277 SDValue Ops[] = { 6278 Op.getOperand(0), // Chain 6279 Op.getOperand(2), // rsrc 6280 Op.getOperand(3), // vindex 6281 Op.getOperand(4), // voffset 6282 Op.getOperand(5), // soffset 6283 Op.getOperand(6), // offset 6284 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6285 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6286 DAG.getTargetConstant(IdxEn, 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_raw_tbuffer_load: { 6297 MemSDNode *M = cast<MemSDNode>(Op); 6298 EVT LoadVT = Op.getValueType(); 6299 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6300 6301 SDValue Ops[] = { 6302 Op.getOperand(0), // Chain 6303 Op.getOperand(2), // rsrc 6304 DAG.getConstant(0, DL, MVT::i32), // vindex 6305 Offsets.first, // voffset 6306 Op.getOperand(4), // soffset 6307 Offsets.second, // offset 6308 Op.getOperand(5), // format 6309 Op.getOperand(6), // cachepolicy, swizzled buffer 6310 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6311 }; 6312 6313 if (LoadVT.getScalarType() == MVT::f16) 6314 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6315 M, DAG, Ops); 6316 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6317 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6318 DAG); 6319 } 6320 case Intrinsic::amdgcn_struct_tbuffer_load: { 6321 MemSDNode *M = cast<MemSDNode>(Op); 6322 EVT LoadVT = Op.getValueType(); 6323 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6324 6325 SDValue Ops[] = { 6326 Op.getOperand(0), // Chain 6327 Op.getOperand(2), // rsrc 6328 Op.getOperand(3), // vindex 6329 Offsets.first, // voffset 6330 Op.getOperand(5), // soffset 6331 Offsets.second, // offset 6332 Op.getOperand(6), // format 6333 Op.getOperand(7), // cachepolicy, swizzled buffer 6334 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6335 }; 6336 6337 if (LoadVT.getScalarType() == MVT::f16) 6338 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6339 M, DAG, Ops); 6340 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6341 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6342 DAG); 6343 } 6344 case Intrinsic::amdgcn_buffer_atomic_swap: 6345 case Intrinsic::amdgcn_buffer_atomic_add: 6346 case Intrinsic::amdgcn_buffer_atomic_sub: 6347 case Intrinsic::amdgcn_buffer_atomic_smin: 6348 case Intrinsic::amdgcn_buffer_atomic_umin: 6349 case Intrinsic::amdgcn_buffer_atomic_smax: 6350 case Intrinsic::amdgcn_buffer_atomic_umax: 6351 case Intrinsic::amdgcn_buffer_atomic_and: 6352 case Intrinsic::amdgcn_buffer_atomic_or: 6353 case Intrinsic::amdgcn_buffer_atomic_xor: { 6354 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6355 unsigned IdxEn = 1; 6356 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6357 IdxEn = Idx->getZExtValue() != 0; 6358 SDValue Ops[] = { 6359 Op.getOperand(0), // Chain 6360 Op.getOperand(2), // vdata 6361 Op.getOperand(3), // rsrc 6362 Op.getOperand(4), // vindex 6363 SDValue(), // voffset -- will be set by setBufferOffsets 6364 SDValue(), // soffset -- will be set by setBufferOffsets 6365 SDValue(), // offset -- will be set by setBufferOffsets 6366 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6367 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6368 }; 6369 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6370 // We don't know the offset if vindex is non-zero, so clear it. 6371 if (IdxEn) 6372 Offset = 0; 6373 EVT VT = Op.getValueType(); 6374 6375 auto *M = cast<MemSDNode>(Op); 6376 M->getMemOperand()->setOffset(Offset); 6377 unsigned Opcode = 0; 6378 6379 switch (IntrID) { 6380 case Intrinsic::amdgcn_buffer_atomic_swap: 6381 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6382 break; 6383 case Intrinsic::amdgcn_buffer_atomic_add: 6384 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6385 break; 6386 case Intrinsic::amdgcn_buffer_atomic_sub: 6387 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6388 break; 6389 case Intrinsic::amdgcn_buffer_atomic_smin: 6390 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6391 break; 6392 case Intrinsic::amdgcn_buffer_atomic_umin: 6393 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6394 break; 6395 case Intrinsic::amdgcn_buffer_atomic_smax: 6396 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6397 break; 6398 case Intrinsic::amdgcn_buffer_atomic_umax: 6399 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6400 break; 6401 case Intrinsic::amdgcn_buffer_atomic_and: 6402 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6403 break; 6404 case Intrinsic::amdgcn_buffer_atomic_or: 6405 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6406 break; 6407 case Intrinsic::amdgcn_buffer_atomic_xor: 6408 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6409 break; 6410 default: 6411 llvm_unreachable("unhandled atomic opcode"); 6412 } 6413 6414 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6415 M->getMemOperand()); 6416 } 6417 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6418 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6419 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6420 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6421 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6422 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6423 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6424 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6425 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6426 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6427 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6428 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6429 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6430 SDValue Ops[] = { 6431 Op.getOperand(0), // Chain 6432 Op.getOperand(2), // vdata 6433 Op.getOperand(3), // rsrc 6434 DAG.getConstant(0, DL, MVT::i32), // vindex 6435 Offsets.first, // voffset 6436 Op.getOperand(5), // soffset 6437 Offsets.second, // offset 6438 Op.getOperand(6), // cachepolicy 6439 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6440 }; 6441 EVT VT = Op.getValueType(); 6442 6443 auto *M = cast<MemSDNode>(Op); 6444 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6445 unsigned Opcode = 0; 6446 6447 switch (IntrID) { 6448 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6449 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6450 break; 6451 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6452 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6453 break; 6454 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6455 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6456 break; 6457 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6458 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6459 break; 6460 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6461 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6462 break; 6463 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6464 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6465 break; 6466 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6467 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6468 break; 6469 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6470 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6471 break; 6472 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6473 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6474 break; 6475 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6476 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6477 break; 6478 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6479 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6480 break; 6481 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6482 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6483 break; 6484 default: 6485 llvm_unreachable("unhandled atomic opcode"); 6486 } 6487 6488 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6489 M->getMemOperand()); 6490 } 6491 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6492 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6493 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6494 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6495 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6496 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6497 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6498 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6499 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6500 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6501 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6502 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6503 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6504 SDValue Ops[] = { 6505 Op.getOperand(0), // Chain 6506 Op.getOperand(2), // vdata 6507 Op.getOperand(3), // rsrc 6508 Op.getOperand(4), // vindex 6509 Offsets.first, // voffset 6510 Op.getOperand(6), // soffset 6511 Offsets.second, // offset 6512 Op.getOperand(7), // cachepolicy 6513 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6514 }; 6515 EVT VT = Op.getValueType(); 6516 6517 auto *M = cast<MemSDNode>(Op); 6518 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6519 Ops[3])); 6520 unsigned Opcode = 0; 6521 6522 switch (IntrID) { 6523 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6524 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6525 break; 6526 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6527 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6528 break; 6529 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6530 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6531 break; 6532 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6533 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6534 break; 6535 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6536 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6537 break; 6538 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6539 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6540 break; 6541 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6542 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6543 break; 6544 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6545 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6546 break; 6547 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6548 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6549 break; 6550 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6551 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6552 break; 6553 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6554 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6555 break; 6556 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6557 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6558 break; 6559 default: 6560 llvm_unreachable("unhandled atomic opcode"); 6561 } 6562 6563 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6564 M->getMemOperand()); 6565 } 6566 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6567 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6568 unsigned IdxEn = 1; 6569 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6570 IdxEn = Idx->getZExtValue() != 0; 6571 SDValue Ops[] = { 6572 Op.getOperand(0), // Chain 6573 Op.getOperand(2), // src 6574 Op.getOperand(3), // cmp 6575 Op.getOperand(4), // rsrc 6576 Op.getOperand(5), // vindex 6577 SDValue(), // voffset -- will be set by setBufferOffsets 6578 SDValue(), // soffset -- will be set by setBufferOffsets 6579 SDValue(), // offset -- will be set by setBufferOffsets 6580 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6581 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6582 }; 6583 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6584 // We don't know the offset if vindex is non-zero, so clear it. 6585 if (IdxEn) 6586 Offset = 0; 6587 EVT VT = Op.getValueType(); 6588 auto *M = cast<MemSDNode>(Op); 6589 M->getMemOperand()->setOffset(Offset); 6590 6591 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6592 Op->getVTList(), Ops, VT, M->getMemOperand()); 6593 } 6594 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6595 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6596 SDValue Ops[] = { 6597 Op.getOperand(0), // Chain 6598 Op.getOperand(2), // src 6599 Op.getOperand(3), // cmp 6600 Op.getOperand(4), // rsrc 6601 DAG.getConstant(0, DL, MVT::i32), // vindex 6602 Offsets.first, // voffset 6603 Op.getOperand(6), // soffset 6604 Offsets.second, // offset 6605 Op.getOperand(7), // cachepolicy 6606 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6607 }; 6608 EVT VT = Op.getValueType(); 6609 auto *M = cast<MemSDNode>(Op); 6610 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6611 6612 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6613 Op->getVTList(), Ops, VT, M->getMemOperand()); 6614 } 6615 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6616 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6617 SDValue Ops[] = { 6618 Op.getOperand(0), // Chain 6619 Op.getOperand(2), // src 6620 Op.getOperand(3), // cmp 6621 Op.getOperand(4), // rsrc 6622 Op.getOperand(5), // vindex 6623 Offsets.first, // voffset 6624 Op.getOperand(7), // soffset 6625 Offsets.second, // offset 6626 Op.getOperand(8), // cachepolicy 6627 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6628 }; 6629 EVT VT = Op.getValueType(); 6630 auto *M = cast<MemSDNode>(Op); 6631 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6632 Ops[4])); 6633 6634 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6635 Op->getVTList(), Ops, VT, M->getMemOperand()); 6636 } 6637 6638 default: 6639 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6640 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6641 return lowerImage(Op, ImageDimIntr, DAG); 6642 6643 return SDValue(); 6644 } 6645 } 6646 6647 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6648 // dwordx4 if on SI. 6649 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6650 SDVTList VTList, 6651 ArrayRef<SDValue> Ops, EVT MemVT, 6652 MachineMemOperand *MMO, 6653 SelectionDAG &DAG) const { 6654 EVT VT = VTList.VTs[0]; 6655 EVT WidenedVT = VT; 6656 EVT WidenedMemVT = MemVT; 6657 if (!Subtarget->hasDwordx3LoadStores() && 6658 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6659 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6660 WidenedVT.getVectorElementType(), 4); 6661 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6662 WidenedMemVT.getVectorElementType(), 4); 6663 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6664 } 6665 6666 assert(VTList.NumVTs == 2); 6667 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6668 6669 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6670 WidenedMemVT, MMO); 6671 if (WidenedVT != VT) { 6672 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6673 DAG.getVectorIdxConstant(0, DL)); 6674 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6675 } 6676 return NewOp; 6677 } 6678 6679 SDValue SITargetLowering::handleD16VData(SDValue VData, 6680 SelectionDAG &DAG) const { 6681 EVT StoreVT = VData.getValueType(); 6682 6683 // No change for f16 and legal vector D16 types. 6684 if (!StoreVT.isVector()) 6685 return VData; 6686 6687 SDLoc DL(VData); 6688 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6689 6690 if (Subtarget->hasUnpackedD16VMem()) { 6691 // We need to unpack the packed data to store. 6692 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6693 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6694 6695 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6696 StoreVT.getVectorNumElements()); 6697 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6698 return DAG.UnrollVectorOp(ZExt.getNode()); 6699 } 6700 6701 assert(isTypeLegal(StoreVT)); 6702 return VData; 6703 } 6704 6705 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6706 SelectionDAG &DAG) const { 6707 SDLoc DL(Op); 6708 SDValue Chain = Op.getOperand(0); 6709 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6710 MachineFunction &MF = DAG.getMachineFunction(); 6711 6712 switch (IntrinsicID) { 6713 case Intrinsic::amdgcn_exp_compr: { 6714 SDValue Src0 = Op.getOperand(4); 6715 SDValue Src1 = Op.getOperand(5); 6716 // Hack around illegal type on SI by directly selecting it. 6717 if (isTypeLegal(Src0.getValueType())) 6718 return SDValue(); 6719 6720 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6721 SDValue Undef = DAG.getUNDEF(MVT::f32); 6722 const SDValue Ops[] = { 6723 Op.getOperand(2), // tgt 6724 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6725 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6726 Undef, // src2 6727 Undef, // src3 6728 Op.getOperand(7), // vm 6729 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6730 Op.getOperand(3), // en 6731 Op.getOperand(0) // Chain 6732 }; 6733 6734 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6735 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6736 } 6737 case Intrinsic::amdgcn_s_barrier: { 6738 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6739 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6740 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6741 if (WGSize <= ST.getWavefrontSize()) 6742 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6743 Op.getOperand(0)), 0); 6744 } 6745 return SDValue(); 6746 }; 6747 case Intrinsic::amdgcn_tbuffer_store: { 6748 SDValue VData = Op.getOperand(2); 6749 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6750 if (IsD16) 6751 VData = handleD16VData(VData, DAG); 6752 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6753 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6754 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6755 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6756 unsigned IdxEn = 1; 6757 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6758 IdxEn = Idx->getZExtValue() != 0; 6759 SDValue Ops[] = { 6760 Chain, 6761 VData, // vdata 6762 Op.getOperand(3), // rsrc 6763 Op.getOperand(4), // vindex 6764 Op.getOperand(5), // voffset 6765 Op.getOperand(6), // soffset 6766 Op.getOperand(7), // offset 6767 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6768 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6769 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6770 }; 6771 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6772 AMDGPUISD::TBUFFER_STORE_FORMAT; 6773 MemSDNode *M = cast<MemSDNode>(Op); 6774 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6775 M->getMemoryVT(), M->getMemOperand()); 6776 } 6777 6778 case Intrinsic::amdgcn_struct_tbuffer_store: { 6779 SDValue VData = Op.getOperand(2); 6780 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6781 if (IsD16) 6782 VData = handleD16VData(VData, DAG); 6783 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6784 SDValue Ops[] = { 6785 Chain, 6786 VData, // vdata 6787 Op.getOperand(3), // rsrc 6788 Op.getOperand(4), // vindex 6789 Offsets.first, // voffset 6790 Op.getOperand(6), // soffset 6791 Offsets.second, // offset 6792 Op.getOperand(7), // format 6793 Op.getOperand(8), // cachepolicy, swizzled buffer 6794 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6795 }; 6796 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6797 AMDGPUISD::TBUFFER_STORE_FORMAT; 6798 MemSDNode *M = cast<MemSDNode>(Op); 6799 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6800 M->getMemoryVT(), M->getMemOperand()); 6801 } 6802 6803 case Intrinsic::amdgcn_raw_tbuffer_store: { 6804 SDValue VData = Op.getOperand(2); 6805 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6806 if (IsD16) 6807 VData = handleD16VData(VData, DAG); 6808 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6809 SDValue Ops[] = { 6810 Chain, 6811 VData, // vdata 6812 Op.getOperand(3), // rsrc 6813 DAG.getConstant(0, DL, MVT::i32), // vindex 6814 Offsets.first, // voffset 6815 Op.getOperand(5), // soffset 6816 Offsets.second, // offset 6817 Op.getOperand(6), // format 6818 Op.getOperand(7), // cachepolicy, swizzled buffer 6819 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6820 }; 6821 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6822 AMDGPUISD::TBUFFER_STORE_FORMAT; 6823 MemSDNode *M = cast<MemSDNode>(Op); 6824 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6825 M->getMemoryVT(), M->getMemOperand()); 6826 } 6827 6828 case Intrinsic::amdgcn_buffer_store: 6829 case Intrinsic::amdgcn_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 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6835 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6836 unsigned IdxEn = 1; 6837 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6838 IdxEn = Idx->getZExtValue() != 0; 6839 SDValue Ops[] = { 6840 Chain, 6841 VData, 6842 Op.getOperand(3), // rsrc 6843 Op.getOperand(4), // vindex 6844 SDValue(), // voffset -- will be set by setBufferOffsets 6845 SDValue(), // soffset -- will be set by setBufferOffsets 6846 SDValue(), // offset -- will be set by setBufferOffsets 6847 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6848 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6849 }; 6850 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6851 // We don't know the offset if vindex is non-zero, so clear it. 6852 if (IdxEn) 6853 Offset = 0; 6854 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6855 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6856 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6857 MemSDNode *M = cast<MemSDNode>(Op); 6858 M->getMemOperand()->setOffset(Offset); 6859 6860 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6861 EVT VDataType = VData.getValueType().getScalarType(); 6862 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6863 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6864 6865 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6866 M->getMemoryVT(), M->getMemOperand()); 6867 } 6868 6869 case Intrinsic::amdgcn_raw_buffer_store: 6870 case Intrinsic::amdgcn_raw_buffer_store_format: { 6871 const bool IsFormat = 6872 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6873 6874 SDValue VData = Op.getOperand(2); 6875 EVT VDataVT = VData.getValueType(); 6876 EVT EltType = VDataVT.getScalarType(); 6877 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6878 if (IsD16) 6879 VData = handleD16VData(VData, DAG); 6880 6881 if (!isTypeLegal(VDataVT)) { 6882 VData = 6883 DAG.getNode(ISD::BITCAST, DL, 6884 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6885 } 6886 6887 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6888 SDValue Ops[] = { 6889 Chain, 6890 VData, 6891 Op.getOperand(3), // rsrc 6892 DAG.getConstant(0, DL, MVT::i32), // vindex 6893 Offsets.first, // voffset 6894 Op.getOperand(5), // soffset 6895 Offsets.second, // offset 6896 Op.getOperand(6), // cachepolicy, swizzled buffer 6897 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6898 }; 6899 unsigned Opc = 6900 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6901 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6902 MemSDNode *M = cast<MemSDNode>(Op); 6903 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6904 6905 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6906 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6907 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 6908 6909 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6910 M->getMemoryVT(), M->getMemOperand()); 6911 } 6912 6913 case Intrinsic::amdgcn_struct_buffer_store: 6914 case Intrinsic::amdgcn_struct_buffer_store_format: { 6915 const bool IsFormat = 6916 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 6917 6918 SDValue VData = Op.getOperand(2); 6919 EVT VDataVT = VData.getValueType(); 6920 EVT EltType = VDataVT.getScalarType(); 6921 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6922 6923 if (IsD16) 6924 VData = handleD16VData(VData, DAG); 6925 6926 if (!isTypeLegal(VDataVT)) { 6927 VData = 6928 DAG.getNode(ISD::BITCAST, DL, 6929 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6930 } 6931 6932 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6933 SDValue Ops[] = { 6934 Chain, 6935 VData, 6936 Op.getOperand(3), // rsrc 6937 Op.getOperand(4), // vindex 6938 Offsets.first, // voffset 6939 Op.getOperand(6), // soffset 6940 Offsets.second, // offset 6941 Op.getOperand(7), // cachepolicy, swizzled buffer 6942 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6943 }; 6944 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6945 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6946 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6947 MemSDNode *M = cast<MemSDNode>(Op); 6948 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6949 Ops[3])); 6950 6951 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6952 EVT VDataType = VData.getValueType().getScalarType(); 6953 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6954 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6955 6956 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6957 M->getMemoryVT(), M->getMemOperand()); 6958 } 6959 6960 case Intrinsic::amdgcn_buffer_atomic_fadd: { 6961 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6962 unsigned IdxEn = 1; 6963 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6964 IdxEn = Idx->getZExtValue() != 0; 6965 SDValue Ops[] = { 6966 Chain, 6967 Op.getOperand(2), // vdata 6968 Op.getOperand(3), // rsrc 6969 Op.getOperand(4), // vindex 6970 SDValue(), // voffset -- will be set by setBufferOffsets 6971 SDValue(), // soffset -- will be set by setBufferOffsets 6972 SDValue(), // offset -- will be set by setBufferOffsets 6973 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6974 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6975 }; 6976 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6977 // We don't know the offset if vindex is non-zero, so clear it. 6978 if (IdxEn) 6979 Offset = 0; 6980 EVT VT = Op.getOperand(2).getValueType(); 6981 6982 auto *M = cast<MemSDNode>(Op); 6983 M->getMemOperand()->setOffset(Offset); 6984 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 6985 : AMDGPUISD::BUFFER_ATOMIC_FADD; 6986 6987 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6988 M->getMemOperand()); 6989 } 6990 6991 case Intrinsic::amdgcn_global_atomic_fadd: { 6992 SDValue Ops[] = { 6993 Chain, 6994 Op.getOperand(2), // ptr 6995 Op.getOperand(3) // vdata 6996 }; 6997 EVT VT = Op.getOperand(3).getValueType(); 6998 6999 auto *M = cast<MemSDNode>(Op); 7000 if (VT.isVector()) { 7001 return DAG.getMemIntrinsicNode( 7002 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7003 M->getMemOperand()); 7004 } 7005 7006 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7007 DAG.getVTList(VT, MVT::Other), Ops, 7008 M->getMemOperand()).getValue(1); 7009 } 7010 case Intrinsic::amdgcn_end_cf: 7011 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7012 Op->getOperand(2), Chain), 0); 7013 7014 default: { 7015 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7016 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7017 return lowerImage(Op, ImageDimIntr, DAG); 7018 7019 return Op; 7020 } 7021 } 7022 } 7023 7024 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7025 // offset (the offset that is included in bounds checking and swizzling, to be 7026 // split between the instruction's voffset and immoffset fields) and soffset 7027 // (the offset that is excluded from bounds checking and swizzling, to go in 7028 // the instruction's soffset field). This function takes the first kind of 7029 // offset and figures out how to split it between voffset and immoffset. 7030 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7031 SDValue Offset, SelectionDAG &DAG) const { 7032 SDLoc DL(Offset); 7033 const unsigned MaxImm = 4095; 7034 SDValue N0 = Offset; 7035 ConstantSDNode *C1 = nullptr; 7036 7037 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7038 N0 = SDValue(); 7039 else if (DAG.isBaseWithConstantOffset(N0)) { 7040 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7041 N0 = N0.getOperand(0); 7042 } 7043 7044 if (C1) { 7045 unsigned ImmOffset = C1->getZExtValue(); 7046 // If the immediate value is too big for the immoffset field, put the value 7047 // and -4096 into the immoffset field so that the value that is copied/added 7048 // for the voffset field is a multiple of 4096, and it stands more chance 7049 // of being CSEd with the copy/add for another similar load/store. 7050 // However, do not do that rounding down to a multiple of 4096 if that is a 7051 // negative number, as it appears to be illegal to have a negative offset 7052 // in the vgpr, even if adding the immediate offset makes it positive. 7053 unsigned Overflow = ImmOffset & ~MaxImm; 7054 ImmOffset -= Overflow; 7055 if ((int32_t)Overflow < 0) { 7056 Overflow += ImmOffset; 7057 ImmOffset = 0; 7058 } 7059 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7060 if (Overflow) { 7061 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7062 if (!N0) 7063 N0 = OverflowVal; 7064 else { 7065 SDValue Ops[] = { N0, OverflowVal }; 7066 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7067 } 7068 } 7069 } 7070 if (!N0) 7071 N0 = DAG.getConstant(0, DL, MVT::i32); 7072 if (!C1) 7073 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7074 return {N0, SDValue(C1, 0)}; 7075 } 7076 7077 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7078 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7079 // pointed to by Offsets. 7080 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7081 SelectionDAG &DAG, SDValue *Offsets, 7082 unsigned Align) const { 7083 SDLoc DL(CombinedOffset); 7084 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7085 uint32_t Imm = C->getZExtValue(); 7086 uint32_t SOffset, ImmOffset; 7087 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7088 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7089 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7090 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7091 return SOffset + ImmOffset; 7092 } 7093 } 7094 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7095 SDValue N0 = CombinedOffset.getOperand(0); 7096 SDValue N1 = CombinedOffset.getOperand(1); 7097 uint32_t SOffset, ImmOffset; 7098 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7099 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7100 Subtarget, Align)) { 7101 Offsets[0] = N0; 7102 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7103 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7104 return 0; 7105 } 7106 } 7107 Offsets[0] = CombinedOffset; 7108 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7109 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7110 return 0; 7111 } 7112 7113 // Handle 8 bit and 16 bit buffer loads 7114 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7115 EVT LoadVT, SDLoc DL, 7116 ArrayRef<SDValue> Ops, 7117 MemSDNode *M) const { 7118 EVT IntVT = LoadVT.changeTypeToInteger(); 7119 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7120 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7121 7122 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7123 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7124 Ops, IntVT, 7125 M->getMemOperand()); 7126 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7127 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7128 7129 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7130 } 7131 7132 // Handle 8 bit and 16 bit buffer stores 7133 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7134 EVT VDataType, SDLoc DL, 7135 SDValue Ops[], 7136 MemSDNode *M) const { 7137 if (VDataType == MVT::f16) 7138 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7139 7140 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7141 Ops[1] = BufferStoreExt; 7142 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7143 AMDGPUISD::BUFFER_STORE_SHORT; 7144 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7145 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7146 M->getMemOperand()); 7147 } 7148 7149 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7150 ISD::LoadExtType ExtType, SDValue Op, 7151 const SDLoc &SL, EVT VT) { 7152 if (VT.bitsLT(Op.getValueType())) 7153 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7154 7155 switch (ExtType) { 7156 case ISD::SEXTLOAD: 7157 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7158 case ISD::ZEXTLOAD: 7159 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7160 case ISD::EXTLOAD: 7161 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7162 case ISD::NON_EXTLOAD: 7163 return Op; 7164 } 7165 7166 llvm_unreachable("invalid ext type"); 7167 } 7168 7169 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7170 SelectionDAG &DAG = DCI.DAG; 7171 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7172 return SDValue(); 7173 7174 // FIXME: Constant loads should all be marked invariant. 7175 unsigned AS = Ld->getAddressSpace(); 7176 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7177 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7178 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7179 return SDValue(); 7180 7181 // Don't do this early, since it may interfere with adjacent load merging for 7182 // illegal types. We can avoid losing alignment information for exotic types 7183 // pre-legalize. 7184 EVT MemVT = Ld->getMemoryVT(); 7185 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7186 MemVT.getSizeInBits() >= 32) 7187 return SDValue(); 7188 7189 SDLoc SL(Ld); 7190 7191 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7192 "unexpected vector extload"); 7193 7194 // TODO: Drop only high part of range. 7195 SDValue Ptr = Ld->getBasePtr(); 7196 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7197 MVT::i32, SL, Ld->getChain(), Ptr, 7198 Ld->getOffset(), 7199 Ld->getPointerInfo(), MVT::i32, 7200 Ld->getAlignment(), 7201 Ld->getMemOperand()->getFlags(), 7202 Ld->getAAInfo(), 7203 nullptr); // Drop ranges 7204 7205 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7206 if (MemVT.isFloatingPoint()) { 7207 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7208 "unexpected fp extload"); 7209 TruncVT = MemVT.changeTypeToInteger(); 7210 } 7211 7212 SDValue Cvt = NewLoad; 7213 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7214 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7215 DAG.getValueType(TruncVT)); 7216 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7217 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7218 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7219 } else { 7220 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7221 } 7222 7223 EVT VT = Ld->getValueType(0); 7224 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7225 7226 DCI.AddToWorklist(Cvt.getNode()); 7227 7228 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7229 // the appropriate extension from the 32-bit load. 7230 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7231 DCI.AddToWorklist(Cvt.getNode()); 7232 7233 // Handle conversion back to floating point if necessary. 7234 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7235 7236 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7237 } 7238 7239 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7240 SDLoc DL(Op); 7241 LoadSDNode *Load = cast<LoadSDNode>(Op); 7242 ISD::LoadExtType ExtType = Load->getExtensionType(); 7243 EVT MemVT = Load->getMemoryVT(); 7244 7245 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7246 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7247 return SDValue(); 7248 7249 // FIXME: Copied from PPC 7250 // First, load into 32 bits, then truncate to 1 bit. 7251 7252 SDValue Chain = Load->getChain(); 7253 SDValue BasePtr = Load->getBasePtr(); 7254 MachineMemOperand *MMO = Load->getMemOperand(); 7255 7256 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7257 7258 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7259 BasePtr, RealMemVT, MMO); 7260 7261 if (!MemVT.isVector()) { 7262 SDValue Ops[] = { 7263 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7264 NewLD.getValue(1) 7265 }; 7266 7267 return DAG.getMergeValues(Ops, DL); 7268 } 7269 7270 SmallVector<SDValue, 3> Elts; 7271 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7272 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7273 DAG.getConstant(I, DL, MVT::i32)); 7274 7275 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7276 } 7277 7278 SDValue Ops[] = { 7279 DAG.getBuildVector(MemVT, DL, Elts), 7280 NewLD.getValue(1) 7281 }; 7282 7283 return DAG.getMergeValues(Ops, DL); 7284 } 7285 7286 if (!MemVT.isVector()) 7287 return SDValue(); 7288 7289 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7290 "Custom lowering for non-i32 vectors hasn't been implemented."); 7291 7292 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7293 MemVT, *Load->getMemOperand())) { 7294 SDValue Ops[2]; 7295 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7296 return DAG.getMergeValues(Ops, DL); 7297 } 7298 7299 unsigned Alignment = Load->getAlignment(); 7300 unsigned AS = Load->getAddressSpace(); 7301 if (Subtarget->hasLDSMisalignedBug() && 7302 AS == AMDGPUAS::FLAT_ADDRESS && 7303 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7304 return SplitVectorLoad(Op, DAG); 7305 } 7306 7307 MachineFunction &MF = DAG.getMachineFunction(); 7308 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7309 // If there is a possibilty that flat instruction access scratch memory 7310 // then we need to use the same legalization rules we use for private. 7311 if (AS == AMDGPUAS::FLAT_ADDRESS && 7312 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7313 AS = MFI->hasFlatScratchInit() ? 7314 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7315 7316 unsigned NumElements = MemVT.getVectorNumElements(); 7317 7318 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7319 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7320 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7321 if (MemVT.isPow2VectorType()) 7322 return SDValue(); 7323 if (NumElements == 3) 7324 return WidenVectorLoad(Op, DAG); 7325 return SplitVectorLoad(Op, DAG); 7326 } 7327 // Non-uniform loads will be selected to MUBUF instructions, so they 7328 // have the same legalization requirements as global and private 7329 // loads. 7330 // 7331 } 7332 7333 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7334 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7335 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7336 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7337 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7338 Alignment >= 4 && NumElements < 32) { 7339 if (MemVT.isPow2VectorType()) 7340 return SDValue(); 7341 if (NumElements == 3) 7342 return WidenVectorLoad(Op, DAG); 7343 return SplitVectorLoad(Op, DAG); 7344 } 7345 // Non-uniform loads will be selected to MUBUF instructions, so they 7346 // have the same legalization requirements as global and private 7347 // loads. 7348 // 7349 } 7350 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7351 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7352 AS == AMDGPUAS::GLOBAL_ADDRESS || 7353 AS == AMDGPUAS::FLAT_ADDRESS) { 7354 if (NumElements > 4) 7355 return SplitVectorLoad(Op, DAG); 7356 // v3 loads not supported on SI. 7357 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7358 return WidenVectorLoad(Op, DAG); 7359 // v3 and v4 loads are supported for private and global memory. 7360 return SDValue(); 7361 } 7362 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7363 // Depending on the setting of the private_element_size field in the 7364 // resource descriptor, we can only make private accesses up to a certain 7365 // size. 7366 switch (Subtarget->getMaxPrivateElementSize()) { 7367 case 4: { 7368 SDValue Ops[2]; 7369 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7370 return DAG.getMergeValues(Ops, DL); 7371 } 7372 case 8: 7373 if (NumElements > 2) 7374 return SplitVectorLoad(Op, DAG); 7375 return SDValue(); 7376 case 16: 7377 // Same as global/flat 7378 if (NumElements > 4) 7379 return SplitVectorLoad(Op, DAG); 7380 // v3 loads not supported on SI. 7381 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7382 return WidenVectorLoad(Op, DAG); 7383 return SDValue(); 7384 default: 7385 llvm_unreachable("unsupported private_element_size"); 7386 } 7387 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7388 // Use ds_read_b128 if possible. 7389 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7390 MemVT.getStoreSize() == 16) 7391 return SDValue(); 7392 7393 if (NumElements > 2) 7394 return SplitVectorLoad(Op, DAG); 7395 7396 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7397 // address is negative, then the instruction is incorrectly treated as 7398 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7399 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7400 // load later in the SILoadStoreOptimizer. 7401 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7402 NumElements == 2 && MemVT.getStoreSize() == 8 && 7403 Load->getAlignment() < 8) { 7404 return SplitVectorLoad(Op, DAG); 7405 } 7406 } 7407 return SDValue(); 7408 } 7409 7410 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7411 EVT VT = Op.getValueType(); 7412 assert(VT.getSizeInBits() == 64); 7413 7414 SDLoc DL(Op); 7415 SDValue Cond = Op.getOperand(0); 7416 7417 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7418 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7419 7420 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7421 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7422 7423 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7424 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7425 7426 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7427 7428 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7429 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7430 7431 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7432 7433 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7434 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7435 } 7436 7437 // Catch division cases where we can use shortcuts with rcp and rsq 7438 // instructions. 7439 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7440 SelectionDAG &DAG) const { 7441 SDLoc SL(Op); 7442 SDValue LHS = Op.getOperand(0); 7443 SDValue RHS = Op.getOperand(1); 7444 EVT VT = Op.getValueType(); 7445 const SDNodeFlags Flags = Op->getFlags(); 7446 7447 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7448 Flags.hasApproximateFuncs(); 7449 7450 // Without !fpmath accuracy information, we can't do more because we don't 7451 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7452 if (!AllowInaccurateRcp) 7453 return SDValue(); 7454 7455 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7456 if (CLHS->isExactlyValue(1.0)) { 7457 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7458 // the CI documentation has a worst case error of 1 ulp. 7459 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7460 // use it as long as we aren't trying to use denormals. 7461 // 7462 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7463 7464 // 1.0 / sqrt(x) -> rsq(x) 7465 7466 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7467 // error seems really high at 2^29 ULP. 7468 if (RHS.getOpcode() == ISD::FSQRT) 7469 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7470 7471 // 1.0 / x -> rcp(x) 7472 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7473 } 7474 7475 // Same as for 1.0, but expand the sign out of the constant. 7476 if (CLHS->isExactlyValue(-1.0)) { 7477 // -1.0 / x -> rcp (fneg x) 7478 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7479 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7480 } 7481 } 7482 7483 // Turn into multiply by the reciprocal. 7484 // x / y -> x * (1.0 / y) 7485 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7486 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7487 } 7488 7489 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7490 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7491 if (GlueChain->getNumValues() <= 1) { 7492 return DAG.getNode(Opcode, SL, VT, A, B); 7493 } 7494 7495 assert(GlueChain->getNumValues() == 3); 7496 7497 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7498 switch (Opcode) { 7499 default: llvm_unreachable("no chain equivalent for opcode"); 7500 case ISD::FMUL: 7501 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7502 break; 7503 } 7504 7505 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7506 GlueChain.getValue(2)); 7507 } 7508 7509 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7510 EVT VT, SDValue A, SDValue B, SDValue C, 7511 SDValue GlueChain) { 7512 if (GlueChain->getNumValues() <= 1) { 7513 return DAG.getNode(Opcode, SL, VT, A, B, C); 7514 } 7515 7516 assert(GlueChain->getNumValues() == 3); 7517 7518 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7519 switch (Opcode) { 7520 default: llvm_unreachable("no chain equivalent for opcode"); 7521 case ISD::FMA: 7522 Opcode = AMDGPUISD::FMA_W_CHAIN; 7523 break; 7524 } 7525 7526 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7527 GlueChain.getValue(2)); 7528 } 7529 7530 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7531 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7532 return FastLowered; 7533 7534 SDLoc SL(Op); 7535 SDValue Src0 = Op.getOperand(0); 7536 SDValue Src1 = Op.getOperand(1); 7537 7538 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7539 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7540 7541 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7542 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7543 7544 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7545 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7546 7547 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7548 } 7549 7550 // Faster 2.5 ULP division that does not support denormals. 7551 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7552 SDLoc SL(Op); 7553 SDValue LHS = Op.getOperand(1); 7554 SDValue RHS = Op.getOperand(2); 7555 7556 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7557 7558 const APFloat K0Val(BitsToFloat(0x6f800000)); 7559 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7560 7561 const APFloat K1Val(BitsToFloat(0x2f800000)); 7562 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7563 7564 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7565 7566 EVT SetCCVT = 7567 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7568 7569 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7570 7571 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7572 7573 // TODO: Should this propagate fast-math-flags? 7574 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7575 7576 // rcp does not support denormals. 7577 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7578 7579 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7580 7581 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7582 } 7583 7584 // Returns immediate value for setting the F32 denorm mode when using the 7585 // S_DENORM_MODE instruction. 7586 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7587 const SDLoc &SL, const GCNSubtarget *ST) { 7588 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7589 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7590 ? FP_DENORM_FLUSH_NONE 7591 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7592 7593 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7594 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7595 } 7596 7597 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7598 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7599 return FastLowered; 7600 7601 SDLoc SL(Op); 7602 SDValue LHS = Op.getOperand(0); 7603 SDValue RHS = Op.getOperand(1); 7604 7605 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7606 7607 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7608 7609 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7610 RHS, RHS, LHS); 7611 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7612 LHS, RHS, LHS); 7613 7614 // Denominator is scaled to not be denormal, so using rcp is ok. 7615 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7616 DenominatorScaled); 7617 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7618 DenominatorScaled); 7619 7620 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7621 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7622 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7623 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7624 7625 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7626 7627 if (!HasFP32Denormals) { 7628 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7629 7630 SDValue EnableDenorm; 7631 if (Subtarget->hasDenormModeInst()) { 7632 const SDValue EnableDenormValue = 7633 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7634 7635 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7636 DAG.getEntryNode(), EnableDenormValue); 7637 } else { 7638 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7639 SL, MVT::i32); 7640 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7641 DAG.getEntryNode(), EnableDenormValue, 7642 BitField); 7643 } 7644 7645 SDValue Ops[3] = { 7646 NegDivScale0, 7647 EnableDenorm.getValue(0), 7648 EnableDenorm.getValue(1) 7649 }; 7650 7651 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7652 } 7653 7654 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7655 ApproxRcp, One, NegDivScale0); 7656 7657 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7658 ApproxRcp, Fma0); 7659 7660 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7661 Fma1, Fma1); 7662 7663 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7664 NumeratorScaled, Mul); 7665 7666 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7667 7668 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7669 NumeratorScaled, Fma3); 7670 7671 if (!HasFP32Denormals) { 7672 SDValue DisableDenorm; 7673 if (Subtarget->hasDenormModeInst()) { 7674 const SDValue DisableDenormValue = 7675 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7676 7677 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7678 Fma4.getValue(1), DisableDenormValue, 7679 Fma4.getValue(2)); 7680 } else { 7681 const SDValue DisableDenormValue = 7682 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7683 7684 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7685 Fma4.getValue(1), DisableDenormValue, 7686 BitField, Fma4.getValue(2)); 7687 } 7688 7689 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7690 DisableDenorm, DAG.getRoot()); 7691 DAG.setRoot(OutputChain); 7692 } 7693 7694 SDValue Scale = NumeratorScaled.getValue(1); 7695 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7696 Fma4, Fma1, Fma3, Scale); 7697 7698 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7699 } 7700 7701 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7702 if (DAG.getTarget().Options.UnsafeFPMath) 7703 return lowerFastUnsafeFDIV(Op, DAG); 7704 7705 SDLoc SL(Op); 7706 SDValue X = Op.getOperand(0); 7707 SDValue Y = Op.getOperand(1); 7708 7709 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7710 7711 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7712 7713 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7714 7715 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7716 7717 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7718 7719 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7720 7721 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7722 7723 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7724 7725 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7726 7727 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7728 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7729 7730 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7731 NegDivScale0, Mul, DivScale1); 7732 7733 SDValue Scale; 7734 7735 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7736 // Workaround a hardware bug on SI where the condition output from div_scale 7737 // is not usable. 7738 7739 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7740 7741 // Figure out if the scale to use for div_fmas. 7742 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7743 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7744 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7745 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7746 7747 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7748 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7749 7750 SDValue Scale0Hi 7751 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7752 SDValue Scale1Hi 7753 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7754 7755 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7756 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7757 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7758 } else { 7759 Scale = DivScale1.getValue(1); 7760 } 7761 7762 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7763 Fma4, Fma3, Mul, Scale); 7764 7765 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7766 } 7767 7768 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7769 EVT VT = Op.getValueType(); 7770 7771 if (VT == MVT::f32) 7772 return LowerFDIV32(Op, DAG); 7773 7774 if (VT == MVT::f64) 7775 return LowerFDIV64(Op, DAG); 7776 7777 if (VT == MVT::f16) 7778 return LowerFDIV16(Op, DAG); 7779 7780 llvm_unreachable("Unexpected type for fdiv"); 7781 } 7782 7783 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7784 SDLoc DL(Op); 7785 StoreSDNode *Store = cast<StoreSDNode>(Op); 7786 EVT VT = Store->getMemoryVT(); 7787 7788 if (VT == MVT::i1) { 7789 return DAG.getTruncStore(Store->getChain(), DL, 7790 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7791 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7792 } 7793 7794 assert(VT.isVector() && 7795 Store->getValue().getValueType().getScalarType() == MVT::i32); 7796 7797 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7798 VT, *Store->getMemOperand())) { 7799 return expandUnalignedStore(Store, DAG); 7800 } 7801 7802 unsigned AS = Store->getAddressSpace(); 7803 if (Subtarget->hasLDSMisalignedBug() && 7804 AS == AMDGPUAS::FLAT_ADDRESS && 7805 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7806 return SplitVectorStore(Op, DAG); 7807 } 7808 7809 MachineFunction &MF = DAG.getMachineFunction(); 7810 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7811 // If there is a possibilty that flat instruction access scratch memory 7812 // then we need to use the same legalization rules we use for private. 7813 if (AS == AMDGPUAS::FLAT_ADDRESS && 7814 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7815 AS = MFI->hasFlatScratchInit() ? 7816 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7817 7818 unsigned NumElements = VT.getVectorNumElements(); 7819 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7820 AS == AMDGPUAS::FLAT_ADDRESS) { 7821 if (NumElements > 4) 7822 return SplitVectorStore(Op, DAG); 7823 // v3 stores not supported on SI. 7824 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7825 return SplitVectorStore(Op, DAG); 7826 return SDValue(); 7827 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7828 switch (Subtarget->getMaxPrivateElementSize()) { 7829 case 4: 7830 return scalarizeVectorStore(Store, DAG); 7831 case 8: 7832 if (NumElements > 2) 7833 return SplitVectorStore(Op, DAG); 7834 return SDValue(); 7835 case 16: 7836 if (NumElements > 4 || NumElements == 3) 7837 return SplitVectorStore(Op, DAG); 7838 return SDValue(); 7839 default: 7840 llvm_unreachable("unsupported private_element_size"); 7841 } 7842 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7843 // Use ds_write_b128 if possible. 7844 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7845 VT.getStoreSize() == 16 && NumElements != 3) 7846 return SDValue(); 7847 7848 if (NumElements > 2) 7849 return SplitVectorStore(Op, DAG); 7850 7851 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7852 // address is negative, then the instruction is incorrectly treated as 7853 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7854 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7855 // store later in the SILoadStoreOptimizer. 7856 if (!Subtarget->hasUsableDSOffset() && 7857 NumElements == 2 && VT.getStoreSize() == 8 && 7858 Store->getAlignment() < 8) { 7859 return SplitVectorStore(Op, DAG); 7860 } 7861 7862 return SDValue(); 7863 } else { 7864 llvm_unreachable("unhandled address space"); 7865 } 7866 } 7867 7868 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7869 SDLoc DL(Op); 7870 EVT VT = Op.getValueType(); 7871 SDValue Arg = Op.getOperand(0); 7872 SDValue TrigVal; 7873 7874 // TODO: Should this propagate fast-math-flags? 7875 7876 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7877 7878 if (Subtarget->hasTrigReducedRange()) { 7879 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7880 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7881 } else { 7882 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7883 } 7884 7885 switch (Op.getOpcode()) { 7886 case ISD::FCOS: 7887 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7888 case ISD::FSIN: 7889 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7890 default: 7891 llvm_unreachable("Wrong trig opcode"); 7892 } 7893 } 7894 7895 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7896 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7897 assert(AtomicNode->isCompareAndSwap()); 7898 unsigned AS = AtomicNode->getAddressSpace(); 7899 7900 // No custom lowering required for local address space 7901 if (!isFlatGlobalAddrSpace(AS)) 7902 return Op; 7903 7904 // Non-local address space requires custom lowering for atomic compare 7905 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7906 SDLoc DL(Op); 7907 SDValue ChainIn = Op.getOperand(0); 7908 SDValue Addr = Op.getOperand(1); 7909 SDValue Old = Op.getOperand(2); 7910 SDValue New = Op.getOperand(3); 7911 EVT VT = Op.getValueType(); 7912 MVT SimpleVT = VT.getSimpleVT(); 7913 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7914 7915 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7916 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7917 7918 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7919 Ops, VT, AtomicNode->getMemOperand()); 7920 } 7921 7922 //===----------------------------------------------------------------------===// 7923 // Custom DAG optimizations 7924 //===----------------------------------------------------------------------===// 7925 7926 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7927 DAGCombinerInfo &DCI) const { 7928 EVT VT = N->getValueType(0); 7929 EVT ScalarVT = VT.getScalarType(); 7930 if (ScalarVT != MVT::f32) 7931 return SDValue(); 7932 7933 SelectionDAG &DAG = DCI.DAG; 7934 SDLoc DL(N); 7935 7936 SDValue Src = N->getOperand(0); 7937 EVT SrcVT = Src.getValueType(); 7938 7939 // TODO: We could try to match extracting the higher bytes, which would be 7940 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7941 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7942 // about in practice. 7943 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7944 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7945 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7946 DCI.AddToWorklist(Cvt.getNode()); 7947 return Cvt; 7948 } 7949 } 7950 7951 return SDValue(); 7952 } 7953 7954 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7955 7956 // This is a variant of 7957 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7958 // 7959 // The normal DAG combiner will do this, but only if the add has one use since 7960 // that would increase the number of instructions. 7961 // 7962 // This prevents us from seeing a constant offset that can be folded into a 7963 // memory instruction's addressing mode. If we know the resulting add offset of 7964 // a pointer can be folded into an addressing offset, we can replace the pointer 7965 // operand with the add of new constant offset. This eliminates one of the uses, 7966 // and may allow the remaining use to also be simplified. 7967 // 7968 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7969 unsigned AddrSpace, 7970 EVT MemVT, 7971 DAGCombinerInfo &DCI) const { 7972 SDValue N0 = N->getOperand(0); 7973 SDValue N1 = N->getOperand(1); 7974 7975 // We only do this to handle cases where it's profitable when there are 7976 // multiple uses of the add, so defer to the standard combine. 7977 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7978 N0->hasOneUse()) 7979 return SDValue(); 7980 7981 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7982 if (!CN1) 7983 return SDValue(); 7984 7985 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7986 if (!CAdd) 7987 return SDValue(); 7988 7989 // If the resulting offset is too large, we can't fold it into the addressing 7990 // mode offset. 7991 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7992 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7993 7994 AddrMode AM; 7995 AM.HasBaseReg = true; 7996 AM.BaseOffs = Offset.getSExtValue(); 7997 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7998 return SDValue(); 7999 8000 SelectionDAG &DAG = DCI.DAG; 8001 SDLoc SL(N); 8002 EVT VT = N->getValueType(0); 8003 8004 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8005 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8006 8007 SDNodeFlags Flags; 8008 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8009 (N0.getOpcode() == ISD::OR || 8010 N0->getFlags().hasNoUnsignedWrap())); 8011 8012 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8013 } 8014 8015 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8016 DAGCombinerInfo &DCI) const { 8017 SDValue Ptr = N->getBasePtr(); 8018 SelectionDAG &DAG = DCI.DAG; 8019 SDLoc SL(N); 8020 8021 // TODO: We could also do this for multiplies. 8022 if (Ptr.getOpcode() == ISD::SHL) { 8023 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8024 N->getMemoryVT(), DCI); 8025 if (NewPtr) { 8026 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8027 8028 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8029 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8030 } 8031 } 8032 8033 return SDValue(); 8034 } 8035 8036 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8037 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8038 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8039 (Opc == ISD::XOR && Val == 0); 8040 } 8041 8042 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8043 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8044 // integer combine opportunities since most 64-bit operations are decomposed 8045 // this way. TODO: We won't want this for SALU especially if it is an inline 8046 // immediate. 8047 SDValue SITargetLowering::splitBinaryBitConstantOp( 8048 DAGCombinerInfo &DCI, 8049 const SDLoc &SL, 8050 unsigned Opc, SDValue LHS, 8051 const ConstantSDNode *CRHS) const { 8052 uint64_t Val = CRHS->getZExtValue(); 8053 uint32_t ValLo = Lo_32(Val); 8054 uint32_t ValHi = Hi_32(Val); 8055 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8056 8057 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8058 bitOpWithConstantIsReducible(Opc, ValHi)) || 8059 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8060 // If we need to materialize a 64-bit immediate, it will be split up later 8061 // anyway. Avoid creating the harder to understand 64-bit immediate 8062 // materialization. 8063 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8064 } 8065 8066 return SDValue(); 8067 } 8068 8069 // Returns true if argument is a boolean value which is not serialized into 8070 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8071 static bool isBoolSGPR(SDValue V) { 8072 if (V.getValueType() != MVT::i1) 8073 return false; 8074 switch (V.getOpcode()) { 8075 default: break; 8076 case ISD::SETCC: 8077 case ISD::AND: 8078 case ISD::OR: 8079 case ISD::XOR: 8080 case AMDGPUISD::FP_CLASS: 8081 return true; 8082 } 8083 return false; 8084 } 8085 8086 // If a constant has all zeroes or all ones within each byte return it. 8087 // Otherwise return 0. 8088 static uint32_t getConstantPermuteMask(uint32_t C) { 8089 // 0xff for any zero byte in the mask 8090 uint32_t ZeroByteMask = 0; 8091 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8092 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8093 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8094 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8095 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8096 if ((NonZeroByteMask & C) != NonZeroByteMask) 8097 return 0; // Partial bytes selected. 8098 return C; 8099 } 8100 8101 // Check if a node selects whole bytes from its operand 0 starting at a byte 8102 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8103 // or -1 if not succeeded. 8104 // Note byte select encoding: 8105 // value 0-3 selects corresponding source byte; 8106 // value 0xc selects zero; 8107 // value 0xff selects 0xff. 8108 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8109 assert(V.getValueSizeInBits() == 32); 8110 8111 if (V.getNumOperands() != 2) 8112 return ~0; 8113 8114 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8115 if (!N1) 8116 return ~0; 8117 8118 uint32_t C = N1->getZExtValue(); 8119 8120 switch (V.getOpcode()) { 8121 default: 8122 break; 8123 case ISD::AND: 8124 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8125 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8126 } 8127 break; 8128 8129 case ISD::OR: 8130 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8131 return (0x03020100 & ~ConstMask) | ConstMask; 8132 } 8133 break; 8134 8135 case ISD::SHL: 8136 if (C % 8) 8137 return ~0; 8138 8139 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8140 8141 case ISD::SRL: 8142 if (C % 8) 8143 return ~0; 8144 8145 return uint32_t(0x0c0c0c0c03020100ull >> C); 8146 } 8147 8148 return ~0; 8149 } 8150 8151 SDValue SITargetLowering::performAndCombine(SDNode *N, 8152 DAGCombinerInfo &DCI) const { 8153 if (DCI.isBeforeLegalize()) 8154 return SDValue(); 8155 8156 SelectionDAG &DAG = DCI.DAG; 8157 EVT VT = N->getValueType(0); 8158 SDValue LHS = N->getOperand(0); 8159 SDValue RHS = N->getOperand(1); 8160 8161 8162 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8163 if (VT == MVT::i64 && CRHS) { 8164 if (SDValue Split 8165 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8166 return Split; 8167 } 8168 8169 if (CRHS && VT == MVT::i32) { 8170 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8171 // nb = number of trailing zeroes in mask 8172 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8173 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8174 uint64_t Mask = CRHS->getZExtValue(); 8175 unsigned Bits = countPopulation(Mask); 8176 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8177 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8178 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8179 unsigned Shift = CShift->getZExtValue(); 8180 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8181 unsigned Offset = NB + Shift; 8182 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8183 SDLoc SL(N); 8184 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8185 LHS->getOperand(0), 8186 DAG.getConstant(Offset, SL, MVT::i32), 8187 DAG.getConstant(Bits, SL, MVT::i32)); 8188 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8189 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8190 DAG.getValueType(NarrowVT)); 8191 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8192 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8193 return Shl; 8194 } 8195 } 8196 } 8197 8198 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8199 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8200 isa<ConstantSDNode>(LHS.getOperand(2))) { 8201 uint32_t Sel = getConstantPermuteMask(Mask); 8202 if (!Sel) 8203 return SDValue(); 8204 8205 // Select 0xc for all zero bytes 8206 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8207 SDLoc DL(N); 8208 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8209 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8210 } 8211 } 8212 8213 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8214 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8215 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8216 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8217 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8218 8219 SDValue X = LHS.getOperand(0); 8220 SDValue Y = RHS.getOperand(0); 8221 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8222 return SDValue(); 8223 8224 if (LCC == ISD::SETO) { 8225 if (X != LHS.getOperand(1)) 8226 return SDValue(); 8227 8228 if (RCC == ISD::SETUNE) { 8229 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8230 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8231 return SDValue(); 8232 8233 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8234 SIInstrFlags::N_SUBNORMAL | 8235 SIInstrFlags::N_ZERO | 8236 SIInstrFlags::P_ZERO | 8237 SIInstrFlags::P_SUBNORMAL | 8238 SIInstrFlags::P_NORMAL; 8239 8240 static_assert(((~(SIInstrFlags::S_NAN | 8241 SIInstrFlags::Q_NAN | 8242 SIInstrFlags::N_INFINITY | 8243 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8244 "mask not equal"); 8245 8246 SDLoc DL(N); 8247 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8248 X, DAG.getConstant(Mask, DL, MVT::i32)); 8249 } 8250 } 8251 } 8252 8253 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8254 std::swap(LHS, RHS); 8255 8256 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8257 RHS.hasOneUse()) { 8258 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8259 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8260 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8261 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8262 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8263 (RHS.getOperand(0) == LHS.getOperand(0) && 8264 LHS.getOperand(0) == LHS.getOperand(1))) { 8265 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8266 unsigned NewMask = LCC == ISD::SETO ? 8267 Mask->getZExtValue() & ~OrdMask : 8268 Mask->getZExtValue() & OrdMask; 8269 8270 SDLoc DL(N); 8271 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8272 DAG.getConstant(NewMask, DL, MVT::i32)); 8273 } 8274 } 8275 8276 if (VT == MVT::i32 && 8277 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8278 // and x, (sext cc from i1) => select cc, x, 0 8279 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8280 std::swap(LHS, RHS); 8281 if (isBoolSGPR(RHS.getOperand(0))) 8282 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8283 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8284 } 8285 8286 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8287 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8288 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8289 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8290 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8291 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8292 if (LHSMask != ~0u && RHSMask != ~0u) { 8293 // Canonicalize the expression in an attempt to have fewer unique masks 8294 // and therefore fewer registers used to hold the masks. 8295 if (LHSMask > RHSMask) { 8296 std::swap(LHSMask, RHSMask); 8297 std::swap(LHS, RHS); 8298 } 8299 8300 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8301 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8302 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8303 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8304 8305 // Check of we need to combine values from two sources within a byte. 8306 if (!(LHSUsedLanes & RHSUsedLanes) && 8307 // If we select high and lower word keep it for SDWA. 8308 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8309 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8310 // Each byte in each mask is either selector mask 0-3, or has higher 8311 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8312 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8313 // mask which is not 0xff wins. By anding both masks we have a correct 8314 // result except that 0x0c shall be corrected to give 0x0c only. 8315 uint32_t Mask = LHSMask & RHSMask; 8316 for (unsigned I = 0; I < 32; I += 8) { 8317 uint32_t ByteSel = 0xff << I; 8318 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8319 Mask &= (0x0c << I) & 0xffffffff; 8320 } 8321 8322 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8323 // or 0x0c. 8324 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8325 SDLoc DL(N); 8326 8327 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8328 LHS.getOperand(0), RHS.getOperand(0), 8329 DAG.getConstant(Sel, DL, MVT::i32)); 8330 } 8331 } 8332 } 8333 8334 return SDValue(); 8335 } 8336 8337 SDValue SITargetLowering::performOrCombine(SDNode *N, 8338 DAGCombinerInfo &DCI) const { 8339 SelectionDAG &DAG = DCI.DAG; 8340 SDValue LHS = N->getOperand(0); 8341 SDValue RHS = N->getOperand(1); 8342 8343 EVT VT = N->getValueType(0); 8344 if (VT == MVT::i1) { 8345 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8346 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8347 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8348 SDValue Src = LHS.getOperand(0); 8349 if (Src != RHS.getOperand(0)) 8350 return SDValue(); 8351 8352 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8353 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8354 if (!CLHS || !CRHS) 8355 return SDValue(); 8356 8357 // Only 10 bits are used. 8358 static const uint32_t MaxMask = 0x3ff; 8359 8360 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8361 SDLoc DL(N); 8362 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8363 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8364 } 8365 8366 return SDValue(); 8367 } 8368 8369 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8370 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8371 LHS.getOpcode() == AMDGPUISD::PERM && 8372 isa<ConstantSDNode>(LHS.getOperand(2))) { 8373 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8374 if (!Sel) 8375 return SDValue(); 8376 8377 Sel |= LHS.getConstantOperandVal(2); 8378 SDLoc DL(N); 8379 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8380 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8381 } 8382 8383 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8384 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8385 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8386 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8387 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8388 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8389 if (LHSMask != ~0u && RHSMask != ~0u) { 8390 // Canonicalize the expression in an attempt to have fewer unique masks 8391 // and therefore fewer registers used to hold the masks. 8392 if (LHSMask > RHSMask) { 8393 std::swap(LHSMask, RHSMask); 8394 std::swap(LHS, RHS); 8395 } 8396 8397 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8398 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8399 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8400 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8401 8402 // Check of we need to combine values from two sources within a byte. 8403 if (!(LHSUsedLanes & RHSUsedLanes) && 8404 // If we select high and lower word keep it for SDWA. 8405 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8406 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8407 // Kill zero bytes selected by other mask. Zero value is 0xc. 8408 LHSMask &= ~RHSUsedLanes; 8409 RHSMask &= ~LHSUsedLanes; 8410 // Add 4 to each active LHS lane 8411 LHSMask |= LHSUsedLanes & 0x04040404; 8412 // Combine masks 8413 uint32_t Sel = LHSMask | RHSMask; 8414 SDLoc DL(N); 8415 8416 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8417 LHS.getOperand(0), RHS.getOperand(0), 8418 DAG.getConstant(Sel, DL, MVT::i32)); 8419 } 8420 } 8421 } 8422 8423 if (VT != MVT::i64) 8424 return SDValue(); 8425 8426 // TODO: This could be a generic combine with a predicate for extracting the 8427 // high half of an integer being free. 8428 8429 // (or i64:x, (zero_extend i32:y)) -> 8430 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8431 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8432 RHS.getOpcode() != ISD::ZERO_EXTEND) 8433 std::swap(LHS, RHS); 8434 8435 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8436 SDValue ExtSrc = RHS.getOperand(0); 8437 EVT SrcVT = ExtSrc.getValueType(); 8438 if (SrcVT == MVT::i32) { 8439 SDLoc SL(N); 8440 SDValue LowLHS, HiBits; 8441 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8442 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8443 8444 DCI.AddToWorklist(LowOr.getNode()); 8445 DCI.AddToWorklist(HiBits.getNode()); 8446 8447 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8448 LowOr, HiBits); 8449 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8450 } 8451 } 8452 8453 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8454 if (CRHS) { 8455 if (SDValue Split 8456 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8457 return Split; 8458 } 8459 8460 return SDValue(); 8461 } 8462 8463 SDValue SITargetLowering::performXorCombine(SDNode *N, 8464 DAGCombinerInfo &DCI) const { 8465 EVT VT = N->getValueType(0); 8466 if (VT != MVT::i64) 8467 return SDValue(); 8468 8469 SDValue LHS = N->getOperand(0); 8470 SDValue RHS = N->getOperand(1); 8471 8472 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8473 if (CRHS) { 8474 if (SDValue Split 8475 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8476 return Split; 8477 } 8478 8479 return SDValue(); 8480 } 8481 8482 // Instructions that will be lowered with a final instruction that zeros the 8483 // high result bits. 8484 // XXX - probably only need to list legal operations. 8485 static bool fp16SrcZerosHighBits(unsigned Opc) { 8486 switch (Opc) { 8487 case ISD::FADD: 8488 case ISD::FSUB: 8489 case ISD::FMUL: 8490 case ISD::FDIV: 8491 case ISD::FREM: 8492 case ISD::FMA: 8493 case ISD::FMAD: 8494 case ISD::FCANONICALIZE: 8495 case ISD::FP_ROUND: 8496 case ISD::UINT_TO_FP: 8497 case ISD::SINT_TO_FP: 8498 case ISD::FABS: 8499 // Fabs is lowered to a bit operation, but it's an and which will clear the 8500 // high bits anyway. 8501 case ISD::FSQRT: 8502 case ISD::FSIN: 8503 case ISD::FCOS: 8504 case ISD::FPOWI: 8505 case ISD::FPOW: 8506 case ISD::FLOG: 8507 case ISD::FLOG2: 8508 case ISD::FLOG10: 8509 case ISD::FEXP: 8510 case ISD::FEXP2: 8511 case ISD::FCEIL: 8512 case ISD::FTRUNC: 8513 case ISD::FRINT: 8514 case ISD::FNEARBYINT: 8515 case ISD::FROUND: 8516 case ISD::FFLOOR: 8517 case ISD::FMINNUM: 8518 case ISD::FMAXNUM: 8519 case AMDGPUISD::FRACT: 8520 case AMDGPUISD::CLAMP: 8521 case AMDGPUISD::COS_HW: 8522 case AMDGPUISD::SIN_HW: 8523 case AMDGPUISD::FMIN3: 8524 case AMDGPUISD::FMAX3: 8525 case AMDGPUISD::FMED3: 8526 case AMDGPUISD::FMAD_FTZ: 8527 case AMDGPUISD::RCP: 8528 case AMDGPUISD::RSQ: 8529 case AMDGPUISD::RCP_IFLAG: 8530 case AMDGPUISD::LDEXP: 8531 return true; 8532 default: 8533 // fcopysign, select and others may be lowered to 32-bit bit operations 8534 // which don't zero the high bits. 8535 return false; 8536 } 8537 } 8538 8539 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8540 DAGCombinerInfo &DCI) const { 8541 if (!Subtarget->has16BitInsts() || 8542 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8543 return SDValue(); 8544 8545 EVT VT = N->getValueType(0); 8546 if (VT != MVT::i32) 8547 return SDValue(); 8548 8549 SDValue Src = N->getOperand(0); 8550 if (Src.getValueType() != MVT::i16) 8551 return SDValue(); 8552 8553 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8554 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8555 if (Src.getOpcode() == ISD::BITCAST) { 8556 SDValue BCSrc = Src.getOperand(0); 8557 if (BCSrc.getValueType() == MVT::f16 && 8558 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8559 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8560 } 8561 8562 return SDValue(); 8563 } 8564 8565 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8566 DAGCombinerInfo &DCI) 8567 const { 8568 SDValue Src = N->getOperand(0); 8569 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8570 8571 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8572 VTSign->getVT() == MVT::i8) || 8573 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8574 VTSign->getVT() == MVT::i16)) && 8575 Src.hasOneUse()) { 8576 auto *M = cast<MemSDNode>(Src); 8577 SDValue Ops[] = { 8578 Src.getOperand(0), // Chain 8579 Src.getOperand(1), // rsrc 8580 Src.getOperand(2), // vindex 8581 Src.getOperand(3), // voffset 8582 Src.getOperand(4), // soffset 8583 Src.getOperand(5), // offset 8584 Src.getOperand(6), 8585 Src.getOperand(7) 8586 }; 8587 // replace with BUFFER_LOAD_BYTE/SHORT 8588 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8589 Src.getOperand(0).getValueType()); 8590 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8591 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8592 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8593 ResList, 8594 Ops, M->getMemoryVT(), 8595 M->getMemOperand()); 8596 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8597 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8598 } 8599 return SDValue(); 8600 } 8601 8602 SDValue SITargetLowering::performClassCombine(SDNode *N, 8603 DAGCombinerInfo &DCI) const { 8604 SelectionDAG &DAG = DCI.DAG; 8605 SDValue Mask = N->getOperand(1); 8606 8607 // fp_class x, 0 -> false 8608 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8609 if (CMask->isNullValue()) 8610 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8611 } 8612 8613 if (N->getOperand(0).isUndef()) 8614 return DAG.getUNDEF(MVT::i1); 8615 8616 return SDValue(); 8617 } 8618 8619 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8620 DAGCombinerInfo &DCI) const { 8621 EVT VT = N->getValueType(0); 8622 SDValue N0 = N->getOperand(0); 8623 8624 if (N0.isUndef()) 8625 return N0; 8626 8627 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8628 N0.getOpcode() == ISD::SINT_TO_FP)) { 8629 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8630 N->getFlags()); 8631 } 8632 8633 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8634 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8635 N0.getOperand(0), N->getFlags()); 8636 } 8637 8638 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8639 } 8640 8641 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8642 unsigned MaxDepth) const { 8643 unsigned Opcode = Op.getOpcode(); 8644 if (Opcode == ISD::FCANONICALIZE) 8645 return true; 8646 8647 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8648 auto F = CFP->getValueAPF(); 8649 if (F.isNaN() && F.isSignaling()) 8650 return false; 8651 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8652 } 8653 8654 // If source is a result of another standard FP operation it is already in 8655 // canonical form. 8656 if (MaxDepth == 0) 8657 return false; 8658 8659 switch (Opcode) { 8660 // These will flush denorms if required. 8661 case ISD::FADD: 8662 case ISD::FSUB: 8663 case ISD::FMUL: 8664 case ISD::FCEIL: 8665 case ISD::FFLOOR: 8666 case ISD::FMA: 8667 case ISD::FMAD: 8668 case ISD::FSQRT: 8669 case ISD::FDIV: 8670 case ISD::FREM: 8671 case ISD::FP_ROUND: 8672 case ISD::FP_EXTEND: 8673 case AMDGPUISD::FMUL_LEGACY: 8674 case AMDGPUISD::FMAD_FTZ: 8675 case AMDGPUISD::RCP: 8676 case AMDGPUISD::RSQ: 8677 case AMDGPUISD::RSQ_CLAMP: 8678 case AMDGPUISD::RCP_LEGACY: 8679 case AMDGPUISD::RSQ_LEGACY: 8680 case AMDGPUISD::RCP_IFLAG: 8681 case AMDGPUISD::TRIG_PREOP: 8682 case AMDGPUISD::DIV_SCALE: 8683 case AMDGPUISD::DIV_FMAS: 8684 case AMDGPUISD::DIV_FIXUP: 8685 case AMDGPUISD::FRACT: 8686 case AMDGPUISD::LDEXP: 8687 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8688 case AMDGPUISD::CVT_F32_UBYTE0: 8689 case AMDGPUISD::CVT_F32_UBYTE1: 8690 case AMDGPUISD::CVT_F32_UBYTE2: 8691 case AMDGPUISD::CVT_F32_UBYTE3: 8692 return true; 8693 8694 // It can/will be lowered or combined as a bit operation. 8695 // Need to check their input recursively to handle. 8696 case ISD::FNEG: 8697 case ISD::FABS: 8698 case ISD::FCOPYSIGN: 8699 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8700 8701 case ISD::FSIN: 8702 case ISD::FCOS: 8703 case ISD::FSINCOS: 8704 return Op.getValueType().getScalarType() != MVT::f16; 8705 8706 case ISD::FMINNUM: 8707 case ISD::FMAXNUM: 8708 case ISD::FMINNUM_IEEE: 8709 case ISD::FMAXNUM_IEEE: 8710 case AMDGPUISD::CLAMP: 8711 case AMDGPUISD::FMED3: 8712 case AMDGPUISD::FMAX3: 8713 case AMDGPUISD::FMIN3: { 8714 // FIXME: Shouldn't treat the generic operations different based these. 8715 // However, we aren't really required to flush the result from 8716 // minnum/maxnum.. 8717 8718 // snans will be quieted, so we only need to worry about denormals. 8719 if (Subtarget->supportsMinMaxDenormModes() || 8720 denormalsEnabledForType(DAG, Op.getValueType())) 8721 return true; 8722 8723 // Flushing may be required. 8724 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8725 // targets need to check their input recursively. 8726 8727 // FIXME: Does this apply with clamp? It's implemented with max. 8728 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8729 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8730 return false; 8731 } 8732 8733 return true; 8734 } 8735 case ISD::SELECT: { 8736 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8737 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8738 } 8739 case ISD::BUILD_VECTOR: { 8740 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8741 SDValue SrcOp = Op.getOperand(i); 8742 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8743 return false; 8744 } 8745 8746 return true; 8747 } 8748 case ISD::EXTRACT_VECTOR_ELT: 8749 case ISD::EXTRACT_SUBVECTOR: { 8750 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8751 } 8752 case ISD::INSERT_VECTOR_ELT: { 8753 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8754 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8755 } 8756 case ISD::UNDEF: 8757 // Could be anything. 8758 return false; 8759 8760 case ISD::BITCAST: { 8761 // Hack round the mess we make when legalizing extract_vector_elt 8762 SDValue Src = Op.getOperand(0); 8763 if (Src.getValueType() == MVT::i16 && 8764 Src.getOpcode() == ISD::TRUNCATE) { 8765 SDValue TruncSrc = Src.getOperand(0); 8766 if (TruncSrc.getValueType() == MVT::i32 && 8767 TruncSrc.getOpcode() == ISD::BITCAST && 8768 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8769 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8770 } 8771 } 8772 8773 return false; 8774 } 8775 case ISD::INTRINSIC_WO_CHAIN: { 8776 unsigned IntrinsicID 8777 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8778 // TODO: Handle more intrinsics 8779 switch (IntrinsicID) { 8780 case Intrinsic::amdgcn_cvt_pkrtz: 8781 case Intrinsic::amdgcn_cubeid: 8782 case Intrinsic::amdgcn_frexp_mant: 8783 case Intrinsic::amdgcn_fdot2: 8784 return true; 8785 default: 8786 break; 8787 } 8788 8789 LLVM_FALLTHROUGH; 8790 } 8791 default: 8792 return denormalsEnabledForType(DAG, Op.getValueType()) && 8793 DAG.isKnownNeverSNaN(Op); 8794 } 8795 8796 llvm_unreachable("invalid operation"); 8797 } 8798 8799 // Constant fold canonicalize. 8800 SDValue SITargetLowering::getCanonicalConstantFP( 8801 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8802 // Flush denormals to 0 if not enabled. 8803 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8804 return DAG.getConstantFP(0.0, SL, VT); 8805 8806 if (C.isNaN()) { 8807 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8808 if (C.isSignaling()) { 8809 // Quiet a signaling NaN. 8810 // FIXME: Is this supposed to preserve payload bits? 8811 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8812 } 8813 8814 // Make sure it is the canonical NaN bitpattern. 8815 // 8816 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8817 // immediate? 8818 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8819 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8820 } 8821 8822 // Already canonical. 8823 return DAG.getConstantFP(C, SL, VT); 8824 } 8825 8826 static bool vectorEltWillFoldAway(SDValue Op) { 8827 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8828 } 8829 8830 SDValue SITargetLowering::performFCanonicalizeCombine( 8831 SDNode *N, 8832 DAGCombinerInfo &DCI) const { 8833 SelectionDAG &DAG = DCI.DAG; 8834 SDValue N0 = N->getOperand(0); 8835 EVT VT = N->getValueType(0); 8836 8837 // fcanonicalize undef -> qnan 8838 if (N0.isUndef()) { 8839 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8840 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8841 } 8842 8843 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8844 EVT VT = N->getValueType(0); 8845 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8846 } 8847 8848 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8849 // (fcanonicalize k) 8850 // 8851 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8852 8853 // TODO: This could be better with wider vectors that will be split to v2f16, 8854 // and to consider uses since there aren't that many packed operations. 8855 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8856 isTypeLegal(MVT::v2f16)) { 8857 SDLoc SL(N); 8858 SDValue NewElts[2]; 8859 SDValue Lo = N0.getOperand(0); 8860 SDValue Hi = N0.getOperand(1); 8861 EVT EltVT = Lo.getValueType(); 8862 8863 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8864 for (unsigned I = 0; I != 2; ++I) { 8865 SDValue Op = N0.getOperand(I); 8866 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8867 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8868 CFP->getValueAPF()); 8869 } else if (Op.isUndef()) { 8870 // Handled below based on what the other operand is. 8871 NewElts[I] = Op; 8872 } else { 8873 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8874 } 8875 } 8876 8877 // If one half is undef, and one is constant, perfer a splat vector rather 8878 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8879 // cheaper to use and may be free with a packed operation. 8880 if (NewElts[0].isUndef()) { 8881 if (isa<ConstantFPSDNode>(NewElts[1])) 8882 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8883 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8884 } 8885 8886 if (NewElts[1].isUndef()) { 8887 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8888 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8889 } 8890 8891 return DAG.getBuildVector(VT, SL, NewElts); 8892 } 8893 } 8894 8895 unsigned SrcOpc = N0.getOpcode(); 8896 8897 // If it's free to do so, push canonicalizes further up the source, which may 8898 // find a canonical source. 8899 // 8900 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8901 // sNaNs. 8902 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8903 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8904 if (CRHS && N0.hasOneUse()) { 8905 SDLoc SL(N); 8906 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8907 N0.getOperand(0)); 8908 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8909 DCI.AddToWorklist(Canon0.getNode()); 8910 8911 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8912 } 8913 } 8914 8915 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8916 } 8917 8918 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8919 switch (Opc) { 8920 case ISD::FMAXNUM: 8921 case ISD::FMAXNUM_IEEE: 8922 return AMDGPUISD::FMAX3; 8923 case ISD::SMAX: 8924 return AMDGPUISD::SMAX3; 8925 case ISD::UMAX: 8926 return AMDGPUISD::UMAX3; 8927 case ISD::FMINNUM: 8928 case ISD::FMINNUM_IEEE: 8929 return AMDGPUISD::FMIN3; 8930 case ISD::SMIN: 8931 return AMDGPUISD::SMIN3; 8932 case ISD::UMIN: 8933 return AMDGPUISD::UMIN3; 8934 default: 8935 llvm_unreachable("Not a min/max opcode"); 8936 } 8937 } 8938 8939 SDValue SITargetLowering::performIntMed3ImmCombine( 8940 SelectionDAG &DAG, const SDLoc &SL, 8941 SDValue Op0, SDValue Op1, bool Signed) const { 8942 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8943 if (!K1) 8944 return SDValue(); 8945 8946 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8947 if (!K0) 8948 return SDValue(); 8949 8950 if (Signed) { 8951 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8952 return SDValue(); 8953 } else { 8954 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8955 return SDValue(); 8956 } 8957 8958 EVT VT = K0->getValueType(0); 8959 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8960 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8961 return DAG.getNode(Med3Opc, SL, VT, 8962 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8963 } 8964 8965 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8966 MVT NVT = MVT::i32; 8967 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8968 8969 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8970 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8971 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8972 8973 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8974 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8975 } 8976 8977 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8978 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8979 return C; 8980 8981 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8982 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8983 return C; 8984 } 8985 8986 return nullptr; 8987 } 8988 8989 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8990 const SDLoc &SL, 8991 SDValue Op0, 8992 SDValue Op1) const { 8993 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8994 if (!K1) 8995 return SDValue(); 8996 8997 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8998 if (!K0) 8999 return SDValue(); 9000 9001 // Ordered >= (although NaN inputs should have folded away by now). 9002 if (K0->getValueAPF() > K1->getValueAPF()) 9003 return SDValue(); 9004 9005 const MachineFunction &MF = DAG.getMachineFunction(); 9006 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9007 9008 // TODO: Check IEEE bit enabled? 9009 EVT VT = Op0.getValueType(); 9010 if (Info->getMode().DX10Clamp) { 9011 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9012 // hardware fmed3 behavior converting to a min. 9013 // FIXME: Should this be allowing -0.0? 9014 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9015 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9016 } 9017 9018 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9019 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9020 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9021 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9022 // then give the other result, which is different from med3 with a NaN 9023 // input. 9024 SDValue Var = Op0.getOperand(0); 9025 if (!DAG.isKnownNeverSNaN(Var)) 9026 return SDValue(); 9027 9028 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9029 9030 if ((!K0->hasOneUse() || 9031 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9032 (!K1->hasOneUse() || 9033 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9034 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9035 Var, SDValue(K0, 0), SDValue(K1, 0)); 9036 } 9037 } 9038 9039 return SDValue(); 9040 } 9041 9042 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9043 DAGCombinerInfo &DCI) const { 9044 SelectionDAG &DAG = DCI.DAG; 9045 9046 EVT VT = N->getValueType(0); 9047 unsigned Opc = N->getOpcode(); 9048 SDValue Op0 = N->getOperand(0); 9049 SDValue Op1 = N->getOperand(1); 9050 9051 // Only do this if the inner op has one use since this will just increases 9052 // register pressure for no benefit. 9053 9054 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9055 !VT.isVector() && 9056 (VT == MVT::i32 || VT == MVT::f32 || 9057 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9058 // max(max(a, b), c) -> max3(a, b, c) 9059 // min(min(a, b), c) -> min3(a, b, c) 9060 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9061 SDLoc DL(N); 9062 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9063 DL, 9064 N->getValueType(0), 9065 Op0.getOperand(0), 9066 Op0.getOperand(1), 9067 Op1); 9068 } 9069 9070 // Try commuted. 9071 // max(a, max(b, c)) -> max3(a, b, c) 9072 // min(a, min(b, c)) -> min3(a, b, c) 9073 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9074 SDLoc DL(N); 9075 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9076 DL, 9077 N->getValueType(0), 9078 Op0, 9079 Op1.getOperand(0), 9080 Op1.getOperand(1)); 9081 } 9082 } 9083 9084 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9085 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9086 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9087 return Med3; 9088 } 9089 9090 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9091 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9092 return Med3; 9093 } 9094 9095 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9096 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9097 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9098 (Opc == AMDGPUISD::FMIN_LEGACY && 9099 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9100 (VT == MVT::f32 || VT == MVT::f64 || 9101 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9102 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9103 Op0.hasOneUse()) { 9104 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9105 return Res; 9106 } 9107 9108 return SDValue(); 9109 } 9110 9111 static bool isClampZeroToOne(SDValue A, SDValue B) { 9112 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9113 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9114 // FIXME: Should this be allowing -0.0? 9115 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9116 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9117 } 9118 } 9119 9120 return false; 9121 } 9122 9123 // FIXME: Should only worry about snans for version with chain. 9124 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9125 DAGCombinerInfo &DCI) const { 9126 EVT VT = N->getValueType(0); 9127 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9128 // NaNs. With a NaN input, the order of the operands may change the result. 9129 9130 SelectionDAG &DAG = DCI.DAG; 9131 SDLoc SL(N); 9132 9133 SDValue Src0 = N->getOperand(0); 9134 SDValue Src1 = N->getOperand(1); 9135 SDValue Src2 = N->getOperand(2); 9136 9137 if (isClampZeroToOne(Src0, Src1)) { 9138 // const_a, const_b, x -> clamp is safe in all cases including signaling 9139 // nans. 9140 // FIXME: Should this be allowing -0.0? 9141 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9142 } 9143 9144 const MachineFunction &MF = DAG.getMachineFunction(); 9145 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9146 9147 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9148 // handling no dx10-clamp? 9149 if (Info->getMode().DX10Clamp) { 9150 // If NaNs is clamped to 0, we are free to reorder the inputs. 9151 9152 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9153 std::swap(Src0, Src1); 9154 9155 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9156 std::swap(Src1, Src2); 9157 9158 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9159 std::swap(Src0, Src1); 9160 9161 if (isClampZeroToOne(Src1, Src2)) 9162 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9163 } 9164 9165 return SDValue(); 9166 } 9167 9168 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9169 DAGCombinerInfo &DCI) const { 9170 SDValue Src0 = N->getOperand(0); 9171 SDValue Src1 = N->getOperand(1); 9172 if (Src0.isUndef() && Src1.isUndef()) 9173 return DCI.DAG.getUNDEF(N->getValueType(0)); 9174 return SDValue(); 9175 } 9176 9177 SDValue SITargetLowering::performExtractVectorEltCombine( 9178 SDNode *N, DAGCombinerInfo &DCI) const { 9179 SDValue Vec = N->getOperand(0); 9180 SelectionDAG &DAG = DCI.DAG; 9181 9182 EVT VecVT = Vec.getValueType(); 9183 EVT EltVT = VecVT.getVectorElementType(); 9184 9185 if ((Vec.getOpcode() == ISD::FNEG || 9186 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9187 SDLoc SL(N); 9188 EVT EltVT = N->getValueType(0); 9189 SDValue Idx = N->getOperand(1); 9190 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9191 Vec.getOperand(0), Idx); 9192 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9193 } 9194 9195 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9196 // => 9197 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9198 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9199 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9200 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9201 SDLoc SL(N); 9202 EVT EltVT = N->getValueType(0); 9203 SDValue Idx = N->getOperand(1); 9204 unsigned Opc = Vec.getOpcode(); 9205 9206 switch(Opc) { 9207 default: 9208 break; 9209 // TODO: Support other binary operations. 9210 case ISD::FADD: 9211 case ISD::FSUB: 9212 case ISD::FMUL: 9213 case ISD::ADD: 9214 case ISD::UMIN: 9215 case ISD::UMAX: 9216 case ISD::SMIN: 9217 case ISD::SMAX: 9218 case ISD::FMAXNUM: 9219 case ISD::FMINNUM: 9220 case ISD::FMAXNUM_IEEE: 9221 case ISD::FMINNUM_IEEE: { 9222 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9223 Vec.getOperand(0), Idx); 9224 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9225 Vec.getOperand(1), Idx); 9226 9227 DCI.AddToWorklist(Elt0.getNode()); 9228 DCI.AddToWorklist(Elt1.getNode()); 9229 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9230 } 9231 } 9232 } 9233 9234 unsigned VecSize = VecVT.getSizeInBits(); 9235 unsigned EltSize = EltVT.getSizeInBits(); 9236 9237 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9238 // This elminates non-constant index and subsequent movrel or scratch access. 9239 // Sub-dword vectors of size 2 dword or less have better implementation. 9240 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9241 // instructions. 9242 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9243 !isa<ConstantSDNode>(N->getOperand(1))) { 9244 SDLoc SL(N); 9245 SDValue Idx = N->getOperand(1); 9246 SDValue V; 9247 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9248 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9249 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9250 if (I == 0) 9251 V = Elt; 9252 else 9253 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9254 } 9255 return V; 9256 } 9257 9258 if (!DCI.isBeforeLegalize()) 9259 return SDValue(); 9260 9261 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9262 // elements. This exposes more load reduction opportunities by replacing 9263 // multiple small extract_vector_elements with a single 32-bit extract. 9264 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9265 if (isa<MemSDNode>(Vec) && 9266 EltSize <= 16 && 9267 EltVT.isByteSized() && 9268 VecSize > 32 && 9269 VecSize % 32 == 0 && 9270 Idx) { 9271 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9272 9273 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9274 unsigned EltIdx = BitIndex / 32; 9275 unsigned LeftoverBitIdx = BitIndex % 32; 9276 SDLoc SL(N); 9277 9278 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9279 DCI.AddToWorklist(Cast.getNode()); 9280 9281 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9282 DAG.getConstant(EltIdx, SL, MVT::i32)); 9283 DCI.AddToWorklist(Elt.getNode()); 9284 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9285 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9286 DCI.AddToWorklist(Srl.getNode()); 9287 9288 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9289 DCI.AddToWorklist(Trunc.getNode()); 9290 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9291 } 9292 9293 return SDValue(); 9294 } 9295 9296 SDValue 9297 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9298 DAGCombinerInfo &DCI) const { 9299 SDValue Vec = N->getOperand(0); 9300 SDValue Idx = N->getOperand(2); 9301 EVT VecVT = Vec.getValueType(); 9302 EVT EltVT = VecVT.getVectorElementType(); 9303 unsigned VecSize = VecVT.getSizeInBits(); 9304 unsigned EltSize = EltVT.getSizeInBits(); 9305 9306 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9307 // => BUILD_VECTOR n x select (e, const-idx) 9308 // This elminates non-constant index and subsequent movrel or scratch access. 9309 // Sub-dword vectors of size 2 dword or less have better implementation. 9310 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9311 // instructions. 9312 if (isa<ConstantSDNode>(Idx) || 9313 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9314 return SDValue(); 9315 9316 SelectionDAG &DAG = DCI.DAG; 9317 SDLoc SL(N); 9318 SDValue Ins = N->getOperand(1); 9319 EVT IdxVT = Idx.getValueType(); 9320 9321 SmallVector<SDValue, 16> Ops; 9322 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9323 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9324 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9325 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9326 Ops.push_back(V); 9327 } 9328 9329 return DAG.getBuildVector(VecVT, SL, Ops); 9330 } 9331 9332 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9333 const SDNode *N0, 9334 const SDNode *N1) const { 9335 EVT VT = N0->getValueType(0); 9336 9337 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9338 // support denormals ever. 9339 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9340 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9341 getSubtarget()->hasMadF16())) && 9342 isOperationLegal(ISD::FMAD, VT)) 9343 return ISD::FMAD; 9344 9345 const TargetOptions &Options = DAG.getTarget().Options; 9346 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9347 (N0->getFlags().hasAllowContract() && 9348 N1->getFlags().hasAllowContract())) && 9349 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9350 return ISD::FMA; 9351 } 9352 9353 return 0; 9354 } 9355 9356 // For a reassociatable opcode perform: 9357 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9358 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9359 SelectionDAG &DAG) const { 9360 EVT VT = N->getValueType(0); 9361 if (VT != MVT::i32 && VT != MVT::i64) 9362 return SDValue(); 9363 9364 unsigned Opc = N->getOpcode(); 9365 SDValue Op0 = N->getOperand(0); 9366 SDValue Op1 = N->getOperand(1); 9367 9368 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9369 return SDValue(); 9370 9371 if (Op0->isDivergent()) 9372 std::swap(Op0, Op1); 9373 9374 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9375 return SDValue(); 9376 9377 SDValue Op2 = Op1.getOperand(1); 9378 Op1 = Op1.getOperand(0); 9379 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9380 return SDValue(); 9381 9382 if (Op1->isDivergent()) 9383 std::swap(Op1, Op2); 9384 9385 // If either operand is constant this will conflict with 9386 // DAGCombiner::ReassociateOps(). 9387 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9388 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9389 return SDValue(); 9390 9391 SDLoc SL(N); 9392 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9393 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9394 } 9395 9396 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9397 EVT VT, 9398 SDValue N0, SDValue N1, SDValue N2, 9399 bool Signed) { 9400 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9401 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9402 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9403 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9404 } 9405 9406 SDValue SITargetLowering::performAddCombine(SDNode *N, 9407 DAGCombinerInfo &DCI) const { 9408 SelectionDAG &DAG = DCI.DAG; 9409 EVT VT = N->getValueType(0); 9410 SDLoc SL(N); 9411 SDValue LHS = N->getOperand(0); 9412 SDValue RHS = N->getOperand(1); 9413 9414 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9415 && Subtarget->hasMad64_32() && 9416 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9417 VT.getScalarSizeInBits() <= 64) { 9418 if (LHS.getOpcode() != ISD::MUL) 9419 std::swap(LHS, RHS); 9420 9421 SDValue MulLHS = LHS.getOperand(0); 9422 SDValue MulRHS = LHS.getOperand(1); 9423 SDValue AddRHS = RHS; 9424 9425 // TODO: Maybe restrict if SGPR inputs. 9426 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9427 numBitsUnsigned(MulRHS, DAG) <= 32) { 9428 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9429 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9430 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9431 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9432 } 9433 9434 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9435 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9436 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9437 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9438 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9439 } 9440 9441 return SDValue(); 9442 } 9443 9444 if (SDValue V = reassociateScalarOps(N, DAG)) { 9445 return V; 9446 } 9447 9448 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9449 return SDValue(); 9450 9451 // add x, zext (setcc) => addcarry x, 0, setcc 9452 // add x, sext (setcc) => subcarry x, 0, setcc 9453 unsigned Opc = LHS.getOpcode(); 9454 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9455 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9456 std::swap(RHS, LHS); 9457 9458 Opc = RHS.getOpcode(); 9459 switch (Opc) { 9460 default: break; 9461 case ISD::ZERO_EXTEND: 9462 case ISD::SIGN_EXTEND: 9463 case ISD::ANY_EXTEND: { 9464 auto Cond = RHS.getOperand(0); 9465 // If this won't be a real VOPC output, we would still need to insert an 9466 // extra instruction anyway. 9467 if (!isBoolSGPR(Cond)) 9468 break; 9469 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9470 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9471 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9472 return DAG.getNode(Opc, SL, VTList, Args); 9473 } 9474 case ISD::ADDCARRY: { 9475 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9476 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9477 if (!C || C->getZExtValue() != 0) break; 9478 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9479 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9480 } 9481 } 9482 return SDValue(); 9483 } 9484 9485 SDValue SITargetLowering::performSubCombine(SDNode *N, 9486 DAGCombinerInfo &DCI) const { 9487 SelectionDAG &DAG = DCI.DAG; 9488 EVT VT = N->getValueType(0); 9489 9490 if (VT != MVT::i32) 9491 return SDValue(); 9492 9493 SDLoc SL(N); 9494 SDValue LHS = N->getOperand(0); 9495 SDValue RHS = N->getOperand(1); 9496 9497 // sub x, zext (setcc) => subcarry x, 0, setcc 9498 // sub x, sext (setcc) => addcarry x, 0, setcc 9499 unsigned Opc = RHS.getOpcode(); 9500 switch (Opc) { 9501 default: break; 9502 case ISD::ZERO_EXTEND: 9503 case ISD::SIGN_EXTEND: 9504 case ISD::ANY_EXTEND: { 9505 auto Cond = RHS.getOperand(0); 9506 // If this won't be a real VOPC output, we would still need to insert an 9507 // extra instruction anyway. 9508 if (!isBoolSGPR(Cond)) 9509 break; 9510 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9511 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9512 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9513 return DAG.getNode(Opc, SL, VTList, Args); 9514 } 9515 } 9516 9517 if (LHS.getOpcode() == ISD::SUBCARRY) { 9518 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9519 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9520 if (!C || !C->isNullValue()) 9521 return SDValue(); 9522 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9523 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9524 } 9525 return SDValue(); 9526 } 9527 9528 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9529 DAGCombinerInfo &DCI) const { 9530 9531 if (N->getValueType(0) != MVT::i32) 9532 return SDValue(); 9533 9534 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9535 if (!C || C->getZExtValue() != 0) 9536 return SDValue(); 9537 9538 SelectionDAG &DAG = DCI.DAG; 9539 SDValue LHS = N->getOperand(0); 9540 9541 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9542 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9543 unsigned LHSOpc = LHS.getOpcode(); 9544 unsigned Opc = N->getOpcode(); 9545 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9546 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9547 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9548 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9549 } 9550 return SDValue(); 9551 } 9552 9553 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9554 DAGCombinerInfo &DCI) const { 9555 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9556 return SDValue(); 9557 9558 SelectionDAG &DAG = DCI.DAG; 9559 EVT VT = N->getValueType(0); 9560 9561 SDLoc SL(N); 9562 SDValue LHS = N->getOperand(0); 9563 SDValue RHS = N->getOperand(1); 9564 9565 // These should really be instruction patterns, but writing patterns with 9566 // source modiifiers is a pain. 9567 9568 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9569 if (LHS.getOpcode() == ISD::FADD) { 9570 SDValue A = LHS.getOperand(0); 9571 if (A == LHS.getOperand(1)) { 9572 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9573 if (FusedOp != 0) { 9574 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9575 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9576 } 9577 } 9578 } 9579 9580 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9581 if (RHS.getOpcode() == ISD::FADD) { 9582 SDValue A = RHS.getOperand(0); 9583 if (A == RHS.getOperand(1)) { 9584 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9585 if (FusedOp != 0) { 9586 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9587 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9588 } 9589 } 9590 } 9591 9592 return SDValue(); 9593 } 9594 9595 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9596 DAGCombinerInfo &DCI) const { 9597 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9598 return SDValue(); 9599 9600 SelectionDAG &DAG = DCI.DAG; 9601 SDLoc SL(N); 9602 EVT VT = N->getValueType(0); 9603 assert(!VT.isVector()); 9604 9605 // Try to get the fneg to fold into the source modifier. This undoes generic 9606 // DAG combines and folds them into the mad. 9607 // 9608 // Only do this if we are not trying to support denormals. v_mad_f32 does 9609 // not support denormals ever. 9610 SDValue LHS = N->getOperand(0); 9611 SDValue RHS = N->getOperand(1); 9612 if (LHS.getOpcode() == ISD::FADD) { 9613 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9614 SDValue A = LHS.getOperand(0); 9615 if (A == LHS.getOperand(1)) { 9616 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9617 if (FusedOp != 0){ 9618 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9619 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9620 9621 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9622 } 9623 } 9624 } 9625 9626 if (RHS.getOpcode() == ISD::FADD) { 9627 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9628 9629 SDValue A = RHS.getOperand(0); 9630 if (A == RHS.getOperand(1)) { 9631 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9632 if (FusedOp != 0){ 9633 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9634 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9635 } 9636 } 9637 } 9638 9639 return SDValue(); 9640 } 9641 9642 SDValue SITargetLowering::performFMACombine(SDNode *N, 9643 DAGCombinerInfo &DCI) const { 9644 SelectionDAG &DAG = DCI.DAG; 9645 EVT VT = N->getValueType(0); 9646 SDLoc SL(N); 9647 9648 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9649 return SDValue(); 9650 9651 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9652 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9653 SDValue Op1 = N->getOperand(0); 9654 SDValue Op2 = N->getOperand(1); 9655 SDValue FMA = N->getOperand(2); 9656 9657 if (FMA.getOpcode() != ISD::FMA || 9658 Op1.getOpcode() != ISD::FP_EXTEND || 9659 Op2.getOpcode() != ISD::FP_EXTEND) 9660 return SDValue(); 9661 9662 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9663 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9664 // is sufficient to allow generaing fdot2. 9665 const TargetOptions &Options = DAG.getTarget().Options; 9666 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9667 (N->getFlags().hasAllowContract() && 9668 FMA->getFlags().hasAllowContract())) { 9669 Op1 = Op1.getOperand(0); 9670 Op2 = Op2.getOperand(0); 9671 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9672 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9673 return SDValue(); 9674 9675 SDValue Vec1 = Op1.getOperand(0); 9676 SDValue Idx1 = Op1.getOperand(1); 9677 SDValue Vec2 = Op2.getOperand(0); 9678 9679 SDValue FMAOp1 = FMA.getOperand(0); 9680 SDValue FMAOp2 = FMA.getOperand(1); 9681 SDValue FMAAcc = FMA.getOperand(2); 9682 9683 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9684 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9685 return SDValue(); 9686 9687 FMAOp1 = FMAOp1.getOperand(0); 9688 FMAOp2 = FMAOp2.getOperand(0); 9689 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9690 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9691 return SDValue(); 9692 9693 SDValue Vec3 = FMAOp1.getOperand(0); 9694 SDValue Vec4 = FMAOp2.getOperand(0); 9695 SDValue Idx2 = FMAOp1.getOperand(1); 9696 9697 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9698 // Idx1 and Idx2 cannot be the same. 9699 Idx1 == Idx2) 9700 return SDValue(); 9701 9702 if (Vec1 == Vec2 || Vec3 == Vec4) 9703 return SDValue(); 9704 9705 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9706 return SDValue(); 9707 9708 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9709 (Vec1 == Vec4 && Vec2 == Vec3)) { 9710 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9711 DAG.getTargetConstant(0, SL, MVT::i1)); 9712 } 9713 } 9714 return SDValue(); 9715 } 9716 9717 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9718 DAGCombinerInfo &DCI) const { 9719 SelectionDAG &DAG = DCI.DAG; 9720 SDLoc SL(N); 9721 9722 SDValue LHS = N->getOperand(0); 9723 SDValue RHS = N->getOperand(1); 9724 EVT VT = LHS.getValueType(); 9725 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9726 9727 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9728 if (!CRHS) { 9729 CRHS = dyn_cast<ConstantSDNode>(LHS); 9730 if (CRHS) { 9731 std::swap(LHS, RHS); 9732 CC = getSetCCSwappedOperands(CC); 9733 } 9734 } 9735 9736 if (CRHS) { 9737 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9738 isBoolSGPR(LHS.getOperand(0))) { 9739 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9740 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9741 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9742 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9743 if ((CRHS->isAllOnesValue() && 9744 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9745 (CRHS->isNullValue() && 9746 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9747 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9748 DAG.getConstant(-1, SL, MVT::i1)); 9749 if ((CRHS->isAllOnesValue() && 9750 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9751 (CRHS->isNullValue() && 9752 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9753 return LHS.getOperand(0); 9754 } 9755 9756 uint64_t CRHSVal = CRHS->getZExtValue(); 9757 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9758 LHS.getOpcode() == ISD::SELECT && 9759 isa<ConstantSDNode>(LHS.getOperand(1)) && 9760 isa<ConstantSDNode>(LHS.getOperand(2)) && 9761 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9762 isBoolSGPR(LHS.getOperand(0))) { 9763 // Given CT != FT: 9764 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9765 // setcc (select cc, CT, CF), CF, ne => cc 9766 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9767 // setcc (select cc, CT, CF), CT, eq => cc 9768 uint64_t CT = LHS.getConstantOperandVal(1); 9769 uint64_t CF = LHS.getConstantOperandVal(2); 9770 9771 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9772 (CT == CRHSVal && CC == ISD::SETNE)) 9773 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9774 DAG.getConstant(-1, SL, MVT::i1)); 9775 if ((CF == CRHSVal && CC == ISD::SETNE) || 9776 (CT == CRHSVal && CC == ISD::SETEQ)) 9777 return LHS.getOperand(0); 9778 } 9779 } 9780 9781 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9782 VT != MVT::f16)) 9783 return SDValue(); 9784 9785 // Match isinf/isfinite pattern 9786 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9787 // (fcmp one (fabs x), inf) -> (fp_class x, 9788 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9789 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9790 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9791 if (!CRHS) 9792 return SDValue(); 9793 9794 const APFloat &APF = CRHS->getValueAPF(); 9795 if (APF.isInfinity() && !APF.isNegative()) { 9796 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9797 SIInstrFlags::N_INFINITY; 9798 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9799 SIInstrFlags::P_ZERO | 9800 SIInstrFlags::N_NORMAL | 9801 SIInstrFlags::P_NORMAL | 9802 SIInstrFlags::N_SUBNORMAL | 9803 SIInstrFlags::P_SUBNORMAL; 9804 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9805 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9806 DAG.getConstant(Mask, SL, MVT::i32)); 9807 } 9808 } 9809 9810 return SDValue(); 9811 } 9812 9813 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9814 DAGCombinerInfo &DCI) const { 9815 SelectionDAG &DAG = DCI.DAG; 9816 SDLoc SL(N); 9817 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9818 9819 SDValue Src = N->getOperand(0); 9820 SDValue Shift = N->getOperand(0); 9821 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 9822 Shift = Shift.getOperand(0); 9823 9824 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 9825 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 9826 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 9827 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9828 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9829 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9830 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 9831 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 9832 SDLoc(Shift.getOperand(0)), MVT::i32); 9833 9834 unsigned ShiftOffset = 8 * Offset; 9835 if (Shift.getOpcode() == ISD::SHL) 9836 ShiftOffset -= C->getZExtValue(); 9837 else 9838 ShiftOffset += C->getZExtValue(); 9839 9840 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 9841 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 9842 MVT::f32, Shift); 9843 } 9844 } 9845 } 9846 9847 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9848 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9849 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 9850 // We simplified Src. If this node is not dead, visit it again so it is 9851 // folded properly. 9852 if (N->getOpcode() != ISD::DELETED_NODE) 9853 DCI.AddToWorklist(N); 9854 return SDValue(N, 0); 9855 } 9856 9857 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 9858 if (SDValue DemandedSrc = 9859 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 9860 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 9861 9862 return SDValue(); 9863 } 9864 9865 SDValue SITargetLowering::performClampCombine(SDNode *N, 9866 DAGCombinerInfo &DCI) const { 9867 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9868 if (!CSrc) 9869 return SDValue(); 9870 9871 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9872 const APFloat &F = CSrc->getValueAPF(); 9873 APFloat Zero = APFloat::getZero(F.getSemantics()); 9874 if (F < Zero || 9875 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9876 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9877 } 9878 9879 APFloat One(F.getSemantics(), "1.0"); 9880 if (F > One) 9881 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9882 9883 return SDValue(CSrc, 0); 9884 } 9885 9886 9887 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9888 DAGCombinerInfo &DCI) const { 9889 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9890 return SDValue(); 9891 switch (N->getOpcode()) { 9892 default: 9893 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9894 case ISD::ADD: 9895 return performAddCombine(N, DCI); 9896 case ISD::SUB: 9897 return performSubCombine(N, DCI); 9898 case ISD::ADDCARRY: 9899 case ISD::SUBCARRY: 9900 return performAddCarrySubCarryCombine(N, DCI); 9901 case ISD::FADD: 9902 return performFAddCombine(N, DCI); 9903 case ISD::FSUB: 9904 return performFSubCombine(N, DCI); 9905 case ISD::SETCC: 9906 return performSetCCCombine(N, DCI); 9907 case ISD::FMAXNUM: 9908 case ISD::FMINNUM: 9909 case ISD::FMAXNUM_IEEE: 9910 case ISD::FMINNUM_IEEE: 9911 case ISD::SMAX: 9912 case ISD::SMIN: 9913 case ISD::UMAX: 9914 case ISD::UMIN: 9915 case AMDGPUISD::FMIN_LEGACY: 9916 case AMDGPUISD::FMAX_LEGACY: 9917 return performMinMaxCombine(N, DCI); 9918 case ISD::FMA: 9919 return performFMACombine(N, DCI); 9920 case ISD::LOAD: { 9921 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9922 return Widended; 9923 LLVM_FALLTHROUGH; 9924 } 9925 case ISD::STORE: 9926 case ISD::ATOMIC_LOAD: 9927 case ISD::ATOMIC_STORE: 9928 case ISD::ATOMIC_CMP_SWAP: 9929 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9930 case ISD::ATOMIC_SWAP: 9931 case ISD::ATOMIC_LOAD_ADD: 9932 case ISD::ATOMIC_LOAD_SUB: 9933 case ISD::ATOMIC_LOAD_AND: 9934 case ISD::ATOMIC_LOAD_OR: 9935 case ISD::ATOMIC_LOAD_XOR: 9936 case ISD::ATOMIC_LOAD_NAND: 9937 case ISD::ATOMIC_LOAD_MIN: 9938 case ISD::ATOMIC_LOAD_MAX: 9939 case ISD::ATOMIC_LOAD_UMIN: 9940 case ISD::ATOMIC_LOAD_UMAX: 9941 case ISD::ATOMIC_LOAD_FADD: 9942 case AMDGPUISD::ATOMIC_INC: 9943 case AMDGPUISD::ATOMIC_DEC: 9944 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9945 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9946 if (DCI.isBeforeLegalize()) 9947 break; 9948 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9949 case ISD::AND: 9950 return performAndCombine(N, DCI); 9951 case ISD::OR: 9952 return performOrCombine(N, DCI); 9953 case ISD::XOR: 9954 return performXorCombine(N, DCI); 9955 case ISD::ZERO_EXTEND: 9956 return performZeroExtendCombine(N, DCI); 9957 case ISD::SIGN_EXTEND_INREG: 9958 return performSignExtendInRegCombine(N , DCI); 9959 case AMDGPUISD::FP_CLASS: 9960 return performClassCombine(N, DCI); 9961 case ISD::FCANONICALIZE: 9962 return performFCanonicalizeCombine(N, DCI); 9963 case AMDGPUISD::RCP: 9964 return performRcpCombine(N, DCI); 9965 case AMDGPUISD::FRACT: 9966 case AMDGPUISD::RSQ: 9967 case AMDGPUISD::RCP_LEGACY: 9968 case AMDGPUISD::RSQ_LEGACY: 9969 case AMDGPUISD::RCP_IFLAG: 9970 case AMDGPUISD::RSQ_CLAMP: 9971 case AMDGPUISD::LDEXP: { 9972 SDValue Src = N->getOperand(0); 9973 if (Src.isUndef()) 9974 return Src; 9975 break; 9976 } 9977 case ISD::SINT_TO_FP: 9978 case ISD::UINT_TO_FP: 9979 return performUCharToFloatCombine(N, DCI); 9980 case AMDGPUISD::CVT_F32_UBYTE0: 9981 case AMDGPUISD::CVT_F32_UBYTE1: 9982 case AMDGPUISD::CVT_F32_UBYTE2: 9983 case AMDGPUISD::CVT_F32_UBYTE3: 9984 return performCvtF32UByteNCombine(N, DCI); 9985 case AMDGPUISD::FMED3: 9986 return performFMed3Combine(N, DCI); 9987 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9988 return performCvtPkRTZCombine(N, DCI); 9989 case AMDGPUISD::CLAMP: 9990 return performClampCombine(N, DCI); 9991 case ISD::SCALAR_TO_VECTOR: { 9992 SelectionDAG &DAG = DCI.DAG; 9993 EVT VT = N->getValueType(0); 9994 9995 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9996 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9997 SDLoc SL(N); 9998 SDValue Src = N->getOperand(0); 9999 EVT EltVT = Src.getValueType(); 10000 if (EltVT == MVT::f16) 10001 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10002 10003 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10004 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10005 } 10006 10007 break; 10008 } 10009 case ISD::EXTRACT_VECTOR_ELT: 10010 return performExtractVectorEltCombine(N, DCI); 10011 case ISD::INSERT_VECTOR_ELT: 10012 return performInsertVectorEltCombine(N, DCI); 10013 } 10014 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10015 } 10016 10017 /// Helper function for adjustWritemask 10018 static unsigned SubIdx2Lane(unsigned Idx) { 10019 switch (Idx) { 10020 default: return 0; 10021 case AMDGPU::sub0: return 0; 10022 case AMDGPU::sub1: return 1; 10023 case AMDGPU::sub2: return 2; 10024 case AMDGPU::sub3: return 3; 10025 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10026 } 10027 } 10028 10029 /// Adjust the writemask of MIMG instructions 10030 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10031 SelectionDAG &DAG) const { 10032 unsigned Opcode = Node->getMachineOpcode(); 10033 10034 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10035 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10036 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10037 return Node; // not implemented for D16 10038 10039 SDNode *Users[5] = { nullptr }; 10040 unsigned Lane = 0; 10041 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10042 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10043 unsigned NewDmask = 0; 10044 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10045 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10046 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10047 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10048 unsigned TFCLane = 0; 10049 bool HasChain = Node->getNumValues() > 1; 10050 10051 if (OldDmask == 0) { 10052 // These are folded out, but on the chance it happens don't assert. 10053 return Node; 10054 } 10055 10056 unsigned OldBitsSet = countPopulation(OldDmask); 10057 // Work out which is the TFE/LWE lane if that is enabled. 10058 if (UsesTFC) { 10059 TFCLane = OldBitsSet; 10060 } 10061 10062 // Try to figure out the used register components 10063 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10064 I != E; ++I) { 10065 10066 // Don't look at users of the chain. 10067 if (I.getUse().getResNo() != 0) 10068 continue; 10069 10070 // Abort if we can't understand the usage 10071 if (!I->isMachineOpcode() || 10072 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10073 return Node; 10074 10075 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10076 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10077 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10078 // set, etc. 10079 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10080 10081 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10082 if (UsesTFC && Lane == TFCLane) { 10083 Users[Lane] = *I; 10084 } else { 10085 // Set which texture component corresponds to the lane. 10086 unsigned Comp; 10087 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10088 Comp = countTrailingZeros(Dmask); 10089 Dmask &= ~(1 << Comp); 10090 } 10091 10092 // Abort if we have more than one user per component. 10093 if (Users[Lane]) 10094 return Node; 10095 10096 Users[Lane] = *I; 10097 NewDmask |= 1 << Comp; 10098 } 10099 } 10100 10101 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10102 bool NoChannels = !NewDmask; 10103 if (NoChannels) { 10104 if (!UsesTFC) { 10105 // No uses of the result and not using TFC. Then do nothing. 10106 return Node; 10107 } 10108 // If the original dmask has one channel - then nothing to do 10109 if (OldBitsSet == 1) 10110 return Node; 10111 // Use an arbitrary dmask - required for the instruction to work 10112 NewDmask = 1; 10113 } 10114 // Abort if there's no change 10115 if (NewDmask == OldDmask) 10116 return Node; 10117 10118 unsigned BitsSet = countPopulation(NewDmask); 10119 10120 // Check for TFE or LWE - increase the number of channels by one to account 10121 // for the extra return value 10122 // This will need adjustment for D16 if this is also included in 10123 // adjustWriteMask (this function) but at present D16 are excluded. 10124 unsigned NewChannels = BitsSet + UsesTFC; 10125 10126 int NewOpcode = 10127 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10128 assert(NewOpcode != -1 && 10129 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10130 "failed to find equivalent MIMG op"); 10131 10132 // Adjust the writemask in the node 10133 SmallVector<SDValue, 12> Ops; 10134 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10135 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10136 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10137 10138 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10139 10140 MVT ResultVT = NewChannels == 1 ? 10141 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10142 NewChannels == 5 ? 8 : NewChannels); 10143 SDVTList NewVTList = HasChain ? 10144 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10145 10146 10147 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10148 NewVTList, Ops); 10149 10150 if (HasChain) { 10151 // Update chain. 10152 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10153 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10154 } 10155 10156 if (NewChannels == 1) { 10157 assert(Node->hasNUsesOfValue(1, 0)); 10158 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10159 SDLoc(Node), Users[Lane]->getValueType(0), 10160 SDValue(NewNode, 0)); 10161 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10162 return nullptr; 10163 } 10164 10165 // Update the users of the node with the new indices 10166 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10167 SDNode *User = Users[i]; 10168 if (!User) { 10169 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10170 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10171 if (i || !NoChannels) 10172 continue; 10173 } else { 10174 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10175 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10176 } 10177 10178 switch (Idx) { 10179 default: break; 10180 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10181 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10182 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10183 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10184 } 10185 } 10186 10187 DAG.RemoveDeadNode(Node); 10188 return nullptr; 10189 } 10190 10191 static bool isFrameIndexOp(SDValue Op) { 10192 if (Op.getOpcode() == ISD::AssertZext) 10193 Op = Op.getOperand(0); 10194 10195 return isa<FrameIndexSDNode>(Op); 10196 } 10197 10198 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10199 /// with frame index operands. 10200 /// LLVM assumes that inputs are to these instructions are registers. 10201 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10202 SelectionDAG &DAG) const { 10203 if (Node->getOpcode() == ISD::CopyToReg) { 10204 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10205 SDValue SrcVal = Node->getOperand(2); 10206 10207 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10208 // to try understanding copies to physical registers. 10209 if (SrcVal.getValueType() == MVT::i1 && 10210 Register::isPhysicalRegister(DestReg->getReg())) { 10211 SDLoc SL(Node); 10212 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10213 SDValue VReg = DAG.getRegister( 10214 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10215 10216 SDNode *Glued = Node->getGluedNode(); 10217 SDValue ToVReg 10218 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10219 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10220 SDValue ToResultReg 10221 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10222 VReg, ToVReg.getValue(1)); 10223 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10224 DAG.RemoveDeadNode(Node); 10225 return ToResultReg.getNode(); 10226 } 10227 } 10228 10229 SmallVector<SDValue, 8> Ops; 10230 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10231 if (!isFrameIndexOp(Node->getOperand(i))) { 10232 Ops.push_back(Node->getOperand(i)); 10233 continue; 10234 } 10235 10236 SDLoc DL(Node); 10237 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10238 Node->getOperand(i).getValueType(), 10239 Node->getOperand(i)), 0)); 10240 } 10241 10242 return DAG.UpdateNodeOperands(Node, Ops); 10243 } 10244 10245 /// Fold the instructions after selecting them. 10246 /// Returns null if users were already updated. 10247 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10248 SelectionDAG &DAG) const { 10249 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10250 unsigned Opcode = Node->getMachineOpcode(); 10251 10252 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10253 !TII->isGather4(Opcode)) { 10254 return adjustWritemask(Node, DAG); 10255 } 10256 10257 if (Opcode == AMDGPU::INSERT_SUBREG || 10258 Opcode == AMDGPU::REG_SEQUENCE) { 10259 legalizeTargetIndependentNode(Node, DAG); 10260 return Node; 10261 } 10262 10263 switch (Opcode) { 10264 case AMDGPU::V_DIV_SCALE_F32: 10265 case AMDGPU::V_DIV_SCALE_F64: { 10266 // Satisfy the operand register constraint when one of the inputs is 10267 // undefined. Ordinarily each undef value will have its own implicit_def of 10268 // a vreg, so force these to use a single register. 10269 SDValue Src0 = Node->getOperand(0); 10270 SDValue Src1 = Node->getOperand(1); 10271 SDValue Src2 = Node->getOperand(2); 10272 10273 if ((Src0.isMachineOpcode() && 10274 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10275 (Src0 == Src1 || Src0 == Src2)) 10276 break; 10277 10278 MVT VT = Src0.getValueType().getSimpleVT(); 10279 const TargetRegisterClass *RC = 10280 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10281 10282 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10283 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10284 10285 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10286 UndefReg, Src0, SDValue()); 10287 10288 // src0 must be the same register as src1 or src2, even if the value is 10289 // undefined, so make sure we don't violate this constraint. 10290 if (Src0.isMachineOpcode() && 10291 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10292 if (Src1.isMachineOpcode() && 10293 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10294 Src0 = Src1; 10295 else if (Src2.isMachineOpcode() && 10296 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10297 Src0 = Src2; 10298 else { 10299 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10300 Src0 = UndefReg; 10301 Src1 = UndefReg; 10302 } 10303 } else 10304 break; 10305 10306 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10307 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10308 Ops.push_back(Node->getOperand(I)); 10309 10310 Ops.push_back(ImpDef.getValue(1)); 10311 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10312 } 10313 default: 10314 break; 10315 } 10316 10317 return Node; 10318 } 10319 10320 /// Assign the register class depending on the number of 10321 /// bits set in the writemask 10322 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10323 SDNode *Node) const { 10324 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10325 10326 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10327 10328 if (TII->isVOP3(MI.getOpcode())) { 10329 // Make sure constant bus requirements are respected. 10330 TII->legalizeOperandsVOP3(MRI, MI); 10331 10332 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10333 // This saves a chain-copy of registers and better ballance register 10334 // use between vgpr and agpr as agpr tuples tend to be big. 10335 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10336 unsigned Opc = MI.getOpcode(); 10337 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10338 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10339 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10340 if (I == -1) 10341 break; 10342 MachineOperand &Op = MI.getOperand(I); 10343 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10344 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10345 !Register::isVirtualRegister(Op.getReg()) || 10346 !TRI->isAGPR(MRI, Op.getReg())) 10347 continue; 10348 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10349 if (!Src || !Src->isCopy() || 10350 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10351 continue; 10352 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10353 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10354 // All uses of agpr64 and agpr32 can also accept vgpr except for 10355 // v_accvgpr_read, but we do not produce agpr reads during selection, 10356 // so no use checks are needed. 10357 MRI.setRegClass(Op.getReg(), NewRC); 10358 } 10359 } 10360 10361 return; 10362 } 10363 10364 // Replace unused atomics with the no return version. 10365 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10366 if (NoRetAtomicOp != -1) { 10367 if (!Node->hasAnyUseOfValue(0)) { 10368 MI.setDesc(TII->get(NoRetAtomicOp)); 10369 MI.RemoveOperand(0); 10370 return; 10371 } 10372 10373 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10374 // instruction, because the return type of these instructions is a vec2 of 10375 // the memory type, so it can be tied to the input operand. 10376 // This means these instructions always have a use, so we need to add a 10377 // special case to check if the atomic has only one extract_subreg use, 10378 // which itself has no uses. 10379 if ((Node->hasNUsesOfValue(1, 0) && 10380 Node->use_begin()->isMachineOpcode() && 10381 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10382 !Node->use_begin()->hasAnyUseOfValue(0))) { 10383 Register Def = MI.getOperand(0).getReg(); 10384 10385 // Change this into a noret atomic. 10386 MI.setDesc(TII->get(NoRetAtomicOp)); 10387 MI.RemoveOperand(0); 10388 10389 // If we only remove the def operand from the atomic instruction, the 10390 // extract_subreg will be left with a use of a vreg without a def. 10391 // So we need to insert an implicit_def to avoid machine verifier 10392 // errors. 10393 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10394 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10395 } 10396 return; 10397 } 10398 } 10399 10400 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10401 uint64_t Val) { 10402 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10403 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10404 } 10405 10406 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10407 const SDLoc &DL, 10408 SDValue Ptr) const { 10409 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10410 10411 // Build the half of the subregister with the constants before building the 10412 // full 128-bit register. If we are building multiple resource descriptors, 10413 // this will allow CSEing of the 2-component register. 10414 const SDValue Ops0[] = { 10415 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10416 buildSMovImm32(DAG, DL, 0), 10417 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10418 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10419 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10420 }; 10421 10422 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10423 MVT::v2i32, Ops0), 0); 10424 10425 // Combine the constants and the pointer. 10426 const SDValue Ops1[] = { 10427 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10428 Ptr, 10429 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10430 SubRegHi, 10431 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10432 }; 10433 10434 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10435 } 10436 10437 /// Return a resource descriptor with the 'Add TID' bit enabled 10438 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10439 /// of the resource descriptor) to create an offset, which is added to 10440 /// the resource pointer. 10441 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10442 SDValue Ptr, uint32_t RsrcDword1, 10443 uint64_t RsrcDword2And3) const { 10444 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10445 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10446 if (RsrcDword1) { 10447 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10448 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10449 0); 10450 } 10451 10452 SDValue DataLo = buildSMovImm32(DAG, DL, 10453 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10454 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10455 10456 const SDValue Ops[] = { 10457 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10458 PtrLo, 10459 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10460 PtrHi, 10461 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10462 DataLo, 10463 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10464 DataHi, 10465 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10466 }; 10467 10468 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10469 } 10470 10471 //===----------------------------------------------------------------------===// 10472 // SI Inline Assembly Support 10473 //===----------------------------------------------------------------------===// 10474 10475 std::pair<unsigned, const TargetRegisterClass *> 10476 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10477 StringRef Constraint, 10478 MVT VT) const { 10479 const TargetRegisterClass *RC = nullptr; 10480 if (Constraint.size() == 1) { 10481 switch (Constraint[0]) { 10482 default: 10483 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10484 case 's': 10485 case 'r': 10486 switch (VT.getSizeInBits()) { 10487 default: 10488 return std::make_pair(0U, nullptr); 10489 case 32: 10490 case 16: 10491 RC = &AMDGPU::SReg_32RegClass; 10492 break; 10493 case 64: 10494 RC = &AMDGPU::SGPR_64RegClass; 10495 break; 10496 case 96: 10497 RC = &AMDGPU::SReg_96RegClass; 10498 break; 10499 case 128: 10500 RC = &AMDGPU::SGPR_128RegClass; 10501 break; 10502 case 160: 10503 RC = &AMDGPU::SReg_160RegClass; 10504 break; 10505 case 256: 10506 RC = &AMDGPU::SReg_256RegClass; 10507 break; 10508 case 512: 10509 RC = &AMDGPU::SReg_512RegClass; 10510 break; 10511 } 10512 break; 10513 case 'v': 10514 switch (VT.getSizeInBits()) { 10515 default: 10516 return std::make_pair(0U, nullptr); 10517 case 32: 10518 case 16: 10519 RC = &AMDGPU::VGPR_32RegClass; 10520 break; 10521 case 64: 10522 RC = &AMDGPU::VReg_64RegClass; 10523 break; 10524 case 96: 10525 RC = &AMDGPU::VReg_96RegClass; 10526 break; 10527 case 128: 10528 RC = &AMDGPU::VReg_128RegClass; 10529 break; 10530 case 160: 10531 RC = &AMDGPU::VReg_160RegClass; 10532 break; 10533 case 256: 10534 RC = &AMDGPU::VReg_256RegClass; 10535 break; 10536 case 512: 10537 RC = &AMDGPU::VReg_512RegClass; 10538 break; 10539 } 10540 break; 10541 case 'a': 10542 if (!Subtarget->hasMAIInsts()) 10543 break; 10544 switch (VT.getSizeInBits()) { 10545 default: 10546 return std::make_pair(0U, nullptr); 10547 case 32: 10548 case 16: 10549 RC = &AMDGPU::AGPR_32RegClass; 10550 break; 10551 case 64: 10552 RC = &AMDGPU::AReg_64RegClass; 10553 break; 10554 case 128: 10555 RC = &AMDGPU::AReg_128RegClass; 10556 break; 10557 case 512: 10558 RC = &AMDGPU::AReg_512RegClass; 10559 break; 10560 case 1024: 10561 RC = &AMDGPU::AReg_1024RegClass; 10562 // v32 types are not legal but we support them here. 10563 return std::make_pair(0U, RC); 10564 } 10565 break; 10566 } 10567 // We actually support i128, i16 and f16 as inline parameters 10568 // even if they are not reported as legal 10569 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10570 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10571 return std::make_pair(0U, RC); 10572 } 10573 10574 if (Constraint.size() > 1) { 10575 if (Constraint[1] == 'v') { 10576 RC = &AMDGPU::VGPR_32RegClass; 10577 } else if (Constraint[1] == 's') { 10578 RC = &AMDGPU::SGPR_32RegClass; 10579 } else if (Constraint[1] == 'a') { 10580 RC = &AMDGPU::AGPR_32RegClass; 10581 } 10582 10583 if (RC) { 10584 uint32_t Idx; 10585 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10586 if (!Failed && Idx < RC->getNumRegs()) 10587 return std::make_pair(RC->getRegister(Idx), RC); 10588 } 10589 } 10590 10591 // FIXME: Returns VS_32 for physical SGPR constraints 10592 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10593 } 10594 10595 SITargetLowering::ConstraintType 10596 SITargetLowering::getConstraintType(StringRef Constraint) const { 10597 if (Constraint.size() == 1) { 10598 switch (Constraint[0]) { 10599 default: break; 10600 case 's': 10601 case 'v': 10602 case 'a': 10603 return C_RegisterClass; 10604 } 10605 } 10606 return TargetLowering::getConstraintType(Constraint); 10607 } 10608 10609 // Figure out which registers should be reserved for stack access. Only after 10610 // the function is legalized do we know all of the non-spill stack objects or if 10611 // calls are present. 10612 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10613 MachineRegisterInfo &MRI = MF.getRegInfo(); 10614 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10615 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10616 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10617 10618 if (Info->isEntryFunction()) { 10619 // Callable functions have fixed registers used for stack access. 10620 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10621 } 10622 10623 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10624 Info->getStackPtrOffsetReg())); 10625 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10626 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10627 10628 // We need to worry about replacing the default register with itself in case 10629 // of MIR testcases missing the MFI. 10630 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10631 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10632 10633 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10634 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10635 10636 Info->limitOccupancy(MF); 10637 10638 if (ST.isWave32() && !MF.empty()) { 10639 // Add VCC_HI def because many instructions marked as imp-use VCC where 10640 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10641 // having a use of undef. 10642 10643 const SIInstrInfo *TII = ST.getInstrInfo(); 10644 DebugLoc DL; 10645 10646 MachineBasicBlock &MBB = MF.front(); 10647 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10648 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10649 10650 for (auto &MBB : MF) { 10651 for (auto &MI : MBB) { 10652 TII->fixImplicitOperands(MI); 10653 } 10654 } 10655 } 10656 10657 TargetLoweringBase::finalizeLowering(MF); 10658 } 10659 10660 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10661 KnownBits &Known, 10662 const APInt &DemandedElts, 10663 const SelectionDAG &DAG, 10664 unsigned Depth) const { 10665 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10666 DAG, Depth); 10667 10668 // Set the high bits to zero based on the maximum allowed scratch size per 10669 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10670 // calculation won't overflow, so assume the sign bit is never set. 10671 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10672 } 10673 10674 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10675 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10676 const Align CacheLineAlign = Align(64); 10677 10678 // Pre-GFX10 target did not benefit from loop alignment 10679 if (!ML || DisableLoopAlignment || 10680 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10681 getSubtarget()->hasInstFwdPrefetchBug()) 10682 return PrefAlign; 10683 10684 // On GFX10 I$ is 4 x 64 bytes cache lines. 10685 // By default prefetcher keeps one cache line behind and reads two ahead. 10686 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10687 // behind and one ahead. 10688 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10689 // If loop fits 64 bytes it always spans no more than two cache lines and 10690 // does not need an alignment. 10691 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10692 // Else if loop is less or equal 192 bytes we need two lines behind. 10693 10694 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10695 const MachineBasicBlock *Header = ML->getHeader(); 10696 if (Header->getAlignment() != PrefAlign) 10697 return Header->getAlignment(); // Already processed. 10698 10699 unsigned LoopSize = 0; 10700 for (const MachineBasicBlock *MBB : ML->blocks()) { 10701 // If inner loop block is aligned assume in average half of the alignment 10702 // size to be added as nops. 10703 if (MBB != Header) 10704 LoopSize += MBB->getAlignment().value() / 2; 10705 10706 for (const MachineInstr &MI : *MBB) { 10707 LoopSize += TII->getInstSizeInBytes(MI); 10708 if (LoopSize > 192) 10709 return PrefAlign; 10710 } 10711 } 10712 10713 if (LoopSize <= 64) 10714 return PrefAlign; 10715 10716 if (LoopSize <= 128) 10717 return CacheLineAlign; 10718 10719 // If any of parent loops is surrounded by prefetch instructions do not 10720 // insert new for inner loop, which would reset parent's settings. 10721 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10722 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10723 auto I = Exit->getFirstNonDebugInstr(); 10724 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10725 return CacheLineAlign; 10726 } 10727 } 10728 10729 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10730 MachineBasicBlock *Exit = ML->getExitBlock(); 10731 10732 if (Pre && Exit) { 10733 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10734 TII->get(AMDGPU::S_INST_PREFETCH)) 10735 .addImm(1); // prefetch 2 lines behind PC 10736 10737 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10738 TII->get(AMDGPU::S_INST_PREFETCH)) 10739 .addImm(2); // prefetch 1 line behind PC 10740 } 10741 10742 return CacheLineAlign; 10743 } 10744 10745 LLVM_ATTRIBUTE_UNUSED 10746 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10747 assert(N->getOpcode() == ISD::CopyFromReg); 10748 do { 10749 // Follow the chain until we find an INLINEASM node. 10750 N = N->getOperand(0).getNode(); 10751 if (N->getOpcode() == ISD::INLINEASM || 10752 N->getOpcode() == ISD::INLINEASM_BR) 10753 return true; 10754 } while (N->getOpcode() == ISD::CopyFromReg); 10755 return false; 10756 } 10757 10758 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10759 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10760 { 10761 switch (N->getOpcode()) { 10762 case ISD::CopyFromReg: 10763 { 10764 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10765 const MachineFunction * MF = FLI->MF; 10766 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10767 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10768 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10769 unsigned Reg = R->getReg(); 10770 if (Register::isPhysicalRegister(Reg)) 10771 return !TRI.isSGPRReg(MRI, Reg); 10772 10773 if (MRI.isLiveIn(Reg)) { 10774 // workitem.id.x workitem.id.y workitem.id.z 10775 // Any VGPR formal argument is also considered divergent 10776 if (!TRI.isSGPRReg(MRI, Reg)) 10777 return true; 10778 // Formal arguments of non-entry functions 10779 // are conservatively considered divergent 10780 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10781 return true; 10782 return false; 10783 } 10784 const Value *V = FLI->getValueFromVirtualReg(Reg); 10785 if (V) 10786 return KDA->isDivergent(V); 10787 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10788 return !TRI.isSGPRReg(MRI, Reg); 10789 } 10790 break; 10791 case ISD::LOAD: { 10792 const LoadSDNode *L = cast<LoadSDNode>(N); 10793 unsigned AS = L->getAddressSpace(); 10794 // A flat load may access private memory. 10795 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10796 } break; 10797 case ISD::CALLSEQ_END: 10798 return true; 10799 break; 10800 case ISD::INTRINSIC_WO_CHAIN: 10801 { 10802 10803 } 10804 return AMDGPU::isIntrinsicSourceOfDivergence( 10805 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10806 case ISD::INTRINSIC_W_CHAIN: 10807 return AMDGPU::isIntrinsicSourceOfDivergence( 10808 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10809 } 10810 return false; 10811 } 10812 10813 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10814 EVT VT) const { 10815 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10816 case MVT::f32: 10817 return hasFP32Denormals(DAG.getMachineFunction()); 10818 case MVT::f64: 10819 case MVT::f16: 10820 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10821 default: 10822 return false; 10823 } 10824 } 10825 10826 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10827 const SelectionDAG &DAG, 10828 bool SNaN, 10829 unsigned Depth) const { 10830 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10831 const MachineFunction &MF = DAG.getMachineFunction(); 10832 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10833 10834 if (Info->getMode().DX10Clamp) 10835 return true; // Clamped to 0. 10836 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10837 } 10838 10839 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10840 SNaN, Depth); 10841 } 10842 10843 TargetLowering::AtomicExpansionKind 10844 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10845 switch (RMW->getOperation()) { 10846 case AtomicRMWInst::FAdd: { 10847 Type *Ty = RMW->getType(); 10848 10849 // We don't have a way to support 16-bit atomics now, so just leave them 10850 // as-is. 10851 if (Ty->isHalfTy()) 10852 return AtomicExpansionKind::None; 10853 10854 if (!Ty->isFloatTy()) 10855 return AtomicExpansionKind::CmpXChg; 10856 10857 // TODO: Do have these for flat. Older targets also had them for buffers. 10858 unsigned AS = RMW->getPointerAddressSpace(); 10859 10860 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10861 return RMW->use_empty() ? AtomicExpansionKind::None : 10862 AtomicExpansionKind::CmpXChg; 10863 } 10864 10865 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10866 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10867 } 10868 default: 10869 break; 10870 } 10871 10872 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10873 } 10874 10875 const TargetRegisterClass * 10876 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10877 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10878 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10879 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10880 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10881 : &AMDGPU::SReg_32RegClass; 10882 if (!TRI->isSGPRClass(RC) && !isDivergent) 10883 return TRI->getEquivalentSGPRClass(RC); 10884 else if (TRI->isSGPRClass(RC) && isDivergent) 10885 return TRI->getEquivalentVGPRClass(RC); 10886 10887 return RC; 10888 } 10889 10890 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 10891 unsigned WaveSize) { 10892 // FIXME: We asssume we never cast the mask results of a control flow 10893 // intrinsic. 10894 // Early exit if the type won't be consistent as a compile time hack. 10895 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 10896 if (!IT || IT->getBitWidth() != WaveSize) 10897 return false; 10898 10899 if (!isa<Instruction>(V)) 10900 return false; 10901 if (!Visited.insert(V).second) 10902 return false; 10903 bool Result = false; 10904 for (auto U : V->users()) { 10905 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10906 if (V == U->getOperand(1)) { 10907 switch (Intrinsic->getIntrinsicID()) { 10908 default: 10909 Result = false; 10910 break; 10911 case Intrinsic::amdgcn_if_break: 10912 case Intrinsic::amdgcn_if: 10913 case Intrinsic::amdgcn_else: 10914 Result = true; 10915 break; 10916 } 10917 } 10918 if (V == U->getOperand(0)) { 10919 switch (Intrinsic->getIntrinsicID()) { 10920 default: 10921 Result = false; 10922 break; 10923 case Intrinsic::amdgcn_end_cf: 10924 case Intrinsic::amdgcn_loop: 10925 Result = true; 10926 break; 10927 } 10928 } 10929 } else { 10930 Result = hasCFUser(U, Visited, WaveSize); 10931 } 10932 if (Result) 10933 break; 10934 } 10935 return Result; 10936 } 10937 10938 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 10939 const Value *V) const { 10940 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 10941 switch (Intrinsic->getIntrinsicID()) { 10942 default: 10943 return false; 10944 case Intrinsic::amdgcn_if_break: 10945 return true; 10946 } 10947 } 10948 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 10949 if (const IntrinsicInst *Intrinsic = 10950 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 10951 switch (Intrinsic->getIntrinsicID()) { 10952 default: 10953 return false; 10954 case Intrinsic::amdgcn_if: 10955 case Intrinsic::amdgcn_else: { 10956 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 10957 if (Indices.size() == 1 && Indices[0] == 1) { 10958 return true; 10959 } 10960 } 10961 } 10962 } 10963 } 10964 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 10965 if (isa<InlineAsm>(CI->getCalledValue())) { 10966 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 10967 ImmutableCallSite CS(CI); 10968 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 10969 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 10970 for (auto &TC : TargetConstraints) { 10971 if (TC.Type == InlineAsm::isOutput) { 10972 ComputeConstraintToUse(TC, SDValue()); 10973 unsigned AssignedReg; 10974 const TargetRegisterClass *RC; 10975 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 10976 SIRI, TC.ConstraintCode, TC.ConstraintVT); 10977 if (RC) { 10978 MachineRegisterInfo &MRI = MF.getRegInfo(); 10979 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 10980 return true; 10981 else if (SIRI->isSGPRClass(RC)) 10982 return true; 10983 } 10984 } 10985 } 10986 } 10987 } 10988 SmallPtrSet<const Value *, 16> Visited; 10989 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 10990 } 10991