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 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 891 assert(DMaskLanes != 0); 892 893 if (auto *VT = dyn_cast<VectorType>(Ty)) { 894 unsigned NumElts = std::min(DMaskLanes, 895 static_cast<unsigned>(VT->getNumElements())); 896 return EVT::getVectorVT(Ty->getContext(), 897 EVT::getEVT(VT->getElementType()), 898 NumElts); 899 } 900 901 return EVT::getEVT(Ty); 902 } 903 904 // Peek through TFE struct returns to only use the data size. 905 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 906 auto *ST = dyn_cast<StructType>(Ty); 907 if (!ST) 908 return memVTFromImageData(Ty, DMaskLanes); 909 910 // Some intrinsics return an aggregate type - special case to work out the 911 // correct memVT. 912 // 913 // Only limited forms of aggregate type currently expected. 914 if (ST->getNumContainedTypes() != 2 || 915 !ST->getContainedType(1)->isIntegerTy(32)) 916 return EVT(); 917 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 918 } 919 920 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 921 const CallInst &CI, 922 MachineFunction &MF, 923 unsigned IntrID) const { 924 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 925 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 926 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 927 (Intrinsic::ID)IntrID); 928 if (Attr.hasFnAttribute(Attribute::ReadNone)) 929 return false; 930 931 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 932 933 if (RsrcIntr->IsImage) { 934 Info.ptrVal = MFI->getImagePSV( 935 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 936 CI.getArgOperand(RsrcIntr->RsrcArg)); 937 Info.align.reset(); 938 } else { 939 Info.ptrVal = MFI->getBufferPSV( 940 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 941 CI.getArgOperand(RsrcIntr->RsrcArg)); 942 } 943 944 Info.flags = MachineMemOperand::MODereferenceable; 945 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 946 unsigned DMaskLanes = 4; 947 948 if (RsrcIntr->IsImage) { 949 const AMDGPU::ImageDimIntrinsicInfo *Intr 950 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 951 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 952 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 953 954 if (!BaseOpcode->Gather4) { 955 // If this isn't a gather, we may have excess loaded elements in the 956 // IR type. Check the dmask for the real number of elements loaded. 957 unsigned DMask 958 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 959 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 960 } 961 962 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 963 } else 964 Info.memVT = EVT::getEVT(CI.getType()); 965 966 // FIXME: What does alignment mean for an image? 967 Info.opc = ISD::INTRINSIC_W_CHAIN; 968 Info.flags |= MachineMemOperand::MOLoad; 969 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 970 Info.opc = ISD::INTRINSIC_VOID; 971 972 Type *DataTy = CI.getArgOperand(0)->getType(); 973 if (RsrcIntr->IsImage) { 974 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 975 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 976 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 977 } else 978 Info.memVT = EVT::getEVT(DataTy); 979 980 Info.flags |= MachineMemOperand::MOStore; 981 } else { 982 // Atomic 983 Info.opc = ISD::INTRINSIC_W_CHAIN; 984 Info.memVT = MVT::getVT(CI.getType()); 985 Info.flags = MachineMemOperand::MOLoad | 986 MachineMemOperand::MOStore | 987 MachineMemOperand::MODereferenceable; 988 989 // XXX - Should this be volatile without known ordering? 990 Info.flags |= MachineMemOperand::MOVolatile; 991 } 992 return true; 993 } 994 995 switch (IntrID) { 996 case Intrinsic::amdgcn_atomic_inc: 997 case Intrinsic::amdgcn_atomic_dec: 998 case Intrinsic::amdgcn_ds_ordered_add: 999 case Intrinsic::amdgcn_ds_ordered_swap: 1000 case Intrinsic::amdgcn_ds_fadd: 1001 case Intrinsic::amdgcn_ds_fmin: 1002 case Intrinsic::amdgcn_ds_fmax: { 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(4)); 1010 if (!Vol->isZero()) 1011 Info.flags |= MachineMemOperand::MOVolatile; 1012 1013 return true; 1014 } 1015 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1016 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1017 1018 Info.opc = ISD::INTRINSIC_VOID; 1019 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1020 Info.ptrVal = MFI->getBufferPSV( 1021 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1022 CI.getArgOperand(1)); 1023 Info.align.reset(); 1024 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1025 1026 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1027 if (!Vol || !Vol->isZero()) 1028 Info.flags |= MachineMemOperand::MOVolatile; 1029 1030 return true; 1031 } 1032 case Intrinsic::amdgcn_global_atomic_fadd: { 1033 Info.opc = ISD::INTRINSIC_VOID; 1034 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1035 ->getPointerElementType()); 1036 Info.ptrVal = CI.getOperand(0); 1037 Info.align.reset(); 1038 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1039 1040 return true; 1041 } 1042 case Intrinsic::amdgcn_ds_append: 1043 case Intrinsic::amdgcn_ds_consume: { 1044 Info.opc = ISD::INTRINSIC_W_CHAIN; 1045 Info.memVT = MVT::getVT(CI.getType()); 1046 Info.ptrVal = CI.getOperand(0); 1047 Info.align.reset(); 1048 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1049 1050 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1051 if (!Vol->isZero()) 1052 Info.flags |= MachineMemOperand::MOVolatile; 1053 1054 return true; 1055 } 1056 case Intrinsic::amdgcn_ds_gws_init: 1057 case Intrinsic::amdgcn_ds_gws_barrier: 1058 case Intrinsic::amdgcn_ds_gws_sema_v: 1059 case Intrinsic::amdgcn_ds_gws_sema_br: 1060 case Intrinsic::amdgcn_ds_gws_sema_p: 1061 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1062 Info.opc = ISD::INTRINSIC_VOID; 1063 1064 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1065 Info.ptrVal = 1066 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1067 1068 // This is an abstract access, but we need to specify a type and size. 1069 Info.memVT = MVT::i32; 1070 Info.size = 4; 1071 Info.align = Align(4); 1072 1073 Info.flags = MachineMemOperand::MOStore; 1074 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1075 Info.flags = MachineMemOperand::MOLoad; 1076 return true; 1077 } 1078 default: 1079 return false; 1080 } 1081 } 1082 1083 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1084 SmallVectorImpl<Value*> &Ops, 1085 Type *&AccessTy) const { 1086 switch (II->getIntrinsicID()) { 1087 case Intrinsic::amdgcn_atomic_inc: 1088 case Intrinsic::amdgcn_atomic_dec: 1089 case Intrinsic::amdgcn_ds_ordered_add: 1090 case Intrinsic::amdgcn_ds_ordered_swap: 1091 case Intrinsic::amdgcn_ds_fadd: 1092 case Intrinsic::amdgcn_ds_fmin: 1093 case Intrinsic::amdgcn_ds_fmax: { 1094 Value *Ptr = II->getArgOperand(0); 1095 AccessTy = II->getType(); 1096 Ops.push_back(Ptr); 1097 return true; 1098 } 1099 default: 1100 return false; 1101 } 1102 } 1103 1104 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1105 if (!Subtarget->hasFlatInstOffsets()) { 1106 // Flat instructions do not have offsets, and only have the register 1107 // address. 1108 return AM.BaseOffs == 0 && AM.Scale == 0; 1109 } 1110 1111 return AM.Scale == 0 && 1112 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1113 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1114 /*Signed=*/false)); 1115 } 1116 1117 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1118 if (Subtarget->hasFlatGlobalInsts()) 1119 return AM.Scale == 0 && 1120 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1121 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1122 /*Signed=*/true)); 1123 1124 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1125 // Assume the we will use FLAT for all global memory accesses 1126 // on VI. 1127 // FIXME: This assumption is currently wrong. On VI we still use 1128 // MUBUF instructions for the r + i addressing mode. As currently 1129 // implemented, the MUBUF instructions only work on buffer < 4GB. 1130 // It may be possible to support > 4GB buffers with MUBUF instructions, 1131 // by setting the stride value in the resource descriptor which would 1132 // increase the size limit to (stride * 4GB). However, this is risky, 1133 // because it has never been validated. 1134 return isLegalFlatAddressingMode(AM); 1135 } 1136 1137 return isLegalMUBUFAddressingMode(AM); 1138 } 1139 1140 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1141 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1142 // additionally can do r + r + i with addr64. 32-bit has more addressing 1143 // mode options. Depending on the resource constant, it can also do 1144 // (i64 r0) + (i32 r1) * (i14 i). 1145 // 1146 // Private arrays end up using a scratch buffer most of the time, so also 1147 // assume those use MUBUF instructions. Scratch loads / stores are currently 1148 // implemented as mubuf instructions with offen bit set, so slightly 1149 // different than the normal addr64. 1150 if (!isUInt<12>(AM.BaseOffs)) 1151 return false; 1152 1153 // FIXME: Since we can split immediate into soffset and immediate offset, 1154 // would it make sense to allow any immediate? 1155 1156 switch (AM.Scale) { 1157 case 0: // r + i or just i, depending on HasBaseReg. 1158 return true; 1159 case 1: 1160 return true; // We have r + r or r + i. 1161 case 2: 1162 if (AM.HasBaseReg) { 1163 // Reject 2 * r + r. 1164 return false; 1165 } 1166 1167 // Allow 2 * r as r + r 1168 // Or 2 * r + i is allowed as r + r + i. 1169 return true; 1170 default: // Don't allow n * r 1171 return false; 1172 } 1173 } 1174 1175 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1176 const AddrMode &AM, Type *Ty, 1177 unsigned AS, Instruction *I) const { 1178 // No global is ever allowed as a base. 1179 if (AM.BaseGV) 1180 return false; 1181 1182 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1183 return isLegalGlobalAddressingMode(AM); 1184 1185 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1186 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1187 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1188 // If the offset isn't a multiple of 4, it probably isn't going to be 1189 // correctly aligned. 1190 // FIXME: Can we get the real alignment here? 1191 if (AM.BaseOffs % 4 != 0) 1192 return isLegalMUBUFAddressingMode(AM); 1193 1194 // There are no SMRD extloads, so if we have to do a small type access we 1195 // will use a MUBUF load. 1196 // FIXME?: We also need to do this if unaligned, but we don't know the 1197 // alignment here. 1198 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1199 return isLegalGlobalAddressingMode(AM); 1200 1201 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1202 // SMRD instructions have an 8-bit, dword offset on SI. 1203 if (!isUInt<8>(AM.BaseOffs / 4)) 1204 return false; 1205 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1206 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1207 // in 8-bits, it can use a smaller encoding. 1208 if (!isUInt<32>(AM.BaseOffs / 4)) 1209 return false; 1210 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1211 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1212 if (!isUInt<20>(AM.BaseOffs)) 1213 return false; 1214 } else 1215 llvm_unreachable("unhandled generation"); 1216 1217 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1218 return true; 1219 1220 if (AM.Scale == 1 && AM.HasBaseReg) 1221 return true; 1222 1223 return false; 1224 1225 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1226 return isLegalMUBUFAddressingMode(AM); 1227 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1228 AS == AMDGPUAS::REGION_ADDRESS) { 1229 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1230 // field. 1231 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1232 // an 8-bit dword offset but we don't know the alignment here. 1233 if (!isUInt<16>(AM.BaseOffs)) 1234 return false; 1235 1236 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1237 return true; 1238 1239 if (AM.Scale == 1 && AM.HasBaseReg) 1240 return true; 1241 1242 return false; 1243 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1244 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1245 // For an unknown address space, this usually means that this is for some 1246 // reason being used for pure arithmetic, and not based on some addressing 1247 // computation. We don't have instructions that compute pointers with any 1248 // addressing modes, so treat them as having no offset like flat 1249 // instructions. 1250 return isLegalFlatAddressingMode(AM); 1251 } else { 1252 llvm_unreachable("unhandled address space"); 1253 } 1254 } 1255 1256 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1257 const SelectionDAG &DAG) const { 1258 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1259 return (MemVT.getSizeInBits() <= 4 * 32); 1260 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1261 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1262 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1263 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1264 return (MemVT.getSizeInBits() <= 2 * 32); 1265 } 1266 return true; 1267 } 1268 1269 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1270 unsigned Size, unsigned AddrSpace, unsigned Align, 1271 MachineMemOperand::Flags Flags, bool *IsFast) const { 1272 if (IsFast) 1273 *IsFast = false; 1274 1275 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1276 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1277 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1278 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1279 // with adjacent offsets. 1280 bool AlignedBy4 = (Align % 4 == 0); 1281 if (IsFast) 1282 *IsFast = AlignedBy4; 1283 1284 return AlignedBy4; 1285 } 1286 1287 // FIXME: We have to be conservative here and assume that flat operations 1288 // will access scratch. If we had access to the IR function, then we 1289 // could determine if any private memory was used in the function. 1290 if (!Subtarget->hasUnalignedScratchAccess() && 1291 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1292 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1293 bool AlignedBy4 = Align >= 4; 1294 if (IsFast) 1295 *IsFast = AlignedBy4; 1296 1297 return AlignedBy4; 1298 } 1299 1300 if (Subtarget->hasUnalignedBufferAccess()) { 1301 // If we have an uniform constant load, it still requires using a slow 1302 // buffer instruction if unaligned. 1303 if (IsFast) { 1304 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1305 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1306 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1307 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1308 Align >= 4 : Align != 2; 1309 } 1310 1311 return true; 1312 } 1313 1314 // Smaller than dword value must be aligned. 1315 if (Size < 32) 1316 return false; 1317 1318 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1319 // byte-address are ignored, thus forcing Dword alignment. 1320 // This applies to private, global, and constant memory. 1321 if (IsFast) 1322 *IsFast = true; 1323 1324 return Size >= 32 && Align >= 4; 1325 } 1326 1327 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1328 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1329 bool *IsFast) const { 1330 if (IsFast) 1331 *IsFast = false; 1332 1333 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1334 // which isn't a simple VT. 1335 // Until MVT is extended to handle this, simply check for the size and 1336 // rely on the condition below: allow accesses if the size is a multiple of 4. 1337 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1338 VT.getStoreSize() > 16)) { 1339 return false; 1340 } 1341 1342 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1343 Align, Flags, IsFast); 1344 } 1345 1346 EVT SITargetLowering::getOptimalMemOpType( 1347 const MemOp &Op, const AttributeList &FuncAttributes) const { 1348 // FIXME: Should account for address space here. 1349 1350 // The default fallback uses the private pointer size as a guess for a type to 1351 // use. Make sure we switch these to 64-bit accesses. 1352 1353 if (Op.size() >= 16 && 1354 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1355 return MVT::v4i32; 1356 1357 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1358 return MVT::v2i32; 1359 1360 // Use the default. 1361 return MVT::Other; 1362 } 1363 1364 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1365 unsigned DestAS) const { 1366 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1367 } 1368 1369 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1370 const MemSDNode *MemNode = cast<MemSDNode>(N); 1371 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1372 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1373 return I && I->getMetadata("amdgpu.noclobber"); 1374 } 1375 1376 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1377 unsigned DestAS) const { 1378 // Flat -> private/local is a simple truncate. 1379 // Flat -> global is no-op 1380 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1381 return true; 1382 1383 return isNoopAddrSpaceCast(SrcAS, DestAS); 1384 } 1385 1386 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1387 const MemSDNode *MemNode = cast<MemSDNode>(N); 1388 1389 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1390 } 1391 1392 TargetLoweringBase::LegalizeTypeAction 1393 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1394 int NumElts = VT.getVectorNumElements(); 1395 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1396 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1397 return TargetLoweringBase::getPreferredVectorAction(VT); 1398 } 1399 1400 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1401 Type *Ty) const { 1402 // FIXME: Could be smarter if called for vector constants. 1403 return true; 1404 } 1405 1406 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1407 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1408 switch (Op) { 1409 case ISD::LOAD: 1410 case ISD::STORE: 1411 1412 // These operations are done with 32-bit instructions anyway. 1413 case ISD::AND: 1414 case ISD::OR: 1415 case ISD::XOR: 1416 case ISD::SELECT: 1417 // TODO: Extensions? 1418 return true; 1419 default: 1420 return false; 1421 } 1422 } 1423 1424 // SimplifySetCC uses this function to determine whether or not it should 1425 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1426 if (VT == MVT::i1 && Op == ISD::SETCC) 1427 return false; 1428 1429 return TargetLowering::isTypeDesirableForOp(Op, VT); 1430 } 1431 1432 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1433 const SDLoc &SL, 1434 SDValue Chain, 1435 uint64_t Offset) const { 1436 const DataLayout &DL = DAG.getDataLayout(); 1437 MachineFunction &MF = DAG.getMachineFunction(); 1438 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1439 1440 const ArgDescriptor *InputPtrReg; 1441 const TargetRegisterClass *RC; 1442 1443 std::tie(InputPtrReg, RC) 1444 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1445 1446 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1447 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1448 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1449 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1450 1451 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1452 } 1453 1454 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1455 const SDLoc &SL) const { 1456 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1457 FIRST_IMPLICIT); 1458 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1459 } 1460 1461 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1462 const SDLoc &SL, SDValue Val, 1463 bool Signed, 1464 const ISD::InputArg *Arg) const { 1465 // First, if it is a widened vector, narrow it. 1466 if (VT.isVector() && 1467 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1468 EVT NarrowedVT = 1469 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1470 VT.getVectorNumElements()); 1471 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1472 DAG.getConstant(0, SL, MVT::i32)); 1473 } 1474 1475 // Then convert the vector elements or scalar value. 1476 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1477 VT.bitsLT(MemVT)) { 1478 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1479 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1480 } 1481 1482 if (MemVT.isFloatingPoint()) 1483 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1484 else if (Signed) 1485 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1486 else 1487 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1488 1489 return Val; 1490 } 1491 1492 SDValue SITargetLowering::lowerKernargMemParameter( 1493 SelectionDAG &DAG, EVT VT, EVT MemVT, 1494 const SDLoc &SL, SDValue Chain, 1495 uint64_t Offset, unsigned Align, bool Signed, 1496 const ISD::InputArg *Arg) const { 1497 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1498 1499 // Try to avoid using an extload by loading earlier than the argument address, 1500 // and extracting the relevant bits. The load should hopefully be merged with 1501 // the previous argument. 1502 if (MemVT.getStoreSize() < 4 && Align < 4) { 1503 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1504 int64_t AlignDownOffset = alignDown(Offset, 4); 1505 int64_t OffsetDiff = Offset - AlignDownOffset; 1506 1507 EVT IntVT = MemVT.changeTypeToInteger(); 1508 1509 // TODO: If we passed in the base kernel offset we could have a better 1510 // alignment than 4, but we don't really need it. 1511 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1512 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1513 MachineMemOperand::MODereferenceable | 1514 MachineMemOperand::MOInvariant); 1515 1516 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1517 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1518 1519 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1520 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1521 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1522 1523 1524 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1525 } 1526 1527 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1528 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1529 MachineMemOperand::MODereferenceable | 1530 MachineMemOperand::MOInvariant); 1531 1532 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1533 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1534 } 1535 1536 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1537 const SDLoc &SL, SDValue Chain, 1538 const ISD::InputArg &Arg) const { 1539 MachineFunction &MF = DAG.getMachineFunction(); 1540 MachineFrameInfo &MFI = MF.getFrameInfo(); 1541 1542 if (Arg.Flags.isByVal()) { 1543 unsigned Size = Arg.Flags.getByValSize(); 1544 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1545 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1546 } 1547 1548 unsigned ArgOffset = VA.getLocMemOffset(); 1549 unsigned ArgSize = VA.getValVT().getStoreSize(); 1550 1551 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1552 1553 // Create load nodes to retrieve arguments from the stack. 1554 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1555 SDValue ArgValue; 1556 1557 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1558 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1559 MVT MemVT = VA.getValVT(); 1560 1561 switch (VA.getLocInfo()) { 1562 default: 1563 break; 1564 case CCValAssign::BCvt: 1565 MemVT = VA.getLocVT(); 1566 break; 1567 case CCValAssign::SExt: 1568 ExtType = ISD::SEXTLOAD; 1569 break; 1570 case CCValAssign::ZExt: 1571 ExtType = ISD::ZEXTLOAD; 1572 break; 1573 case CCValAssign::AExt: 1574 ExtType = ISD::EXTLOAD; 1575 break; 1576 } 1577 1578 ArgValue = DAG.getExtLoad( 1579 ExtType, SL, VA.getLocVT(), Chain, FIN, 1580 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1581 MemVT); 1582 return ArgValue; 1583 } 1584 1585 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1586 const SIMachineFunctionInfo &MFI, 1587 EVT VT, 1588 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1589 const ArgDescriptor *Reg; 1590 const TargetRegisterClass *RC; 1591 1592 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1593 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1594 } 1595 1596 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1597 CallingConv::ID CallConv, 1598 ArrayRef<ISD::InputArg> Ins, 1599 BitVector &Skipped, 1600 FunctionType *FType, 1601 SIMachineFunctionInfo *Info) { 1602 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1603 const ISD::InputArg *Arg = &Ins[I]; 1604 1605 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1606 "vector type argument should have been split"); 1607 1608 // First check if it's a PS input addr. 1609 if (CallConv == CallingConv::AMDGPU_PS && 1610 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1611 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1612 1613 // Inconveniently only the first part of the split is marked as isSplit, 1614 // so skip to the end. We only want to increment PSInputNum once for the 1615 // entire split argument. 1616 if (Arg->Flags.isSplit()) { 1617 while (!Arg->Flags.isSplitEnd()) { 1618 assert((!Arg->VT.isVector() || 1619 Arg->VT.getScalarSizeInBits() == 16) && 1620 "unexpected vector split in ps argument type"); 1621 if (!SkipArg) 1622 Splits.push_back(*Arg); 1623 Arg = &Ins[++I]; 1624 } 1625 } 1626 1627 if (SkipArg) { 1628 // We can safely skip PS inputs. 1629 Skipped.set(Arg->getOrigArgIndex()); 1630 ++PSInputNum; 1631 continue; 1632 } 1633 1634 Info->markPSInputAllocated(PSInputNum); 1635 if (Arg->Used) 1636 Info->markPSInputEnabled(PSInputNum); 1637 1638 ++PSInputNum; 1639 } 1640 1641 Splits.push_back(*Arg); 1642 } 1643 } 1644 1645 // Allocate special inputs passed in VGPRs. 1646 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1647 MachineFunction &MF, 1648 const SIRegisterInfo &TRI, 1649 SIMachineFunctionInfo &Info) const { 1650 const LLT S32 = LLT::scalar(32); 1651 MachineRegisterInfo &MRI = MF.getRegInfo(); 1652 1653 if (Info.hasWorkItemIDX()) { 1654 Register Reg = AMDGPU::VGPR0; 1655 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1656 1657 CCInfo.AllocateReg(Reg); 1658 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1659 } 1660 1661 if (Info.hasWorkItemIDY()) { 1662 Register Reg = AMDGPU::VGPR1; 1663 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1664 1665 CCInfo.AllocateReg(Reg); 1666 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1667 } 1668 1669 if (Info.hasWorkItemIDZ()) { 1670 Register Reg = AMDGPU::VGPR2; 1671 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1672 1673 CCInfo.AllocateReg(Reg); 1674 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1675 } 1676 } 1677 1678 // Try to allocate a VGPR at the end of the argument list, or if no argument 1679 // VGPRs are left allocating a stack slot. 1680 // If \p Mask is is given it indicates bitfield position in the register. 1681 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1682 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1683 ArgDescriptor Arg = ArgDescriptor()) { 1684 if (Arg.isSet()) 1685 return ArgDescriptor::createArg(Arg, Mask); 1686 1687 ArrayRef<MCPhysReg> ArgVGPRs 1688 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1689 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1690 if (RegIdx == ArgVGPRs.size()) { 1691 // Spill to stack required. 1692 int64_t Offset = CCInfo.AllocateStack(4, 4); 1693 1694 return ArgDescriptor::createStack(Offset, Mask); 1695 } 1696 1697 unsigned Reg = ArgVGPRs[RegIdx]; 1698 Reg = CCInfo.AllocateReg(Reg); 1699 assert(Reg != AMDGPU::NoRegister); 1700 1701 MachineFunction &MF = CCInfo.getMachineFunction(); 1702 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1703 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1704 return ArgDescriptor::createRegister(Reg, Mask); 1705 } 1706 1707 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1708 const TargetRegisterClass *RC, 1709 unsigned NumArgRegs) { 1710 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1711 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1712 if (RegIdx == ArgSGPRs.size()) 1713 report_fatal_error("ran out of SGPRs for arguments"); 1714 1715 unsigned Reg = ArgSGPRs[RegIdx]; 1716 Reg = CCInfo.AllocateReg(Reg); 1717 assert(Reg != AMDGPU::NoRegister); 1718 1719 MachineFunction &MF = CCInfo.getMachineFunction(); 1720 MF.addLiveIn(Reg, RC); 1721 return ArgDescriptor::createRegister(Reg); 1722 } 1723 1724 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1725 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1726 } 1727 1728 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1729 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1730 } 1731 1732 /// Allocate implicit function VGPR arguments at the end of allocated user 1733 /// arguments. 1734 void SITargetLowering::allocateSpecialInputVGPRs( 1735 CCState &CCInfo, MachineFunction &MF, 1736 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1737 const unsigned Mask = 0x3ff; 1738 ArgDescriptor Arg; 1739 1740 if (Info.hasWorkItemIDX()) { 1741 Arg = allocateVGPR32Input(CCInfo, Mask); 1742 Info.setWorkItemIDX(Arg); 1743 } 1744 1745 if (Info.hasWorkItemIDY()) { 1746 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1747 Info.setWorkItemIDY(Arg); 1748 } 1749 1750 if (Info.hasWorkItemIDZ()) 1751 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1752 } 1753 1754 /// Allocate implicit function VGPR arguments in fixed registers. 1755 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1756 CCState &CCInfo, MachineFunction &MF, 1757 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1758 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1759 if (!Reg) 1760 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1761 1762 const unsigned Mask = 0x3ff; 1763 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1764 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1765 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1766 } 1767 1768 void SITargetLowering::allocateSpecialInputSGPRs( 1769 CCState &CCInfo, 1770 MachineFunction &MF, 1771 const SIRegisterInfo &TRI, 1772 SIMachineFunctionInfo &Info) const { 1773 auto &ArgInfo = Info.getArgInfo(); 1774 1775 // TODO: Unify handling with private memory pointers. 1776 1777 if (Info.hasDispatchPtr()) 1778 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1779 1780 if (Info.hasQueuePtr()) 1781 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1782 1783 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1784 // constant offset from the kernarg segment. 1785 if (Info.hasImplicitArgPtr()) 1786 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1787 1788 if (Info.hasDispatchID()) 1789 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1790 1791 // flat_scratch_init is not applicable for non-kernel functions. 1792 1793 if (Info.hasWorkGroupIDX()) 1794 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1795 1796 if (Info.hasWorkGroupIDY()) 1797 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1798 1799 if (Info.hasWorkGroupIDZ()) 1800 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1801 } 1802 1803 // Allocate special inputs passed in user SGPRs. 1804 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1805 MachineFunction &MF, 1806 const SIRegisterInfo &TRI, 1807 SIMachineFunctionInfo &Info) const { 1808 if (Info.hasImplicitBufferPtr()) { 1809 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1810 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1811 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1812 } 1813 1814 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1815 if (Info.hasPrivateSegmentBuffer()) { 1816 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1817 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1818 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1819 } 1820 1821 if (Info.hasDispatchPtr()) { 1822 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1823 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1824 CCInfo.AllocateReg(DispatchPtrReg); 1825 } 1826 1827 if (Info.hasQueuePtr()) { 1828 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1829 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1830 CCInfo.AllocateReg(QueuePtrReg); 1831 } 1832 1833 if (Info.hasKernargSegmentPtr()) { 1834 MachineRegisterInfo &MRI = MF.getRegInfo(); 1835 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1836 CCInfo.AllocateReg(InputPtrReg); 1837 1838 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1839 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1840 } 1841 1842 if (Info.hasDispatchID()) { 1843 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1844 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1845 CCInfo.AllocateReg(DispatchIDReg); 1846 } 1847 1848 if (Info.hasFlatScratchInit()) { 1849 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1850 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1851 CCInfo.AllocateReg(FlatScratchInitReg); 1852 } 1853 1854 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1855 // these from the dispatch pointer. 1856 } 1857 1858 // Allocate special input registers that are initialized per-wave. 1859 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1860 MachineFunction &MF, 1861 SIMachineFunctionInfo &Info, 1862 CallingConv::ID CallConv, 1863 bool IsShader) const { 1864 if (Info.hasWorkGroupIDX()) { 1865 unsigned Reg = Info.addWorkGroupIDX(); 1866 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1867 CCInfo.AllocateReg(Reg); 1868 } 1869 1870 if (Info.hasWorkGroupIDY()) { 1871 unsigned Reg = Info.addWorkGroupIDY(); 1872 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1873 CCInfo.AllocateReg(Reg); 1874 } 1875 1876 if (Info.hasWorkGroupIDZ()) { 1877 unsigned Reg = Info.addWorkGroupIDZ(); 1878 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1879 CCInfo.AllocateReg(Reg); 1880 } 1881 1882 if (Info.hasWorkGroupInfo()) { 1883 unsigned Reg = Info.addWorkGroupInfo(); 1884 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1885 CCInfo.AllocateReg(Reg); 1886 } 1887 1888 if (Info.hasPrivateSegmentWaveByteOffset()) { 1889 // Scratch wave offset passed in system SGPR. 1890 unsigned PrivateSegmentWaveByteOffsetReg; 1891 1892 if (IsShader) { 1893 PrivateSegmentWaveByteOffsetReg = 1894 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1895 1896 // This is true if the scratch wave byte offset doesn't have a fixed 1897 // location. 1898 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1899 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1900 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1901 } 1902 } else 1903 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1904 1905 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1906 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1907 } 1908 } 1909 1910 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1911 MachineFunction &MF, 1912 const SIRegisterInfo &TRI, 1913 SIMachineFunctionInfo &Info) { 1914 // Now that we've figured out where the scratch register inputs are, see if 1915 // should reserve the arguments and use them directly. 1916 MachineFrameInfo &MFI = MF.getFrameInfo(); 1917 bool HasStackObjects = MFI.hasStackObjects(); 1918 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1919 1920 // Record that we know we have non-spill stack objects so we don't need to 1921 // check all stack objects later. 1922 if (HasStackObjects) 1923 Info.setHasNonSpillStackObjects(true); 1924 1925 // Everything live out of a block is spilled with fast regalloc, so it's 1926 // almost certain that spilling will be required. 1927 if (TM.getOptLevel() == CodeGenOpt::None) 1928 HasStackObjects = true; 1929 1930 // For now assume stack access is needed in any callee functions, so we need 1931 // the scratch registers to pass in. 1932 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1933 1934 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1935 // If we have stack objects, we unquestionably need the private buffer 1936 // resource. For the Code Object V2 ABI, this will be the first 4 user 1937 // SGPR inputs. We can reserve those and use them directly. 1938 1939 Register PrivateSegmentBufferReg = 1940 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1941 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1942 } else { 1943 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1944 // We tentatively reserve the last registers (skipping the last registers 1945 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1946 // we'll replace these with the ones immediately after those which were 1947 // really allocated. In the prologue copies will be inserted from the 1948 // argument to these reserved registers. 1949 1950 // Without HSA, relocations are used for the scratch pointer and the 1951 // buffer resource setup is always inserted in the prologue. Scratch wave 1952 // offset is still in an input SGPR. 1953 Info.setScratchRSrcReg(ReservedBufferReg); 1954 } 1955 1956 MachineRegisterInfo &MRI = MF.getRegInfo(); 1957 1958 // For entry functions we have to set up the stack pointer if we use it, 1959 // whereas non-entry functions get this "for free". This means there is no 1960 // intrinsic advantage to using S32 over S34 in cases where we do not have 1961 // calls but do need a frame pointer (i.e. if we are requested to have one 1962 // because frame pointer elimination is disabled). To keep things simple we 1963 // only ever use S32 as the call ABI stack pointer, and so using it does not 1964 // imply we need a separate frame pointer. 1965 // 1966 // Try to use s32 as the SP, but move it if it would interfere with input 1967 // arguments. This won't work with calls though. 1968 // 1969 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1970 // registers. 1971 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1972 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1973 } else { 1974 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1975 1976 if (MFI.hasCalls()) 1977 report_fatal_error("call in graphics shader with too many input SGPRs"); 1978 1979 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1980 if (!MRI.isLiveIn(Reg)) { 1981 Info.setStackPtrOffsetReg(Reg); 1982 break; 1983 } 1984 } 1985 1986 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1987 report_fatal_error("failed to find register for SP"); 1988 } 1989 1990 // hasFP should be accurate for entry functions even before the frame is 1991 // finalized, because it does not rely on the known stack size, only 1992 // properties like whether variable sized objects are present. 1993 if (ST.getFrameLowering()->hasFP(MF)) { 1994 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1995 } 1996 } 1997 1998 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1999 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2000 return !Info->isEntryFunction(); 2001 } 2002 2003 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2004 2005 } 2006 2007 void SITargetLowering::insertCopiesSplitCSR( 2008 MachineBasicBlock *Entry, 2009 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2010 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2011 2012 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2013 if (!IStart) 2014 return; 2015 2016 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2017 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2018 MachineBasicBlock::iterator MBBI = Entry->begin(); 2019 for (const MCPhysReg *I = IStart; *I; ++I) { 2020 const TargetRegisterClass *RC = nullptr; 2021 if (AMDGPU::SReg_64RegClass.contains(*I)) 2022 RC = &AMDGPU::SGPR_64RegClass; 2023 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2024 RC = &AMDGPU::SGPR_32RegClass; 2025 else 2026 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2027 2028 Register NewVR = MRI->createVirtualRegister(RC); 2029 // Create copy from CSR to a virtual register. 2030 Entry->addLiveIn(*I); 2031 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2032 .addReg(*I); 2033 2034 // Insert the copy-back instructions right before the terminator. 2035 for (auto *Exit : Exits) 2036 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2037 TII->get(TargetOpcode::COPY), *I) 2038 .addReg(NewVR); 2039 } 2040 } 2041 2042 SDValue SITargetLowering::LowerFormalArguments( 2043 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2044 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2045 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2046 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2047 2048 MachineFunction &MF = DAG.getMachineFunction(); 2049 const Function &Fn = MF.getFunction(); 2050 FunctionType *FType = MF.getFunction().getFunctionType(); 2051 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2052 2053 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2054 DiagnosticInfoUnsupported NoGraphicsHSA( 2055 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2056 DAG.getContext()->diagnose(NoGraphicsHSA); 2057 return DAG.getEntryNode(); 2058 } 2059 2060 SmallVector<ISD::InputArg, 16> Splits; 2061 SmallVector<CCValAssign, 16> ArgLocs; 2062 BitVector Skipped(Ins.size()); 2063 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2064 *DAG.getContext()); 2065 2066 bool IsShader = AMDGPU::isShader(CallConv); 2067 bool IsKernel = AMDGPU::isKernel(CallConv); 2068 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2069 2070 if (IsShader) { 2071 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2072 2073 // At least one interpolation mode must be enabled or else the GPU will 2074 // hang. 2075 // 2076 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2077 // set PSInputAddr, the user wants to enable some bits after the compilation 2078 // based on run-time states. Since we can't know what the final PSInputEna 2079 // will look like, so we shouldn't do anything here and the user should take 2080 // responsibility for the correct programming. 2081 // 2082 // Otherwise, the following restrictions apply: 2083 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2084 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2085 // enabled too. 2086 if (CallConv == CallingConv::AMDGPU_PS) { 2087 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2088 ((Info->getPSInputAddr() & 0xF) == 0 && 2089 Info->isPSInputAllocated(11))) { 2090 CCInfo.AllocateReg(AMDGPU::VGPR0); 2091 CCInfo.AllocateReg(AMDGPU::VGPR1); 2092 Info->markPSInputAllocated(0); 2093 Info->markPSInputEnabled(0); 2094 } 2095 if (Subtarget->isAmdPalOS()) { 2096 // For isAmdPalOS, the user does not enable some bits after compilation 2097 // based on run-time states; the register values being generated here are 2098 // the final ones set in hardware. Therefore we need to apply the 2099 // workaround to PSInputAddr and PSInputEnable together. (The case where 2100 // a bit is set in PSInputAddr but not PSInputEnable is where the 2101 // frontend set up an input arg for a particular interpolation mode, but 2102 // nothing uses that input arg. Really we should have an earlier pass 2103 // that removes such an arg.) 2104 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2105 if ((PsInputBits & 0x7F) == 0 || 2106 ((PsInputBits & 0xF) == 0 && 2107 (PsInputBits >> 11 & 1))) 2108 Info->markPSInputEnabled( 2109 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2110 } 2111 } 2112 2113 assert(!Info->hasDispatchPtr() && 2114 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2115 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2116 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2117 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2118 !Info->hasWorkItemIDZ()); 2119 } else if (IsKernel) { 2120 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2121 } else { 2122 Splits.append(Ins.begin(), Ins.end()); 2123 } 2124 2125 if (IsEntryFunc) { 2126 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2127 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2128 } else { 2129 // For the fixed ABI, pass workitem IDs in the last argument register. 2130 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2131 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2132 } 2133 2134 if (IsKernel) { 2135 analyzeFormalArgumentsCompute(CCInfo, Ins); 2136 } else { 2137 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2138 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2139 } 2140 2141 SmallVector<SDValue, 16> Chains; 2142 2143 // FIXME: This is the minimum kernel argument alignment. We should improve 2144 // this to the maximum alignment of the arguments. 2145 // 2146 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2147 // kern arg offset. 2148 const unsigned KernelArgBaseAlign = 16; 2149 2150 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2151 const ISD::InputArg &Arg = Ins[i]; 2152 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2153 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2154 continue; 2155 } 2156 2157 CCValAssign &VA = ArgLocs[ArgIdx++]; 2158 MVT VT = VA.getLocVT(); 2159 2160 if (IsEntryFunc && VA.isMemLoc()) { 2161 VT = Ins[i].VT; 2162 EVT MemVT = VA.getLocVT(); 2163 2164 const uint64_t Offset = VA.getLocMemOffset(); 2165 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2166 2167 SDValue Arg = lowerKernargMemParameter( 2168 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2169 Chains.push_back(Arg.getValue(1)); 2170 2171 auto *ParamTy = 2172 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2173 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2174 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2175 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2176 // On SI local pointers are just offsets into LDS, so they are always 2177 // less than 16-bits. On CI and newer they could potentially be 2178 // real pointers, so we can't guarantee their size. 2179 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2180 DAG.getValueType(MVT::i16)); 2181 } 2182 2183 InVals.push_back(Arg); 2184 continue; 2185 } else if (!IsEntryFunc && VA.isMemLoc()) { 2186 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2187 InVals.push_back(Val); 2188 if (!Arg.Flags.isByVal()) 2189 Chains.push_back(Val.getValue(1)); 2190 continue; 2191 } 2192 2193 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2194 2195 Register Reg = VA.getLocReg(); 2196 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2197 EVT ValVT = VA.getValVT(); 2198 2199 Reg = MF.addLiveIn(Reg, RC); 2200 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2201 2202 if (Arg.Flags.isSRet()) { 2203 // The return object should be reasonably addressable. 2204 2205 // FIXME: This helps when the return is a real sret. If it is a 2206 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2207 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2208 unsigned NumBits 2209 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2210 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2211 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2212 } 2213 2214 // If this is an 8 or 16-bit value, it is really passed promoted 2215 // to 32 bits. Insert an assert[sz]ext to capture this, then 2216 // truncate to the right size. 2217 switch (VA.getLocInfo()) { 2218 case CCValAssign::Full: 2219 break; 2220 case CCValAssign::BCvt: 2221 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2222 break; 2223 case CCValAssign::SExt: 2224 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2225 DAG.getValueType(ValVT)); 2226 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2227 break; 2228 case CCValAssign::ZExt: 2229 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2230 DAG.getValueType(ValVT)); 2231 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2232 break; 2233 case CCValAssign::AExt: 2234 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2235 break; 2236 default: 2237 llvm_unreachable("Unknown loc info!"); 2238 } 2239 2240 InVals.push_back(Val); 2241 } 2242 2243 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2244 // Special inputs come after user arguments. 2245 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2246 } 2247 2248 // Start adding system SGPRs. 2249 if (IsEntryFunc) { 2250 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2251 } else { 2252 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2253 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2254 } 2255 2256 auto &ArgUsageInfo = 2257 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2258 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2259 2260 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2261 Info->setBytesInStackArgArea(StackArgSize); 2262 2263 return Chains.empty() ? Chain : 2264 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2265 } 2266 2267 // TODO: If return values can't fit in registers, we should return as many as 2268 // possible in registers before passing on stack. 2269 bool SITargetLowering::CanLowerReturn( 2270 CallingConv::ID CallConv, 2271 MachineFunction &MF, bool IsVarArg, 2272 const SmallVectorImpl<ISD::OutputArg> &Outs, 2273 LLVMContext &Context) const { 2274 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2275 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2276 // for shaders. Vector types should be explicitly handled by CC. 2277 if (AMDGPU::isEntryFunctionCC(CallConv)) 2278 return true; 2279 2280 SmallVector<CCValAssign, 16> RVLocs; 2281 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2282 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2283 } 2284 2285 SDValue 2286 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2287 bool isVarArg, 2288 const SmallVectorImpl<ISD::OutputArg> &Outs, 2289 const SmallVectorImpl<SDValue> &OutVals, 2290 const SDLoc &DL, SelectionDAG &DAG) const { 2291 MachineFunction &MF = DAG.getMachineFunction(); 2292 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2293 2294 if (AMDGPU::isKernel(CallConv)) { 2295 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2296 OutVals, DL, DAG); 2297 } 2298 2299 bool IsShader = AMDGPU::isShader(CallConv); 2300 2301 Info->setIfReturnsVoid(Outs.empty()); 2302 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2303 2304 // CCValAssign - represent the assignment of the return value to a location. 2305 SmallVector<CCValAssign, 48> RVLocs; 2306 SmallVector<ISD::OutputArg, 48> Splits; 2307 2308 // CCState - Info about the registers and stack slots. 2309 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2310 *DAG.getContext()); 2311 2312 // Analyze outgoing return values. 2313 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2314 2315 SDValue Flag; 2316 SmallVector<SDValue, 48> RetOps; 2317 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2318 2319 // Add return address for callable functions. 2320 if (!Info->isEntryFunction()) { 2321 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2322 SDValue ReturnAddrReg = CreateLiveInRegister( 2323 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2324 2325 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2326 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2327 MVT::i64); 2328 Chain = 2329 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2330 Flag = Chain.getValue(1); 2331 RetOps.push_back(ReturnAddrVirtualReg); 2332 } 2333 2334 // Copy the result values into the output registers. 2335 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2336 ++I, ++RealRVLocIdx) { 2337 CCValAssign &VA = RVLocs[I]; 2338 assert(VA.isRegLoc() && "Can only return in registers!"); 2339 // TODO: Partially return in registers if return values don't fit. 2340 SDValue Arg = OutVals[RealRVLocIdx]; 2341 2342 // Copied from other backends. 2343 switch (VA.getLocInfo()) { 2344 case CCValAssign::Full: 2345 break; 2346 case CCValAssign::BCvt: 2347 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2348 break; 2349 case CCValAssign::SExt: 2350 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2351 break; 2352 case CCValAssign::ZExt: 2353 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2354 break; 2355 case CCValAssign::AExt: 2356 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2357 break; 2358 default: 2359 llvm_unreachable("Unknown loc info!"); 2360 } 2361 2362 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2363 Flag = Chain.getValue(1); 2364 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2365 } 2366 2367 // FIXME: Does sret work properly? 2368 if (!Info->isEntryFunction()) { 2369 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2370 const MCPhysReg *I = 2371 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2372 if (I) { 2373 for (; *I; ++I) { 2374 if (AMDGPU::SReg_64RegClass.contains(*I)) 2375 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2376 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2377 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2378 else 2379 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2380 } 2381 } 2382 } 2383 2384 // Update chain and glue. 2385 RetOps[0] = Chain; 2386 if (Flag.getNode()) 2387 RetOps.push_back(Flag); 2388 2389 unsigned Opc = AMDGPUISD::ENDPGM; 2390 if (!IsWaveEnd) 2391 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2392 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2393 } 2394 2395 SDValue SITargetLowering::LowerCallResult( 2396 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2397 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2398 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2399 SDValue ThisVal) const { 2400 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2401 2402 // Assign locations to each value returned by this call. 2403 SmallVector<CCValAssign, 16> RVLocs; 2404 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2405 *DAG.getContext()); 2406 CCInfo.AnalyzeCallResult(Ins, RetCC); 2407 2408 // Copy all of the result registers out of their specified physreg. 2409 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2410 CCValAssign VA = RVLocs[i]; 2411 SDValue Val; 2412 2413 if (VA.isRegLoc()) { 2414 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2415 Chain = Val.getValue(1); 2416 InFlag = Val.getValue(2); 2417 } else if (VA.isMemLoc()) { 2418 report_fatal_error("TODO: return values in memory"); 2419 } else 2420 llvm_unreachable("unknown argument location type"); 2421 2422 switch (VA.getLocInfo()) { 2423 case CCValAssign::Full: 2424 break; 2425 case CCValAssign::BCvt: 2426 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2427 break; 2428 case CCValAssign::ZExt: 2429 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2430 DAG.getValueType(VA.getValVT())); 2431 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2432 break; 2433 case CCValAssign::SExt: 2434 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2435 DAG.getValueType(VA.getValVT())); 2436 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2437 break; 2438 case CCValAssign::AExt: 2439 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2440 break; 2441 default: 2442 llvm_unreachable("Unknown loc info!"); 2443 } 2444 2445 InVals.push_back(Val); 2446 } 2447 2448 return Chain; 2449 } 2450 2451 // Add code to pass special inputs required depending on used features separate 2452 // from the explicit user arguments present in the IR. 2453 void SITargetLowering::passSpecialInputs( 2454 CallLoweringInfo &CLI, 2455 CCState &CCInfo, 2456 const SIMachineFunctionInfo &Info, 2457 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2458 SmallVectorImpl<SDValue> &MemOpChains, 2459 SDValue Chain) const { 2460 // If we don't have a call site, this was a call inserted by 2461 // legalization. These can never use special inputs. 2462 if (!CLI.CS) 2463 return; 2464 2465 SelectionDAG &DAG = CLI.DAG; 2466 const SDLoc &DL = CLI.DL; 2467 2468 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2469 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2470 2471 const AMDGPUFunctionArgInfo *CalleeArgInfo 2472 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2473 if (const Function *CalleeFunc = CLI.CS.getCalledFunction()) { 2474 auto &ArgUsageInfo = 2475 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2476 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2477 } 2478 2479 // TODO: Unify with private memory register handling. This is complicated by 2480 // the fact that at least in kernels, the input argument is not necessarily 2481 // in the same location as the input. 2482 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2483 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2484 AMDGPUFunctionArgInfo::QUEUE_PTR, 2485 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2486 AMDGPUFunctionArgInfo::DISPATCH_ID, 2487 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2488 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2489 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2490 }; 2491 2492 for (auto InputID : InputRegs) { 2493 const ArgDescriptor *OutgoingArg; 2494 const TargetRegisterClass *ArgRC; 2495 2496 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2497 if (!OutgoingArg) 2498 continue; 2499 2500 const ArgDescriptor *IncomingArg; 2501 const TargetRegisterClass *IncomingArgRC; 2502 std::tie(IncomingArg, IncomingArgRC) 2503 = CallerArgInfo.getPreloadedValue(InputID); 2504 assert(IncomingArgRC == ArgRC); 2505 2506 // All special arguments are ints for now. 2507 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2508 SDValue InputReg; 2509 2510 if (IncomingArg) { 2511 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2512 } else { 2513 // The implicit arg ptr is special because it doesn't have a corresponding 2514 // input for kernels, and is computed from the kernarg segment pointer. 2515 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2516 InputReg = getImplicitArgPtr(DAG, DL); 2517 } 2518 2519 if (OutgoingArg->isRegister()) { 2520 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2521 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2522 report_fatal_error("failed to allocate implicit input argument"); 2523 } else { 2524 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2525 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2526 SpecialArgOffset); 2527 MemOpChains.push_back(ArgStore); 2528 } 2529 } 2530 2531 // Pack workitem IDs into a single register or pass it as is if already 2532 // packed. 2533 const ArgDescriptor *OutgoingArg; 2534 const TargetRegisterClass *ArgRC; 2535 2536 std::tie(OutgoingArg, ArgRC) = 2537 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2538 if (!OutgoingArg) 2539 std::tie(OutgoingArg, ArgRC) = 2540 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2541 if (!OutgoingArg) 2542 std::tie(OutgoingArg, ArgRC) = 2543 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2544 if (!OutgoingArg) 2545 return; 2546 2547 const ArgDescriptor *IncomingArgX 2548 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2549 const ArgDescriptor *IncomingArgY 2550 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2551 const ArgDescriptor *IncomingArgZ 2552 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2553 2554 SDValue InputReg; 2555 SDLoc SL; 2556 2557 // If incoming ids are not packed we need to pack them. 2558 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2559 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2560 2561 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2562 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2563 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2564 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2565 InputReg = InputReg.getNode() ? 2566 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2567 } 2568 2569 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2570 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2571 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2572 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2573 InputReg = InputReg.getNode() ? 2574 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2575 } 2576 2577 if (!InputReg.getNode()) { 2578 // Workitem ids are already packed, any of present incoming arguments 2579 // will carry all required fields. 2580 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2581 IncomingArgX ? *IncomingArgX : 2582 IncomingArgY ? *IncomingArgY : 2583 *IncomingArgZ, ~0u); 2584 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2585 } 2586 2587 if (OutgoingArg->isRegister()) { 2588 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2589 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2590 } else { 2591 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2592 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2593 SpecialArgOffset); 2594 MemOpChains.push_back(ArgStore); 2595 } 2596 } 2597 2598 static bool canGuaranteeTCO(CallingConv::ID CC) { 2599 return CC == CallingConv::Fast; 2600 } 2601 2602 /// Return true if we might ever do TCO for calls with this calling convention. 2603 static bool mayTailCallThisCC(CallingConv::ID CC) { 2604 switch (CC) { 2605 case CallingConv::C: 2606 return true; 2607 default: 2608 return canGuaranteeTCO(CC); 2609 } 2610 } 2611 2612 bool SITargetLowering::isEligibleForTailCallOptimization( 2613 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2614 const SmallVectorImpl<ISD::OutputArg> &Outs, 2615 const SmallVectorImpl<SDValue> &OutVals, 2616 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2617 if (!mayTailCallThisCC(CalleeCC)) 2618 return false; 2619 2620 MachineFunction &MF = DAG.getMachineFunction(); 2621 const Function &CallerF = MF.getFunction(); 2622 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2623 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2624 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2625 2626 // Kernels aren't callable, and don't have a live in return address so it 2627 // doesn't make sense to do a tail call with entry functions. 2628 if (!CallerPreserved) 2629 return false; 2630 2631 bool CCMatch = CallerCC == CalleeCC; 2632 2633 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2634 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2635 return true; 2636 return false; 2637 } 2638 2639 // TODO: Can we handle var args? 2640 if (IsVarArg) 2641 return false; 2642 2643 for (const Argument &Arg : CallerF.args()) { 2644 if (Arg.hasByValAttr()) 2645 return false; 2646 } 2647 2648 LLVMContext &Ctx = *DAG.getContext(); 2649 2650 // Check that the call results are passed in the same way. 2651 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2652 CCAssignFnForCall(CalleeCC, IsVarArg), 2653 CCAssignFnForCall(CallerCC, IsVarArg))) 2654 return false; 2655 2656 // The callee has to preserve all registers the caller needs to preserve. 2657 if (!CCMatch) { 2658 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2659 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2660 return false; 2661 } 2662 2663 // Nothing more to check if the callee is taking no arguments. 2664 if (Outs.empty()) 2665 return true; 2666 2667 SmallVector<CCValAssign, 16> ArgLocs; 2668 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2669 2670 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2671 2672 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2673 // If the stack arguments for this call do not fit into our own save area then 2674 // the call cannot be made tail. 2675 // TODO: Is this really necessary? 2676 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2677 return false; 2678 2679 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2680 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2681 } 2682 2683 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2684 if (!CI->isTailCall()) 2685 return false; 2686 2687 const Function *ParentFn = CI->getParent()->getParent(); 2688 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2689 return false; 2690 return true; 2691 } 2692 2693 // The wave scratch offset register is used as the global base pointer. 2694 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2695 SmallVectorImpl<SDValue> &InVals) const { 2696 SelectionDAG &DAG = CLI.DAG; 2697 const SDLoc &DL = CLI.DL; 2698 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2699 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2700 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2701 SDValue Chain = CLI.Chain; 2702 SDValue Callee = CLI.Callee; 2703 bool &IsTailCall = CLI.IsTailCall; 2704 CallingConv::ID CallConv = CLI.CallConv; 2705 bool IsVarArg = CLI.IsVarArg; 2706 bool IsSibCall = false; 2707 bool IsThisReturn = false; 2708 MachineFunction &MF = DAG.getMachineFunction(); 2709 2710 if (Callee.isUndef() || isNullConstant(Callee)) { 2711 if (!CLI.IsTailCall) { 2712 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2713 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2714 } 2715 2716 return Chain; 2717 } 2718 2719 if (IsVarArg) { 2720 return lowerUnhandledCall(CLI, InVals, 2721 "unsupported call to variadic function "); 2722 } 2723 2724 if (!CLI.CS.getInstruction()) 2725 report_fatal_error("unsupported libcall legalization"); 2726 2727 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && !CLI.CS.getCalledFunction()) { 2728 return lowerUnhandledCall(CLI, InVals, 2729 "unsupported indirect call to function "); 2730 } 2731 2732 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2733 return lowerUnhandledCall(CLI, InVals, 2734 "unsupported required tail call to function "); 2735 } 2736 2737 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2738 // Note the issue is with the CC of the calling function, not of the call 2739 // itself. 2740 return lowerUnhandledCall(CLI, InVals, 2741 "unsupported call from graphics shader of function "); 2742 } 2743 2744 if (IsTailCall) { 2745 IsTailCall = isEligibleForTailCallOptimization( 2746 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2747 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2748 report_fatal_error("failed to perform tail call elimination on a call " 2749 "site marked musttail"); 2750 } 2751 2752 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2753 2754 // A sibling call is one where we're under the usual C ABI and not planning 2755 // to change that but can still do a tail call: 2756 if (!TailCallOpt && IsTailCall) 2757 IsSibCall = true; 2758 2759 if (IsTailCall) 2760 ++NumTailCalls; 2761 } 2762 2763 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2764 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2765 SmallVector<SDValue, 8> MemOpChains; 2766 2767 // Analyze operands of the call, assigning locations to each operand. 2768 SmallVector<CCValAssign, 16> ArgLocs; 2769 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2770 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2771 2772 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2773 // With a fixed ABI, allocate fixed registers before user arguments. 2774 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2775 } 2776 2777 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2778 2779 // Get a count of how many bytes are to be pushed on the stack. 2780 unsigned NumBytes = CCInfo.getNextStackOffset(); 2781 2782 if (IsSibCall) { 2783 // Since we're not changing the ABI to make this a tail call, the memory 2784 // operands are already available in the caller's incoming argument space. 2785 NumBytes = 0; 2786 } 2787 2788 // FPDiff is the byte offset of the call's argument area from the callee's. 2789 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2790 // by this amount for a tail call. In a sibling call it must be 0 because the 2791 // caller will deallocate the entire stack and the callee still expects its 2792 // arguments to begin at SP+0. Completely unused for non-tail calls. 2793 int32_t FPDiff = 0; 2794 MachineFrameInfo &MFI = MF.getFrameInfo(); 2795 2796 // Adjust the stack pointer for the new arguments... 2797 // These operations are automatically eliminated by the prolog/epilog pass 2798 if (!IsSibCall) { 2799 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2800 2801 SmallVector<SDValue, 4> CopyFromChains; 2802 2803 // In the HSA case, this should be an identity copy. 2804 SDValue ScratchRSrcReg 2805 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2806 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2807 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2808 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2809 } 2810 2811 MVT PtrVT = MVT::i32; 2812 2813 // Walk the register/memloc assignments, inserting copies/loads. 2814 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2815 CCValAssign &VA = ArgLocs[i]; 2816 SDValue Arg = OutVals[i]; 2817 2818 // Promote the value if needed. 2819 switch (VA.getLocInfo()) { 2820 case CCValAssign::Full: 2821 break; 2822 case CCValAssign::BCvt: 2823 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2824 break; 2825 case CCValAssign::ZExt: 2826 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2827 break; 2828 case CCValAssign::SExt: 2829 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2830 break; 2831 case CCValAssign::AExt: 2832 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2833 break; 2834 case CCValAssign::FPExt: 2835 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2836 break; 2837 default: 2838 llvm_unreachable("Unknown loc info!"); 2839 } 2840 2841 if (VA.isRegLoc()) { 2842 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2843 } else { 2844 assert(VA.isMemLoc()); 2845 2846 SDValue DstAddr; 2847 MachinePointerInfo DstInfo; 2848 2849 unsigned LocMemOffset = VA.getLocMemOffset(); 2850 int32_t Offset = LocMemOffset; 2851 2852 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2853 MaybeAlign Alignment; 2854 2855 if (IsTailCall) { 2856 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2857 unsigned OpSize = Flags.isByVal() ? 2858 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2859 2860 // FIXME: We can have better than the minimum byval required alignment. 2861 Alignment = 2862 Flags.isByVal() 2863 ? Flags.getNonZeroByValAlign() 2864 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2865 2866 Offset = Offset + FPDiff; 2867 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2868 2869 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2870 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2871 2872 // Make sure any stack arguments overlapping with where we're storing 2873 // are loaded before this eventual operation. Otherwise they'll be 2874 // clobbered. 2875 2876 // FIXME: Why is this really necessary? This seems to just result in a 2877 // lot of code to copy the stack and write them back to the same 2878 // locations, which are supposed to be immutable? 2879 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2880 } else { 2881 DstAddr = PtrOff; 2882 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2883 Alignment = 2884 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2885 } 2886 2887 if (Outs[i].Flags.isByVal()) { 2888 SDValue SizeNode = 2889 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2890 SDValue Cpy = 2891 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2892 Outs[i].Flags.getNonZeroByValAlign(), 2893 /*isVol = */ false, /*AlwaysInline = */ true, 2894 /*isTailCall = */ false, DstInfo, 2895 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2896 2897 MemOpChains.push_back(Cpy); 2898 } else { 2899 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2900 Alignment ? Alignment->value() : 0); 2901 MemOpChains.push_back(Store); 2902 } 2903 } 2904 } 2905 2906 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2907 // Copy special input registers after user input arguments. 2908 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2909 } 2910 2911 if (!MemOpChains.empty()) 2912 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2913 2914 // Build a sequence of copy-to-reg nodes chained together with token chain 2915 // and flag operands which copy the outgoing args into the appropriate regs. 2916 SDValue InFlag; 2917 for (auto &RegToPass : RegsToPass) { 2918 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2919 RegToPass.second, InFlag); 2920 InFlag = Chain.getValue(1); 2921 } 2922 2923 2924 SDValue PhysReturnAddrReg; 2925 if (IsTailCall) { 2926 // Since the return is being combined with the call, we need to pass on the 2927 // return address. 2928 2929 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2930 SDValue ReturnAddrReg = CreateLiveInRegister( 2931 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2932 2933 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2934 MVT::i64); 2935 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2936 InFlag = Chain.getValue(1); 2937 } 2938 2939 // We don't usually want to end the call-sequence here because we would tidy 2940 // the frame up *after* the call, however in the ABI-changing tail-call case 2941 // we've carefully laid out the parameters so that when sp is reset they'll be 2942 // in the correct location. 2943 if (IsTailCall && !IsSibCall) { 2944 Chain = DAG.getCALLSEQ_END(Chain, 2945 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2946 DAG.getTargetConstant(0, DL, MVT::i32), 2947 InFlag, DL); 2948 InFlag = Chain.getValue(1); 2949 } 2950 2951 std::vector<SDValue> Ops; 2952 Ops.push_back(Chain); 2953 Ops.push_back(Callee); 2954 // Add a redundant copy of the callee global which will not be legalized, as 2955 // we need direct access to the callee later. 2956 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 2957 const GlobalValue *GV = GSD->getGlobal(); 2958 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2959 } else { 2960 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 2961 } 2962 2963 if (IsTailCall) { 2964 // Each tail call may have to adjust the stack by a different amount, so 2965 // this information must travel along with the operation for eventual 2966 // consumption by emitEpilogue. 2967 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2968 2969 Ops.push_back(PhysReturnAddrReg); 2970 } 2971 2972 // Add argument registers to the end of the list so that they are known live 2973 // into the call. 2974 for (auto &RegToPass : RegsToPass) { 2975 Ops.push_back(DAG.getRegister(RegToPass.first, 2976 RegToPass.second.getValueType())); 2977 } 2978 2979 // Add a register mask operand representing the call-preserved registers. 2980 2981 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2982 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2983 assert(Mask && "Missing call preserved mask for calling convention"); 2984 Ops.push_back(DAG.getRegisterMask(Mask)); 2985 2986 if (InFlag.getNode()) 2987 Ops.push_back(InFlag); 2988 2989 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2990 2991 // If we're doing a tall call, use a TC_RETURN here rather than an 2992 // actual call instruction. 2993 if (IsTailCall) { 2994 MFI.setHasTailCall(); 2995 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2996 } 2997 2998 // Returns a chain and a flag for retval copy to use. 2999 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3000 Chain = Call.getValue(0); 3001 InFlag = Call.getValue(1); 3002 3003 uint64_t CalleePopBytes = NumBytes; 3004 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3005 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3006 InFlag, DL); 3007 if (!Ins.empty()) 3008 InFlag = Chain.getValue(1); 3009 3010 // Handle result values, copying them out of physregs into vregs that we 3011 // return. 3012 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3013 InVals, IsThisReturn, 3014 IsThisReturn ? OutVals[0] : SDValue()); 3015 } 3016 3017 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3018 const MachineFunction &MF) const { 3019 Register Reg = StringSwitch<Register>(RegName) 3020 .Case("m0", AMDGPU::M0) 3021 .Case("exec", AMDGPU::EXEC) 3022 .Case("exec_lo", AMDGPU::EXEC_LO) 3023 .Case("exec_hi", AMDGPU::EXEC_HI) 3024 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3025 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3026 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3027 .Default(Register()); 3028 3029 if (Reg == AMDGPU::NoRegister) { 3030 report_fatal_error(Twine("invalid register name \"" 3031 + StringRef(RegName) + "\".")); 3032 3033 } 3034 3035 if (!Subtarget->hasFlatScrRegister() && 3036 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3037 report_fatal_error(Twine("invalid register \"" 3038 + StringRef(RegName) + "\" for subtarget.")); 3039 } 3040 3041 switch (Reg) { 3042 case AMDGPU::M0: 3043 case AMDGPU::EXEC_LO: 3044 case AMDGPU::EXEC_HI: 3045 case AMDGPU::FLAT_SCR_LO: 3046 case AMDGPU::FLAT_SCR_HI: 3047 if (VT.getSizeInBits() == 32) 3048 return Reg; 3049 break; 3050 case AMDGPU::EXEC: 3051 case AMDGPU::FLAT_SCR: 3052 if (VT.getSizeInBits() == 64) 3053 return Reg; 3054 break; 3055 default: 3056 llvm_unreachable("missing register type checking"); 3057 } 3058 3059 report_fatal_error(Twine("invalid type for register \"" 3060 + StringRef(RegName) + "\".")); 3061 } 3062 3063 // If kill is not the last instruction, split the block so kill is always a 3064 // proper terminator. 3065 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3066 MachineBasicBlock *BB) const { 3067 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3068 3069 MachineBasicBlock::iterator SplitPoint(&MI); 3070 ++SplitPoint; 3071 3072 if (SplitPoint == BB->end()) { 3073 // Don't bother with a new block. 3074 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3075 return BB; 3076 } 3077 3078 MachineFunction *MF = BB->getParent(); 3079 MachineBasicBlock *SplitBB 3080 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3081 3082 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3083 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3084 3085 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3086 BB->addSuccessor(SplitBB); 3087 3088 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3089 return SplitBB; 3090 } 3091 3092 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3093 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3094 // be the first instruction in the remainder block. 3095 // 3096 /// \returns { LoopBody, Remainder } 3097 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3098 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3099 MachineFunction *MF = MBB.getParent(); 3100 MachineBasicBlock::iterator I(&MI); 3101 3102 // To insert the loop we need to split the block. Move everything after this 3103 // point to a new block, and insert a new empty block between the two. 3104 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3105 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3106 MachineFunction::iterator MBBI(MBB); 3107 ++MBBI; 3108 3109 MF->insert(MBBI, LoopBB); 3110 MF->insert(MBBI, RemainderBB); 3111 3112 LoopBB->addSuccessor(LoopBB); 3113 LoopBB->addSuccessor(RemainderBB); 3114 3115 // Move the rest of the block into a new block. 3116 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3117 3118 if (InstInLoop) { 3119 auto Next = std::next(I); 3120 3121 // Move instruction to loop body. 3122 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3123 3124 // Move the rest of the block. 3125 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3126 } else { 3127 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3128 } 3129 3130 MBB.addSuccessor(LoopBB); 3131 3132 return std::make_pair(LoopBB, RemainderBB); 3133 } 3134 3135 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3136 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3137 MachineBasicBlock *MBB = MI.getParent(); 3138 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3139 auto I = MI.getIterator(); 3140 auto E = std::next(I); 3141 3142 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3143 .addImm(0); 3144 3145 MIBundleBuilder Bundler(*MBB, I, E); 3146 finalizeBundle(*MBB, Bundler.begin()); 3147 } 3148 3149 MachineBasicBlock * 3150 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3151 MachineBasicBlock *BB) const { 3152 const DebugLoc &DL = MI.getDebugLoc(); 3153 3154 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3155 3156 MachineBasicBlock *LoopBB; 3157 MachineBasicBlock *RemainderBB; 3158 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3159 3160 // Apparently kill flags are only valid if the def is in the same block? 3161 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3162 Src->setIsKill(false); 3163 3164 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3165 3166 MachineBasicBlock::iterator I = LoopBB->end(); 3167 3168 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3169 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3170 3171 // Clear TRAP_STS.MEM_VIOL 3172 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3173 .addImm(0) 3174 .addImm(EncodedReg); 3175 3176 bundleInstWithWaitcnt(MI); 3177 3178 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3179 3180 // Load and check TRAP_STS.MEM_VIOL 3181 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3182 .addImm(EncodedReg); 3183 3184 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3185 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3186 .addReg(Reg, RegState::Kill) 3187 .addImm(0); 3188 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3189 .addMBB(LoopBB); 3190 3191 return RemainderBB; 3192 } 3193 3194 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3195 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3196 // will only do one iteration. In the worst case, this will loop 64 times. 3197 // 3198 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3199 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3200 const SIInstrInfo *TII, 3201 MachineRegisterInfo &MRI, 3202 MachineBasicBlock &OrigBB, 3203 MachineBasicBlock &LoopBB, 3204 const DebugLoc &DL, 3205 const MachineOperand &IdxReg, 3206 unsigned InitReg, 3207 unsigned ResultReg, 3208 unsigned PhiReg, 3209 unsigned InitSaveExecReg, 3210 int Offset, 3211 bool UseGPRIdxMode, 3212 bool IsIndirectSrc) { 3213 MachineFunction *MF = OrigBB.getParent(); 3214 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3215 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3216 MachineBasicBlock::iterator I = LoopBB.begin(); 3217 3218 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3219 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3220 Register NewExec = MRI.createVirtualRegister(BoolRC); 3221 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3222 Register CondReg = MRI.createVirtualRegister(BoolRC); 3223 3224 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3225 .addReg(InitReg) 3226 .addMBB(&OrigBB) 3227 .addReg(ResultReg) 3228 .addMBB(&LoopBB); 3229 3230 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3231 .addReg(InitSaveExecReg) 3232 .addMBB(&OrigBB) 3233 .addReg(NewExec) 3234 .addMBB(&LoopBB); 3235 3236 // Read the next variant <- also loop target. 3237 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3238 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3239 3240 // Compare the just read M0 value to all possible Idx values. 3241 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3242 .addReg(CurrentIdxReg) 3243 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3244 3245 // Update EXEC, save the original EXEC value to VCC. 3246 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3247 : AMDGPU::S_AND_SAVEEXEC_B64), 3248 NewExec) 3249 .addReg(CondReg, RegState::Kill); 3250 3251 MRI.setSimpleHint(NewExec, CondReg); 3252 3253 if (UseGPRIdxMode) { 3254 unsigned IdxReg; 3255 if (Offset == 0) { 3256 IdxReg = CurrentIdxReg; 3257 } else { 3258 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3259 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3260 .addReg(CurrentIdxReg, RegState::Kill) 3261 .addImm(Offset); 3262 } 3263 unsigned IdxMode = IsIndirectSrc ? 3264 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3265 MachineInstr *SetOn = 3266 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3267 .addReg(IdxReg, RegState::Kill) 3268 .addImm(IdxMode); 3269 SetOn->getOperand(3).setIsUndef(); 3270 } else { 3271 // Move index from VCC into M0 3272 if (Offset == 0) { 3273 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3274 .addReg(CurrentIdxReg, RegState::Kill); 3275 } else { 3276 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3277 .addReg(CurrentIdxReg, RegState::Kill) 3278 .addImm(Offset); 3279 } 3280 } 3281 3282 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3283 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3284 MachineInstr *InsertPt = 3285 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3286 : AMDGPU::S_XOR_B64_term), Exec) 3287 .addReg(Exec) 3288 .addReg(NewExec); 3289 3290 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3291 // s_cbranch_scc0? 3292 3293 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3294 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3295 .addMBB(&LoopBB); 3296 3297 return InsertPt->getIterator(); 3298 } 3299 3300 // This has slightly sub-optimal regalloc when the source vector is killed by 3301 // the read. The register allocator does not understand that the kill is 3302 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3303 // subregister from it, using 1 more VGPR than necessary. This was saved when 3304 // this was expanded after register allocation. 3305 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3306 MachineBasicBlock &MBB, 3307 MachineInstr &MI, 3308 unsigned InitResultReg, 3309 unsigned PhiReg, 3310 int Offset, 3311 bool UseGPRIdxMode, 3312 bool IsIndirectSrc) { 3313 MachineFunction *MF = MBB.getParent(); 3314 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3315 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3316 MachineRegisterInfo &MRI = MF->getRegInfo(); 3317 const DebugLoc &DL = MI.getDebugLoc(); 3318 MachineBasicBlock::iterator I(&MI); 3319 3320 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3321 Register DstReg = MI.getOperand(0).getReg(); 3322 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3323 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3324 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3325 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3326 3327 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3328 3329 // Save the EXEC mask 3330 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3331 .addReg(Exec); 3332 3333 MachineBasicBlock *LoopBB; 3334 MachineBasicBlock *RemainderBB; 3335 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3336 3337 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3338 3339 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3340 InitResultReg, DstReg, PhiReg, TmpExec, 3341 Offset, UseGPRIdxMode, IsIndirectSrc); 3342 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3343 MachineFunction::iterator MBBI(LoopBB); 3344 ++MBBI; 3345 MF->insert(MBBI, LandingPad); 3346 LoopBB->removeSuccessor(RemainderBB); 3347 LandingPad->addSuccessor(RemainderBB); 3348 LoopBB->addSuccessor(LandingPad); 3349 MachineBasicBlock::iterator First = LandingPad->begin(); 3350 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3351 .addReg(SaveExec); 3352 3353 return InsPt; 3354 } 3355 3356 // Returns subreg index, offset 3357 static std::pair<unsigned, int> 3358 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3359 const TargetRegisterClass *SuperRC, 3360 unsigned VecReg, 3361 int Offset) { 3362 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3363 3364 // Skip out of bounds offsets, or else we would end up using an undefined 3365 // register. 3366 if (Offset >= NumElts || Offset < 0) 3367 return std::make_pair(AMDGPU::sub0, Offset); 3368 3369 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3370 } 3371 3372 // Return true if the index is an SGPR and was set. 3373 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3374 MachineRegisterInfo &MRI, 3375 MachineInstr &MI, 3376 int Offset, 3377 bool UseGPRIdxMode, 3378 bool IsIndirectSrc) { 3379 MachineBasicBlock *MBB = MI.getParent(); 3380 const DebugLoc &DL = MI.getDebugLoc(); 3381 MachineBasicBlock::iterator I(&MI); 3382 3383 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3384 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3385 3386 assert(Idx->getReg() != AMDGPU::NoRegister); 3387 3388 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3389 return false; 3390 3391 if (UseGPRIdxMode) { 3392 unsigned IdxMode = IsIndirectSrc ? 3393 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3394 if (Offset == 0) { 3395 MachineInstr *SetOn = 3396 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3397 .add(*Idx) 3398 .addImm(IdxMode); 3399 3400 SetOn->getOperand(3).setIsUndef(); 3401 } else { 3402 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3403 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3404 .add(*Idx) 3405 .addImm(Offset); 3406 MachineInstr *SetOn = 3407 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3408 .addReg(Tmp, RegState::Kill) 3409 .addImm(IdxMode); 3410 3411 SetOn->getOperand(3).setIsUndef(); 3412 } 3413 3414 return true; 3415 } 3416 3417 if (Offset == 0) { 3418 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3419 .add(*Idx); 3420 } else { 3421 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3422 .add(*Idx) 3423 .addImm(Offset); 3424 } 3425 3426 return true; 3427 } 3428 3429 // Control flow needs to be inserted if indexing with a VGPR. 3430 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3431 MachineBasicBlock &MBB, 3432 const GCNSubtarget &ST) { 3433 const SIInstrInfo *TII = ST.getInstrInfo(); 3434 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3435 MachineFunction *MF = MBB.getParent(); 3436 MachineRegisterInfo &MRI = MF->getRegInfo(); 3437 3438 Register Dst = MI.getOperand(0).getReg(); 3439 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3440 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3441 3442 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3443 3444 unsigned SubReg; 3445 std::tie(SubReg, Offset) 3446 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3447 3448 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3449 3450 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3451 MachineBasicBlock::iterator I(&MI); 3452 const DebugLoc &DL = MI.getDebugLoc(); 3453 3454 if (UseGPRIdxMode) { 3455 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3456 // to avoid interfering with other uses, so probably requires a new 3457 // optimization pass. 3458 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3459 .addReg(SrcReg, RegState::Undef, SubReg) 3460 .addReg(SrcReg, RegState::Implicit) 3461 .addReg(AMDGPU::M0, RegState::Implicit); 3462 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3463 } else { 3464 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3465 .addReg(SrcReg, RegState::Undef, SubReg) 3466 .addReg(SrcReg, RegState::Implicit); 3467 } 3468 3469 MI.eraseFromParent(); 3470 3471 return &MBB; 3472 } 3473 3474 const DebugLoc &DL = MI.getDebugLoc(); 3475 MachineBasicBlock::iterator I(&MI); 3476 3477 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3478 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3479 3480 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3481 3482 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3483 Offset, UseGPRIdxMode, true); 3484 MachineBasicBlock *LoopBB = InsPt->getParent(); 3485 3486 if (UseGPRIdxMode) { 3487 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3488 .addReg(SrcReg, RegState::Undef, SubReg) 3489 .addReg(SrcReg, RegState::Implicit) 3490 .addReg(AMDGPU::M0, RegState::Implicit); 3491 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3492 } else { 3493 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3494 .addReg(SrcReg, RegState::Undef, SubReg) 3495 .addReg(SrcReg, RegState::Implicit); 3496 } 3497 3498 MI.eraseFromParent(); 3499 3500 return LoopBB; 3501 } 3502 3503 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3504 MachineBasicBlock &MBB, 3505 const GCNSubtarget &ST) { 3506 const SIInstrInfo *TII = ST.getInstrInfo(); 3507 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3508 MachineFunction *MF = MBB.getParent(); 3509 MachineRegisterInfo &MRI = MF->getRegInfo(); 3510 3511 Register Dst = MI.getOperand(0).getReg(); 3512 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3513 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3514 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3515 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3516 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3517 3518 // This can be an immediate, but will be folded later. 3519 assert(Val->getReg()); 3520 3521 unsigned SubReg; 3522 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3523 SrcVec->getReg(), 3524 Offset); 3525 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3526 3527 if (Idx->getReg() == AMDGPU::NoRegister) { 3528 MachineBasicBlock::iterator I(&MI); 3529 const DebugLoc &DL = MI.getDebugLoc(); 3530 3531 assert(Offset == 0); 3532 3533 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3534 .add(*SrcVec) 3535 .add(*Val) 3536 .addImm(SubReg); 3537 3538 MI.eraseFromParent(); 3539 return &MBB; 3540 } 3541 3542 const MCInstrDesc &MovRelDesc 3543 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3544 3545 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3546 MachineBasicBlock::iterator I(&MI); 3547 const DebugLoc &DL = MI.getDebugLoc(); 3548 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3549 .addReg(SrcVec->getReg()) 3550 .add(*Val) 3551 .addImm(SubReg); 3552 if (UseGPRIdxMode) 3553 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3554 3555 MI.eraseFromParent(); 3556 return &MBB; 3557 } 3558 3559 if (Val->isReg()) 3560 MRI.clearKillFlags(Val->getReg()); 3561 3562 const DebugLoc &DL = MI.getDebugLoc(); 3563 3564 Register PhiReg = MRI.createVirtualRegister(VecRC); 3565 3566 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3567 Offset, UseGPRIdxMode, false); 3568 MachineBasicBlock *LoopBB = InsPt->getParent(); 3569 3570 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3571 .addReg(PhiReg) 3572 .add(*Val) 3573 .addImm(AMDGPU::sub0); 3574 if (UseGPRIdxMode) 3575 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3576 3577 MI.eraseFromParent(); 3578 return LoopBB; 3579 } 3580 3581 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3582 MachineInstr &MI, MachineBasicBlock *BB) const { 3583 3584 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3585 MachineFunction *MF = BB->getParent(); 3586 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3587 3588 if (TII->isMIMG(MI)) { 3589 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3590 report_fatal_error("missing mem operand from MIMG instruction"); 3591 } 3592 // Add a memoperand for mimg instructions so that they aren't assumed to 3593 // be ordered memory instuctions. 3594 3595 return BB; 3596 } 3597 3598 switch (MI.getOpcode()) { 3599 case AMDGPU::S_ADD_U64_PSEUDO: 3600 case AMDGPU::S_SUB_U64_PSEUDO: { 3601 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3602 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3603 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3604 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3605 const DebugLoc &DL = MI.getDebugLoc(); 3606 3607 MachineOperand &Dest = MI.getOperand(0); 3608 MachineOperand &Src0 = MI.getOperand(1); 3609 MachineOperand &Src1 = MI.getOperand(2); 3610 3611 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3612 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3613 3614 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3615 Src0, BoolRC, AMDGPU::sub0, 3616 &AMDGPU::SReg_32RegClass); 3617 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3618 Src0, BoolRC, AMDGPU::sub1, 3619 &AMDGPU::SReg_32RegClass); 3620 3621 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3622 Src1, BoolRC, AMDGPU::sub0, 3623 &AMDGPU::SReg_32RegClass); 3624 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3625 Src1, BoolRC, AMDGPU::sub1, 3626 &AMDGPU::SReg_32RegClass); 3627 3628 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3629 3630 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3631 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3632 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3633 .add(Src0Sub0) 3634 .add(Src1Sub0); 3635 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3636 .add(Src0Sub1) 3637 .add(Src1Sub1); 3638 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3639 .addReg(DestSub0) 3640 .addImm(AMDGPU::sub0) 3641 .addReg(DestSub1) 3642 .addImm(AMDGPU::sub1); 3643 MI.eraseFromParent(); 3644 return BB; 3645 } 3646 case AMDGPU::SI_INIT_M0: { 3647 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3648 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3649 .add(MI.getOperand(0)); 3650 MI.eraseFromParent(); 3651 return BB; 3652 } 3653 case AMDGPU::SI_INIT_EXEC: 3654 // This should be before all vector instructions. 3655 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3656 AMDGPU::EXEC) 3657 .addImm(MI.getOperand(0).getImm()); 3658 MI.eraseFromParent(); 3659 return BB; 3660 3661 case AMDGPU::SI_INIT_EXEC_LO: 3662 // This should be before all vector instructions. 3663 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3664 AMDGPU::EXEC_LO) 3665 .addImm(MI.getOperand(0).getImm()); 3666 MI.eraseFromParent(); 3667 return BB; 3668 3669 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3670 // Extract the thread count from an SGPR input and set EXEC accordingly. 3671 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3672 // 3673 // S_BFE_U32 count, input, {shift, 7} 3674 // S_BFM_B64 exec, count, 0 3675 // S_CMP_EQ_U32 count, 64 3676 // S_CMOV_B64 exec, -1 3677 MachineInstr *FirstMI = &*BB->begin(); 3678 MachineRegisterInfo &MRI = MF->getRegInfo(); 3679 Register InputReg = MI.getOperand(0).getReg(); 3680 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3681 bool Found = false; 3682 3683 // Move the COPY of the input reg to the beginning, so that we can use it. 3684 for (auto I = BB->begin(); I != &MI; I++) { 3685 if (I->getOpcode() != TargetOpcode::COPY || 3686 I->getOperand(0).getReg() != InputReg) 3687 continue; 3688 3689 if (I == FirstMI) { 3690 FirstMI = &*++BB->begin(); 3691 } else { 3692 I->removeFromParent(); 3693 BB->insert(FirstMI, &*I); 3694 } 3695 Found = true; 3696 break; 3697 } 3698 assert(Found); 3699 (void)Found; 3700 3701 // This should be before all vector instructions. 3702 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3703 bool isWave32 = getSubtarget()->isWave32(); 3704 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3705 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3706 .addReg(InputReg) 3707 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3708 BuildMI(*BB, FirstMI, DebugLoc(), 3709 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3710 Exec) 3711 .addReg(CountReg) 3712 .addImm(0); 3713 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3714 .addReg(CountReg, RegState::Kill) 3715 .addImm(getSubtarget()->getWavefrontSize()); 3716 BuildMI(*BB, FirstMI, DebugLoc(), 3717 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3718 Exec) 3719 .addImm(-1); 3720 MI.eraseFromParent(); 3721 return BB; 3722 } 3723 3724 case AMDGPU::GET_GROUPSTATICSIZE: { 3725 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3726 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3727 DebugLoc DL = MI.getDebugLoc(); 3728 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3729 .add(MI.getOperand(0)) 3730 .addImm(MFI->getLDSSize()); 3731 MI.eraseFromParent(); 3732 return BB; 3733 } 3734 case AMDGPU::SI_INDIRECT_SRC_V1: 3735 case AMDGPU::SI_INDIRECT_SRC_V2: 3736 case AMDGPU::SI_INDIRECT_SRC_V4: 3737 case AMDGPU::SI_INDIRECT_SRC_V8: 3738 case AMDGPU::SI_INDIRECT_SRC_V16: 3739 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3740 case AMDGPU::SI_INDIRECT_DST_V1: 3741 case AMDGPU::SI_INDIRECT_DST_V2: 3742 case AMDGPU::SI_INDIRECT_DST_V4: 3743 case AMDGPU::SI_INDIRECT_DST_V8: 3744 case AMDGPU::SI_INDIRECT_DST_V16: 3745 return emitIndirectDst(MI, *BB, *getSubtarget()); 3746 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3747 case AMDGPU::SI_KILL_I1_PSEUDO: 3748 return splitKillBlock(MI, BB); 3749 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3750 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3751 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3752 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3753 3754 Register Dst = MI.getOperand(0).getReg(); 3755 Register Src0 = MI.getOperand(1).getReg(); 3756 Register Src1 = MI.getOperand(2).getReg(); 3757 const DebugLoc &DL = MI.getDebugLoc(); 3758 Register SrcCond = MI.getOperand(3).getReg(); 3759 3760 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3761 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3762 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3763 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3764 3765 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3766 .addReg(SrcCond); 3767 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3768 .addImm(0) 3769 .addReg(Src0, 0, AMDGPU::sub0) 3770 .addImm(0) 3771 .addReg(Src1, 0, AMDGPU::sub0) 3772 .addReg(SrcCondCopy); 3773 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3774 .addImm(0) 3775 .addReg(Src0, 0, AMDGPU::sub1) 3776 .addImm(0) 3777 .addReg(Src1, 0, AMDGPU::sub1) 3778 .addReg(SrcCondCopy); 3779 3780 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3781 .addReg(DstLo) 3782 .addImm(AMDGPU::sub0) 3783 .addReg(DstHi) 3784 .addImm(AMDGPU::sub1); 3785 MI.eraseFromParent(); 3786 return BB; 3787 } 3788 case AMDGPU::SI_BR_UNDEF: { 3789 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3790 const DebugLoc &DL = MI.getDebugLoc(); 3791 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3792 .add(MI.getOperand(0)); 3793 Br->getOperand(1).setIsUndef(true); // read undef SCC 3794 MI.eraseFromParent(); 3795 return BB; 3796 } 3797 case AMDGPU::ADJCALLSTACKUP: 3798 case AMDGPU::ADJCALLSTACKDOWN: { 3799 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3800 MachineInstrBuilder MIB(*MF, &MI); 3801 3802 // Add an implicit use of the frame offset reg to prevent the restore copy 3803 // inserted after the call from being reorderd after stack operations in the 3804 // the caller's frame. 3805 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3806 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3807 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3808 return BB; 3809 } 3810 case AMDGPU::SI_CALL_ISEL: { 3811 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3812 const DebugLoc &DL = MI.getDebugLoc(); 3813 3814 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3815 3816 MachineInstrBuilder MIB; 3817 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3818 3819 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3820 MIB.add(MI.getOperand(I)); 3821 3822 MIB.cloneMemRefs(MI); 3823 MI.eraseFromParent(); 3824 return BB; 3825 } 3826 case AMDGPU::V_ADD_I32_e32: 3827 case AMDGPU::V_SUB_I32_e32: 3828 case AMDGPU::V_SUBREV_I32_e32: { 3829 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3830 const DebugLoc &DL = MI.getDebugLoc(); 3831 unsigned Opc = MI.getOpcode(); 3832 3833 bool NeedClampOperand = false; 3834 if (TII->pseudoToMCOpcode(Opc) == -1) { 3835 Opc = AMDGPU::getVOPe64(Opc); 3836 NeedClampOperand = true; 3837 } 3838 3839 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3840 if (TII->isVOP3(*I)) { 3841 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3842 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3843 I.addReg(TRI->getVCC(), RegState::Define); 3844 } 3845 I.add(MI.getOperand(1)) 3846 .add(MI.getOperand(2)); 3847 if (NeedClampOperand) 3848 I.addImm(0); // clamp bit for e64 encoding 3849 3850 TII->legalizeOperands(*I); 3851 3852 MI.eraseFromParent(); 3853 return BB; 3854 } 3855 case AMDGPU::DS_GWS_INIT: 3856 case AMDGPU::DS_GWS_SEMA_V: 3857 case AMDGPU::DS_GWS_SEMA_BR: 3858 case AMDGPU::DS_GWS_SEMA_P: 3859 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3860 case AMDGPU::DS_GWS_BARRIER: 3861 // A s_waitcnt 0 is required to be the instruction immediately following. 3862 if (getSubtarget()->hasGWSAutoReplay()) { 3863 bundleInstWithWaitcnt(MI); 3864 return BB; 3865 } 3866 3867 return emitGWSMemViolTestLoop(MI, BB); 3868 default: 3869 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3870 } 3871 } 3872 3873 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3874 return isTypeLegal(VT.getScalarType()); 3875 } 3876 3877 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3878 // This currently forces unfolding various combinations of fsub into fma with 3879 // free fneg'd operands. As long as we have fast FMA (controlled by 3880 // isFMAFasterThanFMulAndFAdd), we should perform these. 3881 3882 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3883 // most of these combines appear to be cycle neutral but save on instruction 3884 // count / code size. 3885 return true; 3886 } 3887 3888 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3889 EVT VT) const { 3890 if (!VT.isVector()) { 3891 return MVT::i1; 3892 } 3893 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3894 } 3895 3896 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3897 // TODO: Should i16 be used always if legal? For now it would force VALU 3898 // shifts. 3899 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3900 } 3901 3902 // Answering this is somewhat tricky and depends on the specific device which 3903 // have different rates for fma or all f64 operations. 3904 // 3905 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3906 // regardless of which device (although the number of cycles differs between 3907 // devices), so it is always profitable for f64. 3908 // 3909 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3910 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3911 // which we can always do even without fused FP ops since it returns the same 3912 // result as the separate operations and since it is always full 3913 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3914 // however does not support denormals, so we do report fma as faster if we have 3915 // a fast fma device and require denormals. 3916 // 3917 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3918 EVT VT) const { 3919 VT = VT.getScalarType(); 3920 3921 switch (VT.getSimpleVT().SimpleTy) { 3922 case MVT::f32: { 3923 // This is as fast on some subtargets. However, we always have full rate f32 3924 // mad available which returns the same result as the separate operations 3925 // which we should prefer over fma. We can't use this if we want to support 3926 // denormals, so only report this in these cases. 3927 if (hasFP32Denormals(MF)) 3928 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3929 3930 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3931 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3932 } 3933 case MVT::f64: 3934 return true; 3935 case MVT::f16: 3936 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3937 default: 3938 break; 3939 } 3940 3941 return false; 3942 } 3943 3944 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3945 const SDNode *N) const { 3946 // TODO: Check future ftz flag 3947 // v_mad_f32/v_mac_f32 do not support denormals. 3948 EVT VT = N->getValueType(0); 3949 if (VT == MVT::f32) 3950 return !hasFP32Denormals(DAG.getMachineFunction()); 3951 if (VT == MVT::f16) { 3952 return Subtarget->hasMadF16() && 3953 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3954 } 3955 3956 return false; 3957 } 3958 3959 //===----------------------------------------------------------------------===// 3960 // Custom DAG Lowering Operations 3961 //===----------------------------------------------------------------------===// 3962 3963 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3964 // wider vector type is legal. 3965 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3966 SelectionDAG &DAG) const { 3967 unsigned Opc = Op.getOpcode(); 3968 EVT VT = Op.getValueType(); 3969 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 3970 3971 SDValue Lo, Hi; 3972 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3973 3974 SDLoc SL(Op); 3975 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3976 Op->getFlags()); 3977 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3978 Op->getFlags()); 3979 3980 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3981 } 3982 3983 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3984 // wider vector type is legal. 3985 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3986 SelectionDAG &DAG) const { 3987 unsigned Opc = Op.getOpcode(); 3988 EVT VT = Op.getValueType(); 3989 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3990 3991 SDValue Lo0, Hi0; 3992 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3993 SDValue Lo1, Hi1; 3994 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3995 3996 SDLoc SL(Op); 3997 3998 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3999 Op->getFlags()); 4000 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4001 Op->getFlags()); 4002 4003 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4004 } 4005 4006 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4007 SelectionDAG &DAG) const { 4008 unsigned Opc = Op.getOpcode(); 4009 EVT VT = Op.getValueType(); 4010 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4011 4012 SDValue Lo0, Hi0; 4013 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4014 SDValue Lo1, Hi1; 4015 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4016 SDValue Lo2, Hi2; 4017 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4018 4019 SDLoc SL(Op); 4020 4021 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4022 Op->getFlags()); 4023 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4024 Op->getFlags()); 4025 4026 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4027 } 4028 4029 4030 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4031 switch (Op.getOpcode()) { 4032 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4033 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4034 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4035 case ISD::LOAD: { 4036 SDValue Result = LowerLOAD(Op, DAG); 4037 assert((!Result.getNode() || 4038 Result.getNode()->getNumValues() == 2) && 4039 "Load should return a value and a chain"); 4040 return Result; 4041 } 4042 4043 case ISD::FSIN: 4044 case ISD::FCOS: 4045 return LowerTrig(Op, DAG); 4046 case ISD::SELECT: return LowerSELECT(Op, DAG); 4047 case ISD::FDIV: return LowerFDIV(Op, DAG); 4048 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4049 case ISD::STORE: return LowerSTORE(Op, DAG); 4050 case ISD::GlobalAddress: { 4051 MachineFunction &MF = DAG.getMachineFunction(); 4052 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4053 return LowerGlobalAddress(MFI, Op, DAG); 4054 } 4055 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4056 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4057 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4058 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4059 case ISD::INSERT_SUBVECTOR: 4060 return lowerINSERT_SUBVECTOR(Op, DAG); 4061 case ISD::INSERT_VECTOR_ELT: 4062 return lowerINSERT_VECTOR_ELT(Op, DAG); 4063 case ISD::EXTRACT_VECTOR_ELT: 4064 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4065 case ISD::VECTOR_SHUFFLE: 4066 return lowerVECTOR_SHUFFLE(Op, DAG); 4067 case ISD::BUILD_VECTOR: 4068 return lowerBUILD_VECTOR(Op, DAG); 4069 case ISD::FP_ROUND: 4070 return lowerFP_ROUND(Op, DAG); 4071 case ISD::TRAP: 4072 return lowerTRAP(Op, DAG); 4073 case ISD::DEBUGTRAP: 4074 return lowerDEBUGTRAP(Op, DAG); 4075 case ISD::FABS: 4076 case ISD::FNEG: 4077 case ISD::FCANONICALIZE: 4078 case ISD::BSWAP: 4079 return splitUnaryVectorOp(Op, DAG); 4080 case ISD::FMINNUM: 4081 case ISD::FMAXNUM: 4082 return lowerFMINNUM_FMAXNUM(Op, DAG); 4083 case ISD::FMA: 4084 return splitTernaryVectorOp(Op, DAG); 4085 case ISD::SHL: 4086 case ISD::SRA: 4087 case ISD::SRL: 4088 case ISD::ADD: 4089 case ISD::SUB: 4090 case ISD::MUL: 4091 case ISD::SMIN: 4092 case ISD::SMAX: 4093 case ISD::UMIN: 4094 case ISD::UMAX: 4095 case ISD::FADD: 4096 case ISD::FMUL: 4097 case ISD::FMINNUM_IEEE: 4098 case ISD::FMAXNUM_IEEE: 4099 return splitBinaryVectorOp(Op, DAG); 4100 } 4101 return SDValue(); 4102 } 4103 4104 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4105 const SDLoc &DL, 4106 SelectionDAG &DAG, bool Unpacked) { 4107 if (!LoadVT.isVector()) 4108 return Result; 4109 4110 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4111 // Truncate to v2i16/v4i16. 4112 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4113 4114 // Workaround legalizer not scalarizing truncate after vector op 4115 // legalization byt not creating intermediate vector trunc. 4116 SmallVector<SDValue, 4> Elts; 4117 DAG.ExtractVectorElements(Result, Elts); 4118 for (SDValue &Elt : Elts) 4119 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4120 4121 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4122 4123 // Bitcast to original type (v2f16/v4f16). 4124 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4125 } 4126 4127 // Cast back to the original packed type. 4128 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4129 } 4130 4131 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4132 MemSDNode *M, 4133 SelectionDAG &DAG, 4134 ArrayRef<SDValue> Ops, 4135 bool IsIntrinsic) const { 4136 SDLoc DL(M); 4137 4138 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4139 EVT LoadVT = M->getValueType(0); 4140 4141 EVT EquivLoadVT = LoadVT; 4142 if (Unpacked && LoadVT.isVector()) { 4143 EquivLoadVT = LoadVT.isVector() ? 4144 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4145 LoadVT.getVectorNumElements()) : LoadVT; 4146 } 4147 4148 // Change from v4f16/v2f16 to EquivLoadVT. 4149 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4150 4151 SDValue Load 4152 = DAG.getMemIntrinsicNode( 4153 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4154 VTList, Ops, M->getMemoryVT(), 4155 M->getMemOperand()); 4156 if (!Unpacked) // Just adjusted the opcode. 4157 return Load; 4158 4159 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4160 4161 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4162 } 4163 4164 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4165 SelectionDAG &DAG, 4166 ArrayRef<SDValue> Ops) const { 4167 SDLoc DL(M); 4168 EVT LoadVT = M->getValueType(0); 4169 EVT EltType = LoadVT.getScalarType(); 4170 EVT IntVT = LoadVT.changeTypeToInteger(); 4171 4172 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4173 4174 unsigned Opc = 4175 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4176 4177 if (IsD16) { 4178 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4179 } 4180 4181 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4182 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4183 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4184 4185 if (isTypeLegal(LoadVT)) { 4186 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4187 M->getMemOperand(), DAG); 4188 } 4189 4190 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4191 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4192 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4193 M->getMemOperand(), DAG); 4194 return DAG.getMergeValues( 4195 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4196 DL); 4197 } 4198 4199 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4200 SDNode *N, SelectionDAG &DAG) { 4201 EVT VT = N->getValueType(0); 4202 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4203 int CondCode = CD->getSExtValue(); 4204 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4205 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4206 return DAG.getUNDEF(VT); 4207 4208 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4209 4210 SDValue LHS = N->getOperand(1); 4211 SDValue RHS = N->getOperand(2); 4212 4213 SDLoc DL(N); 4214 4215 EVT CmpVT = LHS.getValueType(); 4216 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4217 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4218 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4219 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4220 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4221 } 4222 4223 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4224 4225 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4226 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4227 4228 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4229 DAG.getCondCode(CCOpcode)); 4230 if (VT.bitsEq(CCVT)) 4231 return SetCC; 4232 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4233 } 4234 4235 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4236 SDNode *N, SelectionDAG &DAG) { 4237 EVT VT = N->getValueType(0); 4238 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4239 4240 int CondCode = CD->getSExtValue(); 4241 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4242 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4243 return DAG.getUNDEF(VT); 4244 } 4245 4246 SDValue Src0 = N->getOperand(1); 4247 SDValue Src1 = N->getOperand(2); 4248 EVT CmpVT = Src0.getValueType(); 4249 SDLoc SL(N); 4250 4251 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4252 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4253 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4254 } 4255 4256 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4257 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4258 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4259 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4260 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4261 Src1, DAG.getCondCode(CCOpcode)); 4262 if (VT.bitsEq(CCVT)) 4263 return SetCC; 4264 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4265 } 4266 4267 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4268 SelectionDAG &DAG) { 4269 EVT VT = N->getValueType(0); 4270 SDValue Src = N->getOperand(1); 4271 SDLoc SL(N); 4272 4273 if (Src.getOpcode() == ISD::SETCC) { 4274 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4275 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4276 Src.getOperand(1), Src.getOperand(2)); 4277 } 4278 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4279 // (ballot 0) -> 0 4280 if (Arg->isNullValue()) 4281 return DAG.getConstant(0, SL, VT); 4282 4283 // (ballot 1) -> EXEC/EXEC_LO 4284 if (Arg->isOne()) { 4285 Register Exec; 4286 if (VT.getScalarSizeInBits() == 32) 4287 Exec = AMDGPU::EXEC_LO; 4288 else if (VT.getScalarSizeInBits() == 64) 4289 Exec = AMDGPU::EXEC; 4290 else 4291 return SDValue(); 4292 4293 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4294 } 4295 } 4296 4297 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4298 // ISD::SETNE) 4299 return DAG.getNode( 4300 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4301 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4302 } 4303 4304 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4305 SmallVectorImpl<SDValue> &Results, 4306 SelectionDAG &DAG) const { 4307 switch (N->getOpcode()) { 4308 case ISD::INSERT_VECTOR_ELT: { 4309 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4310 Results.push_back(Res); 4311 return; 4312 } 4313 case ISD::EXTRACT_VECTOR_ELT: { 4314 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4315 Results.push_back(Res); 4316 return; 4317 } 4318 case ISD::INTRINSIC_WO_CHAIN: { 4319 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4320 switch (IID) { 4321 case Intrinsic::amdgcn_cvt_pkrtz: { 4322 SDValue Src0 = N->getOperand(1); 4323 SDValue Src1 = N->getOperand(2); 4324 SDLoc SL(N); 4325 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4326 Src0, Src1); 4327 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4328 return; 4329 } 4330 case Intrinsic::amdgcn_cvt_pknorm_i16: 4331 case Intrinsic::amdgcn_cvt_pknorm_u16: 4332 case Intrinsic::amdgcn_cvt_pk_i16: 4333 case Intrinsic::amdgcn_cvt_pk_u16: { 4334 SDValue Src0 = N->getOperand(1); 4335 SDValue Src1 = N->getOperand(2); 4336 SDLoc SL(N); 4337 unsigned Opcode; 4338 4339 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4340 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4341 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4342 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4343 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4344 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4345 else 4346 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4347 4348 EVT VT = N->getValueType(0); 4349 if (isTypeLegal(VT)) 4350 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4351 else { 4352 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4353 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4354 } 4355 return; 4356 } 4357 } 4358 break; 4359 } 4360 case ISD::INTRINSIC_W_CHAIN: { 4361 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4362 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4363 // FIXME: Hacky 4364 Results.push_back(Res.getOperand(0)); 4365 Results.push_back(Res.getOperand(1)); 4366 } else { 4367 Results.push_back(Res); 4368 Results.push_back(Res.getValue(1)); 4369 } 4370 return; 4371 } 4372 4373 break; 4374 } 4375 case ISD::SELECT: { 4376 SDLoc SL(N); 4377 EVT VT = N->getValueType(0); 4378 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4379 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4380 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4381 4382 EVT SelectVT = NewVT; 4383 if (NewVT.bitsLT(MVT::i32)) { 4384 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4385 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4386 SelectVT = MVT::i32; 4387 } 4388 4389 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4390 N->getOperand(0), LHS, RHS); 4391 4392 if (NewVT != SelectVT) 4393 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4394 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4395 return; 4396 } 4397 case ISD::FNEG: { 4398 if (N->getValueType(0) != MVT::v2f16) 4399 break; 4400 4401 SDLoc SL(N); 4402 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4403 4404 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4405 BC, 4406 DAG.getConstant(0x80008000, SL, MVT::i32)); 4407 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4408 return; 4409 } 4410 case ISD::FABS: { 4411 if (N->getValueType(0) != MVT::v2f16) 4412 break; 4413 4414 SDLoc SL(N); 4415 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4416 4417 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4418 BC, 4419 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4420 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4421 return; 4422 } 4423 default: 4424 break; 4425 } 4426 } 4427 4428 /// Helper function for LowerBRCOND 4429 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4430 4431 SDNode *Parent = Value.getNode(); 4432 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4433 I != E; ++I) { 4434 4435 if (I.getUse().get() != Value) 4436 continue; 4437 4438 if (I->getOpcode() == Opcode) 4439 return *I; 4440 } 4441 return nullptr; 4442 } 4443 4444 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4445 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4446 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4447 case Intrinsic::amdgcn_if: 4448 return AMDGPUISD::IF; 4449 case Intrinsic::amdgcn_else: 4450 return AMDGPUISD::ELSE; 4451 case Intrinsic::amdgcn_loop: 4452 return AMDGPUISD::LOOP; 4453 case Intrinsic::amdgcn_end_cf: 4454 llvm_unreachable("should not occur"); 4455 default: 4456 return 0; 4457 } 4458 } 4459 4460 // break, if_break, else_break are all only used as inputs to loop, not 4461 // directly as branch conditions. 4462 return 0; 4463 } 4464 4465 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4466 const Triple &TT = getTargetMachine().getTargetTriple(); 4467 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4468 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4469 AMDGPU::shouldEmitConstantsToTextSection(TT); 4470 } 4471 4472 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4473 // FIXME: Either avoid relying on address space here or change the default 4474 // address space for functions to avoid the explicit check. 4475 return (GV->getValueType()->isFunctionTy() || 4476 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4477 !shouldEmitFixup(GV) && 4478 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4479 } 4480 4481 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4482 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4483 } 4484 4485 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4486 if (!GV->hasExternalLinkage()) 4487 return true; 4488 4489 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4490 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4491 } 4492 4493 /// This transforms the control flow intrinsics to get the branch destination as 4494 /// last parameter, also switches branch target with BR if the need arise 4495 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4496 SelectionDAG &DAG) const { 4497 SDLoc DL(BRCOND); 4498 4499 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4500 SDValue Target = BRCOND.getOperand(2); 4501 SDNode *BR = nullptr; 4502 SDNode *SetCC = nullptr; 4503 4504 if (Intr->getOpcode() == ISD::SETCC) { 4505 // As long as we negate the condition everything is fine 4506 SetCC = Intr; 4507 Intr = SetCC->getOperand(0).getNode(); 4508 4509 } else { 4510 // Get the target from BR if we don't negate the condition 4511 BR = findUser(BRCOND, ISD::BR); 4512 Target = BR->getOperand(1); 4513 } 4514 4515 // FIXME: This changes the types of the intrinsics instead of introducing new 4516 // nodes with the correct types. 4517 // e.g. llvm.amdgcn.loop 4518 4519 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4520 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4521 4522 unsigned CFNode = isCFIntrinsic(Intr); 4523 if (CFNode == 0) { 4524 // This is a uniform branch so we don't need to legalize. 4525 return BRCOND; 4526 } 4527 4528 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4529 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4530 4531 assert(!SetCC || 4532 (SetCC->getConstantOperandVal(1) == 1 && 4533 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4534 ISD::SETNE)); 4535 4536 // operands of the new intrinsic call 4537 SmallVector<SDValue, 4> Ops; 4538 if (HaveChain) 4539 Ops.push_back(BRCOND.getOperand(0)); 4540 4541 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4542 Ops.push_back(Target); 4543 4544 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4545 4546 // build the new intrinsic call 4547 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4548 4549 if (!HaveChain) { 4550 SDValue Ops[] = { 4551 SDValue(Result, 0), 4552 BRCOND.getOperand(0) 4553 }; 4554 4555 Result = DAG.getMergeValues(Ops, DL).getNode(); 4556 } 4557 4558 if (BR) { 4559 // Give the branch instruction our target 4560 SDValue Ops[] = { 4561 BR->getOperand(0), 4562 BRCOND.getOperand(2) 4563 }; 4564 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4565 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4566 BR = NewBR.getNode(); 4567 } 4568 4569 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4570 4571 // Copy the intrinsic results to registers 4572 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4573 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4574 if (!CopyToReg) 4575 continue; 4576 4577 Chain = DAG.getCopyToReg( 4578 Chain, DL, 4579 CopyToReg->getOperand(1), 4580 SDValue(Result, i - 1), 4581 SDValue()); 4582 4583 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4584 } 4585 4586 // Remove the old intrinsic from the chain 4587 DAG.ReplaceAllUsesOfValueWith( 4588 SDValue(Intr, Intr->getNumValues() - 1), 4589 Intr->getOperand(0)); 4590 4591 return Chain; 4592 } 4593 4594 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4595 SelectionDAG &DAG) const { 4596 MVT VT = Op.getSimpleValueType(); 4597 SDLoc DL(Op); 4598 // Checking the depth 4599 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4600 return DAG.getConstant(0, DL, VT); 4601 4602 MachineFunction &MF = DAG.getMachineFunction(); 4603 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4604 // Check for kernel and shader functions 4605 if (Info->isEntryFunction()) 4606 return DAG.getConstant(0, DL, VT); 4607 4608 MachineFrameInfo &MFI = MF.getFrameInfo(); 4609 // There is a call to @llvm.returnaddress in this function 4610 MFI.setReturnAddressIsTaken(true); 4611 4612 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4613 // Get the return address reg and mark it as an implicit live-in 4614 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4615 4616 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4617 } 4618 4619 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4620 SDValue Op, 4621 const SDLoc &DL, 4622 EVT VT) const { 4623 return Op.getValueType().bitsLE(VT) ? 4624 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4625 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4626 DAG.getTargetConstant(0, DL, MVT::i32)); 4627 } 4628 4629 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4630 assert(Op.getValueType() == MVT::f16 && 4631 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4632 4633 SDValue Src = Op.getOperand(0); 4634 EVT SrcVT = Src.getValueType(); 4635 if (SrcVT != MVT::f64) 4636 return Op; 4637 4638 SDLoc DL(Op); 4639 4640 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4641 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4642 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4643 } 4644 4645 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4646 SelectionDAG &DAG) const { 4647 EVT VT = Op.getValueType(); 4648 const MachineFunction &MF = DAG.getMachineFunction(); 4649 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4650 bool IsIEEEMode = Info->getMode().IEEE; 4651 4652 // FIXME: Assert during selection that this is only selected for 4653 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4654 // mode functions, but this happens to be OK since it's only done in cases 4655 // where there is known no sNaN. 4656 if (IsIEEEMode) 4657 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4658 4659 if (VT == MVT::v4f16) 4660 return splitBinaryVectorOp(Op, DAG); 4661 return Op; 4662 } 4663 4664 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4665 SDLoc SL(Op); 4666 SDValue Chain = Op.getOperand(0); 4667 4668 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4669 !Subtarget->isTrapHandlerEnabled()) 4670 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4671 4672 MachineFunction &MF = DAG.getMachineFunction(); 4673 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4674 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4675 assert(UserSGPR != AMDGPU::NoRegister); 4676 SDValue QueuePtr = CreateLiveInRegister( 4677 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4678 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4679 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4680 QueuePtr, SDValue()); 4681 SDValue Ops[] = { 4682 ToReg, 4683 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4684 SGPR01, 4685 ToReg.getValue(1) 4686 }; 4687 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4688 } 4689 4690 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4691 SDLoc SL(Op); 4692 SDValue Chain = Op.getOperand(0); 4693 MachineFunction &MF = DAG.getMachineFunction(); 4694 4695 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4696 !Subtarget->isTrapHandlerEnabled()) { 4697 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4698 "debugtrap handler not supported", 4699 Op.getDebugLoc(), 4700 DS_Warning); 4701 LLVMContext &Ctx = MF.getFunction().getContext(); 4702 Ctx.diagnose(NoTrap); 4703 return Chain; 4704 } 4705 4706 SDValue Ops[] = { 4707 Chain, 4708 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4709 }; 4710 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4711 } 4712 4713 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4714 SelectionDAG &DAG) const { 4715 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4716 if (Subtarget->hasApertureRegs()) { 4717 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4718 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4719 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4720 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4721 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4722 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4723 unsigned Encoding = 4724 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4725 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4726 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4727 4728 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4729 SDValue ApertureReg = SDValue( 4730 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4731 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4732 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4733 } 4734 4735 MachineFunction &MF = DAG.getMachineFunction(); 4736 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4737 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4738 assert(UserSGPR != AMDGPU::NoRegister); 4739 4740 SDValue QueuePtr = CreateLiveInRegister( 4741 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4742 4743 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4744 // private_segment_aperture_base_hi. 4745 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4746 4747 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4748 4749 // TODO: Use custom target PseudoSourceValue. 4750 // TODO: We should use the value from the IR intrinsic call, but it might not 4751 // be available and how do we get it? 4752 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4753 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4754 MinAlign(64, StructOffset), 4755 MachineMemOperand::MODereferenceable | 4756 MachineMemOperand::MOInvariant); 4757 } 4758 4759 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4760 SelectionDAG &DAG) const { 4761 SDLoc SL(Op); 4762 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4763 4764 SDValue Src = ASC->getOperand(0); 4765 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4766 4767 const AMDGPUTargetMachine &TM = 4768 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4769 4770 // flat -> local/private 4771 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4772 unsigned DestAS = ASC->getDestAddressSpace(); 4773 4774 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4775 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4776 unsigned NullVal = TM.getNullPointerValue(DestAS); 4777 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4778 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4779 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4780 4781 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4782 NonNull, Ptr, SegmentNullPtr); 4783 } 4784 } 4785 4786 // local/private -> flat 4787 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4788 unsigned SrcAS = ASC->getSrcAddressSpace(); 4789 4790 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4791 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4792 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4793 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4794 4795 SDValue NonNull 4796 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4797 4798 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4799 SDValue CvtPtr 4800 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4801 4802 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4803 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4804 FlatNullPtr); 4805 } 4806 } 4807 4808 // global <-> flat are no-ops and never emitted. 4809 4810 const MachineFunction &MF = DAG.getMachineFunction(); 4811 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4812 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4813 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4814 4815 return DAG.getUNDEF(ASC->getValueType(0)); 4816 } 4817 4818 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4819 // the small vector and inserting them into the big vector. That is better than 4820 // the default expansion of doing it via a stack slot. Even though the use of 4821 // the stack slot would be optimized away afterwards, the stack slot itself 4822 // remains. 4823 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4824 SelectionDAG &DAG) const { 4825 SDValue Vec = Op.getOperand(0); 4826 SDValue Ins = Op.getOperand(1); 4827 SDValue Idx = Op.getOperand(2); 4828 EVT VecVT = Vec.getValueType(); 4829 EVT InsVT = Ins.getValueType(); 4830 EVT EltVT = VecVT.getVectorElementType(); 4831 unsigned InsNumElts = InsVT.getVectorNumElements(); 4832 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4833 SDLoc SL(Op); 4834 4835 for (unsigned I = 0; I != InsNumElts; ++I) { 4836 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4837 DAG.getConstant(I, SL, MVT::i32)); 4838 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4839 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4840 } 4841 return Vec; 4842 } 4843 4844 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4845 SelectionDAG &DAG) const { 4846 SDValue Vec = Op.getOperand(0); 4847 SDValue InsVal = Op.getOperand(1); 4848 SDValue Idx = Op.getOperand(2); 4849 EVT VecVT = Vec.getValueType(); 4850 EVT EltVT = VecVT.getVectorElementType(); 4851 unsigned VecSize = VecVT.getSizeInBits(); 4852 unsigned EltSize = EltVT.getSizeInBits(); 4853 4854 4855 assert(VecSize <= 64); 4856 4857 unsigned NumElts = VecVT.getVectorNumElements(); 4858 SDLoc SL(Op); 4859 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4860 4861 if (NumElts == 4 && EltSize == 16 && KIdx) { 4862 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4863 4864 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4865 DAG.getConstant(0, SL, MVT::i32)); 4866 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4867 DAG.getConstant(1, SL, MVT::i32)); 4868 4869 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4870 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4871 4872 unsigned Idx = KIdx->getZExtValue(); 4873 bool InsertLo = Idx < 2; 4874 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4875 InsertLo ? LoVec : HiVec, 4876 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4877 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4878 4879 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4880 4881 SDValue Concat = InsertLo ? 4882 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4883 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4884 4885 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4886 } 4887 4888 if (isa<ConstantSDNode>(Idx)) 4889 return SDValue(); 4890 4891 MVT IntVT = MVT::getIntegerVT(VecSize); 4892 4893 // Avoid stack access for dynamic indexing. 4894 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4895 4896 // Create a congruent vector with the target value in each element so that 4897 // the required element can be masked and ORed into the target vector. 4898 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4899 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4900 4901 assert(isPowerOf2_32(EltSize)); 4902 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4903 4904 // Convert vector index to bit-index. 4905 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4906 4907 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4908 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4909 DAG.getConstant(0xffff, SL, IntVT), 4910 ScaledIdx); 4911 4912 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4913 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4914 DAG.getNOT(SL, BFM, IntVT), BCVec); 4915 4916 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4917 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4918 } 4919 4920 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4921 SelectionDAG &DAG) const { 4922 SDLoc SL(Op); 4923 4924 EVT ResultVT = Op.getValueType(); 4925 SDValue Vec = Op.getOperand(0); 4926 SDValue Idx = Op.getOperand(1); 4927 EVT VecVT = Vec.getValueType(); 4928 unsigned VecSize = VecVT.getSizeInBits(); 4929 EVT EltVT = VecVT.getVectorElementType(); 4930 assert(VecSize <= 64); 4931 4932 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4933 4934 // Make sure we do any optimizations that will make it easier to fold 4935 // source modifiers before obscuring it with bit operations. 4936 4937 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4938 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4939 return Combined; 4940 4941 unsigned EltSize = EltVT.getSizeInBits(); 4942 assert(isPowerOf2_32(EltSize)); 4943 4944 MVT IntVT = MVT::getIntegerVT(VecSize); 4945 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4946 4947 // Convert vector index to bit-index (* EltSize) 4948 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4949 4950 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4951 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4952 4953 if (ResultVT == MVT::f16) { 4954 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4955 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4956 } 4957 4958 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4959 } 4960 4961 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4962 assert(Elt % 2 == 0); 4963 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4964 } 4965 4966 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4967 SelectionDAG &DAG) const { 4968 SDLoc SL(Op); 4969 EVT ResultVT = Op.getValueType(); 4970 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4971 4972 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4973 EVT EltVT = PackVT.getVectorElementType(); 4974 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4975 4976 // vector_shuffle <0,1,6,7> lhs, rhs 4977 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4978 // 4979 // vector_shuffle <6,7,2,3> lhs, rhs 4980 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4981 // 4982 // vector_shuffle <6,7,0,1> lhs, rhs 4983 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4984 4985 // Avoid scalarizing when both halves are reading from consecutive elements. 4986 SmallVector<SDValue, 4> Pieces; 4987 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4988 if (elementPairIsContiguous(SVN->getMask(), I)) { 4989 const int Idx = SVN->getMaskElt(I); 4990 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4991 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4992 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4993 PackVT, SVN->getOperand(VecIdx), 4994 DAG.getConstant(EltIdx, SL, MVT::i32)); 4995 Pieces.push_back(SubVec); 4996 } else { 4997 const int Idx0 = SVN->getMaskElt(I); 4998 const int Idx1 = SVN->getMaskElt(I + 1); 4999 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5000 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5001 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5002 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5003 5004 SDValue Vec0 = SVN->getOperand(VecIdx0); 5005 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5006 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5007 5008 SDValue Vec1 = SVN->getOperand(VecIdx1); 5009 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5010 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5011 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5012 } 5013 } 5014 5015 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5016 } 5017 5018 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5019 SelectionDAG &DAG) const { 5020 SDLoc SL(Op); 5021 EVT VT = Op.getValueType(); 5022 5023 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5024 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5025 5026 // Turn into pair of packed build_vectors. 5027 // TODO: Special case for constants that can be materialized with s_mov_b64. 5028 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5029 { Op.getOperand(0), Op.getOperand(1) }); 5030 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5031 { Op.getOperand(2), Op.getOperand(3) }); 5032 5033 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5034 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5035 5036 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5037 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5038 } 5039 5040 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5041 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5042 5043 SDValue Lo = Op.getOperand(0); 5044 SDValue Hi = Op.getOperand(1); 5045 5046 // Avoid adding defined bits with the zero_extend. 5047 if (Hi.isUndef()) { 5048 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5049 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5050 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5051 } 5052 5053 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5054 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5055 5056 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5057 DAG.getConstant(16, SL, MVT::i32)); 5058 if (Lo.isUndef()) 5059 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5060 5061 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5062 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5063 5064 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5065 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5066 } 5067 5068 bool 5069 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5070 // We can fold offsets for anything that doesn't require a GOT relocation. 5071 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5072 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5073 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5074 !shouldEmitGOTReloc(GA->getGlobal()); 5075 } 5076 5077 static SDValue 5078 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5079 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5080 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5081 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5082 // lowered to the following code sequence: 5083 // 5084 // For constant address space: 5085 // s_getpc_b64 s[0:1] 5086 // s_add_u32 s0, s0, $symbol 5087 // s_addc_u32 s1, s1, 0 5088 // 5089 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5090 // a fixup or relocation is emitted to replace $symbol with a literal 5091 // constant, which is a pc-relative offset from the encoding of the $symbol 5092 // operand to the global variable. 5093 // 5094 // For global address space: 5095 // s_getpc_b64 s[0:1] 5096 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5097 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5098 // 5099 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5100 // fixups or relocations are emitted to replace $symbol@*@lo and 5101 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5102 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5103 // operand to the global variable. 5104 // 5105 // What we want here is an offset from the value returned by s_getpc 5106 // (which is the address of the s_add_u32 instruction) to the global 5107 // variable, but since the encoding of $symbol starts 4 bytes after the start 5108 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5109 // small. This requires us to add 4 to the global variable offset in order to 5110 // compute the correct address. 5111 SDValue PtrLo = 5112 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5113 SDValue PtrHi; 5114 if (GAFlags == SIInstrInfo::MO_NONE) { 5115 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5116 } else { 5117 PtrHi = 5118 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5119 } 5120 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5121 } 5122 5123 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5124 SDValue Op, 5125 SelectionDAG &DAG) const { 5126 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5127 const GlobalValue *GV = GSD->getGlobal(); 5128 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5129 shouldUseLDSConstAddress(GV)) || 5130 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5131 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5132 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5133 5134 SDLoc DL(GSD); 5135 EVT PtrVT = Op.getValueType(); 5136 5137 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5138 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5139 SIInstrInfo::MO_ABS32_LO); 5140 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5141 } 5142 5143 if (shouldEmitFixup(GV)) 5144 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5145 else if (shouldEmitPCReloc(GV)) 5146 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5147 SIInstrInfo::MO_REL32); 5148 5149 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5150 SIInstrInfo::MO_GOTPCREL32); 5151 5152 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5153 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5154 const DataLayout &DataLayout = DAG.getDataLayout(); 5155 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5156 MachinePointerInfo PtrInfo 5157 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5158 5159 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5160 MachineMemOperand::MODereferenceable | 5161 MachineMemOperand::MOInvariant); 5162 } 5163 5164 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5165 const SDLoc &DL, SDValue V) const { 5166 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5167 // the destination register. 5168 // 5169 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5170 // so we will end up with redundant moves to m0. 5171 // 5172 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5173 5174 // A Null SDValue creates a glue result. 5175 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5176 V, Chain); 5177 return SDValue(M0, 0); 5178 } 5179 5180 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5181 SDValue Op, 5182 MVT VT, 5183 unsigned Offset) const { 5184 SDLoc SL(Op); 5185 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5186 DAG.getEntryNode(), Offset, 4, false); 5187 // The local size values will have the hi 16-bits as zero. 5188 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5189 DAG.getValueType(VT)); 5190 } 5191 5192 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5193 EVT VT) { 5194 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5195 "non-hsa intrinsic with hsa target", 5196 DL.getDebugLoc()); 5197 DAG.getContext()->diagnose(BadIntrin); 5198 return DAG.getUNDEF(VT); 5199 } 5200 5201 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5202 EVT VT) { 5203 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5204 "intrinsic not supported on subtarget", 5205 DL.getDebugLoc()); 5206 DAG.getContext()->diagnose(BadIntrin); 5207 return DAG.getUNDEF(VT); 5208 } 5209 5210 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5211 ArrayRef<SDValue> Elts) { 5212 assert(!Elts.empty()); 5213 MVT Type; 5214 unsigned NumElts; 5215 5216 if (Elts.size() == 1) { 5217 Type = MVT::f32; 5218 NumElts = 1; 5219 } else if (Elts.size() == 2) { 5220 Type = MVT::v2f32; 5221 NumElts = 2; 5222 } else if (Elts.size() == 3) { 5223 Type = MVT::v3f32; 5224 NumElts = 3; 5225 } else if (Elts.size() <= 4) { 5226 Type = MVT::v4f32; 5227 NumElts = 4; 5228 } else if (Elts.size() <= 8) { 5229 Type = MVT::v8f32; 5230 NumElts = 8; 5231 } else { 5232 assert(Elts.size() <= 16); 5233 Type = MVT::v16f32; 5234 NumElts = 16; 5235 } 5236 5237 SmallVector<SDValue, 16> VecElts(NumElts); 5238 for (unsigned i = 0; i < Elts.size(); ++i) { 5239 SDValue Elt = Elts[i]; 5240 if (Elt.getValueType() != MVT::f32) 5241 Elt = DAG.getBitcast(MVT::f32, Elt); 5242 VecElts[i] = Elt; 5243 } 5244 for (unsigned i = Elts.size(); i < NumElts; ++i) 5245 VecElts[i] = DAG.getUNDEF(MVT::f32); 5246 5247 if (NumElts == 1) 5248 return VecElts[0]; 5249 return DAG.getBuildVector(Type, DL, VecElts); 5250 } 5251 5252 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5253 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5254 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5255 5256 uint64_t Value = CachePolicyConst->getZExtValue(); 5257 SDLoc DL(CachePolicy); 5258 if (GLC) { 5259 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5260 Value &= ~(uint64_t)0x1; 5261 } 5262 if (SLC) { 5263 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5264 Value &= ~(uint64_t)0x2; 5265 } 5266 if (DLC) { 5267 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5268 Value &= ~(uint64_t)0x4; 5269 } 5270 5271 return Value == 0; 5272 } 5273 5274 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5275 SDValue Src, int ExtraElts) { 5276 EVT SrcVT = Src.getValueType(); 5277 5278 SmallVector<SDValue, 8> Elts; 5279 5280 if (SrcVT.isVector()) 5281 DAG.ExtractVectorElements(Src, Elts); 5282 else 5283 Elts.push_back(Src); 5284 5285 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5286 while (ExtraElts--) 5287 Elts.push_back(Undef); 5288 5289 return DAG.getBuildVector(CastVT, DL, Elts); 5290 } 5291 5292 // Re-construct the required return value for a image load intrinsic. 5293 // This is more complicated due to the optional use TexFailCtrl which means the required 5294 // return type is an aggregate 5295 static SDValue constructRetValue(SelectionDAG &DAG, 5296 MachineSDNode *Result, 5297 ArrayRef<EVT> ResultTypes, 5298 bool IsTexFail, bool Unpacked, bool IsD16, 5299 int DMaskPop, int NumVDataDwords, 5300 const SDLoc &DL, LLVMContext &Context) { 5301 // Determine the required return type. This is the same regardless of IsTexFail flag 5302 EVT ReqRetVT = ResultTypes[0]; 5303 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5304 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5305 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5306 5307 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5308 DMaskPop : (DMaskPop + 1) / 2; 5309 5310 MVT DataDwordVT = NumDataDwords == 1 ? 5311 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5312 5313 MVT MaskPopVT = MaskPopDwords == 1 ? 5314 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5315 5316 SDValue Data(Result, 0); 5317 SDValue TexFail; 5318 5319 if (IsTexFail) { 5320 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5321 if (MaskPopVT.isVector()) { 5322 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5323 SDValue(Result, 0), ZeroIdx); 5324 } else { 5325 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5326 SDValue(Result, 0), ZeroIdx); 5327 } 5328 5329 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5330 SDValue(Result, 0), 5331 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5332 } 5333 5334 if (DataDwordVT.isVector()) 5335 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5336 NumDataDwords - MaskPopDwords); 5337 5338 if (IsD16) 5339 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5340 5341 if (!ReqRetVT.isVector()) 5342 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5343 5344 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5345 5346 if (TexFail) 5347 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5348 5349 if (Result->getNumValues() == 1) 5350 return Data; 5351 5352 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5353 } 5354 5355 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5356 SDValue *LWE, bool &IsTexFail) { 5357 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5358 5359 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5360 if (Value) { 5361 IsTexFail = true; 5362 } 5363 5364 SDLoc DL(TexFailCtrlConst); 5365 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5366 Value &= ~(uint64_t)0x1; 5367 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5368 Value &= ~(uint64_t)0x2; 5369 5370 return Value == 0; 5371 } 5372 5373 SDValue SITargetLowering::lowerImage(SDValue Op, 5374 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5375 SelectionDAG &DAG) const { 5376 SDLoc DL(Op); 5377 MachineFunction &MF = DAG.getMachineFunction(); 5378 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5379 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5380 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5381 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5382 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5383 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5384 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5385 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5386 unsigned IntrOpcode = Intr->BaseOpcode; 5387 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5388 5389 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5390 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5391 bool IsD16 = false; 5392 bool IsA16 = false; 5393 SDValue VData; 5394 int NumVDataDwords; 5395 bool AdjustRetType = false; 5396 5397 unsigned AddrIdx; // Index of first address argument 5398 unsigned DMask; 5399 unsigned DMaskLanes = 0; 5400 5401 if (BaseOpcode->Atomic) { 5402 VData = Op.getOperand(2); 5403 5404 bool Is64Bit = VData.getValueType() == MVT::i64; 5405 if (BaseOpcode->AtomicX2) { 5406 SDValue VData2 = Op.getOperand(3); 5407 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5408 {VData, VData2}); 5409 if (Is64Bit) 5410 VData = DAG.getBitcast(MVT::v4i32, VData); 5411 5412 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5413 DMask = Is64Bit ? 0xf : 0x3; 5414 NumVDataDwords = Is64Bit ? 4 : 2; 5415 AddrIdx = 4; 5416 } else { 5417 DMask = Is64Bit ? 0x3 : 0x1; 5418 NumVDataDwords = Is64Bit ? 2 : 1; 5419 AddrIdx = 3; 5420 } 5421 } else { 5422 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5423 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5424 DMask = DMaskConst->getZExtValue(); 5425 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5426 5427 if (BaseOpcode->Store) { 5428 VData = Op.getOperand(2); 5429 5430 MVT StoreVT = VData.getSimpleValueType(); 5431 if (StoreVT.getScalarType() == MVT::f16) { 5432 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5433 return Op; // D16 is unsupported for this instruction 5434 5435 IsD16 = true; 5436 VData = handleD16VData(VData, DAG); 5437 } 5438 5439 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5440 } else { 5441 // Work out the num dwords based on the dmask popcount and underlying type 5442 // and whether packing is supported. 5443 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5444 if (LoadVT.getScalarType() == MVT::f16) { 5445 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5446 return Op; // D16 is unsupported for this instruction 5447 5448 IsD16 = true; 5449 } 5450 5451 // Confirm that the return type is large enough for the dmask specified 5452 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5453 (!LoadVT.isVector() && DMaskLanes > 1)) 5454 return Op; 5455 5456 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5457 NumVDataDwords = (DMaskLanes + 1) / 2; 5458 else 5459 NumVDataDwords = DMaskLanes; 5460 5461 AdjustRetType = true; 5462 } 5463 5464 AddrIdx = DMaskIdx + 1; 5465 } 5466 5467 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5468 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5469 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5470 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5471 NumCoords + NumLCM; 5472 unsigned NumMIVAddrs = NumVAddrs; 5473 5474 SmallVector<SDValue, 4> VAddrs; 5475 5476 // Optimize _L to _LZ when _L is zero 5477 if (LZMappingInfo) { 5478 if (auto ConstantLod = 5479 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5480 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5481 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5482 NumMIVAddrs--; // remove 'lod' 5483 } 5484 } 5485 } 5486 5487 // Optimize _mip away, when 'lod' is zero 5488 if (MIPMappingInfo) { 5489 if (auto ConstantLod = 5490 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5491 if (ConstantLod->isNullValue()) { 5492 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5493 NumMIVAddrs--; // remove 'lod' 5494 } 5495 } 5496 } 5497 5498 // Check for 16 bit addresses and pack if true. 5499 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5500 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5501 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5502 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5503 // Illegal to use a16 images 5504 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5505 return Op; 5506 5507 IsA16 = true; 5508 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5509 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5510 SDValue AddrLo; 5511 // Push back extra arguments. 5512 if (i < DimIdx) { 5513 AddrLo = Op.getOperand(i); 5514 } else { 5515 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5516 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5517 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5518 ((NumGradients / 2) % 2 == 1 && 5519 (i == DimIdx + (NumGradients / 2) - 1 || 5520 i == DimIdx + NumGradients - 1))) { 5521 AddrLo = Op.getOperand(i); 5522 if (AddrLo.getValueType() != MVT::i16) 5523 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5524 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5525 } else { 5526 AddrLo = DAG.getBuildVector(VectorVT, DL, 5527 {Op.getOperand(i), Op.getOperand(i + 1)}); 5528 i++; 5529 } 5530 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5531 } 5532 VAddrs.push_back(AddrLo); 5533 } 5534 } else { 5535 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5536 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5537 } 5538 5539 // If the register allocator cannot place the address registers contiguously 5540 // without introducing moves, then using the non-sequential address encoding 5541 // is always preferable, since it saves VALU instructions and is usually a 5542 // wash in terms of code size or even better. 5543 // 5544 // However, we currently have no way of hinting to the register allocator that 5545 // MIMG addresses should be placed contiguously when it is possible to do so, 5546 // so force non-NSA for the common 2-address case as a heuristic. 5547 // 5548 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5549 // allocation when possible. 5550 bool UseNSA = 5551 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5552 SDValue VAddr; 5553 if (!UseNSA) 5554 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5555 5556 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5557 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5558 unsigned CtrlIdx; // Index of texfailctrl argument 5559 SDValue Unorm; 5560 if (!BaseOpcode->Sampler) { 5561 Unorm = True; 5562 CtrlIdx = AddrIdx + NumVAddrs + 1; 5563 } else { 5564 auto UnormConst = 5565 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5566 5567 Unorm = UnormConst->getZExtValue() ? True : False; 5568 CtrlIdx = AddrIdx + NumVAddrs + 3; 5569 } 5570 5571 SDValue TFE; 5572 SDValue LWE; 5573 SDValue TexFail = Op.getOperand(CtrlIdx); 5574 bool IsTexFail = false; 5575 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5576 return Op; 5577 5578 if (IsTexFail) { 5579 if (!DMaskLanes) { 5580 // Expecting to get an error flag since TFC is on - and dmask is 0 5581 // Force dmask to be at least 1 otherwise the instruction will fail 5582 DMask = 0x1; 5583 DMaskLanes = 1; 5584 NumVDataDwords = 1; 5585 } 5586 NumVDataDwords += 1; 5587 AdjustRetType = true; 5588 } 5589 5590 // Has something earlier tagged that the return type needs adjusting 5591 // This happens if the instruction is a load or has set TexFailCtrl flags 5592 if (AdjustRetType) { 5593 // NumVDataDwords reflects the true number of dwords required in the return type 5594 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5595 // This is a no-op load. This can be eliminated 5596 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5597 if (isa<MemSDNode>(Op)) 5598 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5599 return Undef; 5600 } 5601 5602 EVT NewVT = NumVDataDwords > 1 ? 5603 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5604 : MVT::i32; 5605 5606 ResultTypes[0] = NewVT; 5607 if (ResultTypes.size() == 3) { 5608 // Original result was aggregate type used for TexFailCtrl results 5609 // The actual instruction returns as a vector type which has now been 5610 // created. Remove the aggregate result. 5611 ResultTypes.erase(&ResultTypes[1]); 5612 } 5613 } 5614 5615 SDValue GLC; 5616 SDValue SLC; 5617 SDValue DLC; 5618 if (BaseOpcode->Atomic) { 5619 GLC = True; // TODO no-return optimization 5620 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5621 IsGFX10 ? &DLC : nullptr)) 5622 return Op; 5623 } else { 5624 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5625 IsGFX10 ? &DLC : nullptr)) 5626 return Op; 5627 } 5628 5629 SmallVector<SDValue, 26> Ops; 5630 if (BaseOpcode->Store || BaseOpcode->Atomic) 5631 Ops.push_back(VData); // vdata 5632 if (UseNSA) { 5633 for (const SDValue &Addr : VAddrs) 5634 Ops.push_back(Addr); 5635 } else { 5636 Ops.push_back(VAddr); 5637 } 5638 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5639 if (BaseOpcode->Sampler) 5640 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5641 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5642 if (IsGFX10) 5643 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5644 Ops.push_back(Unorm); 5645 if (IsGFX10) 5646 Ops.push_back(DLC); 5647 Ops.push_back(GLC); 5648 Ops.push_back(SLC); 5649 Ops.push_back(IsA16 && // r128, a16 for gfx9 5650 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5651 if (IsGFX10) 5652 Ops.push_back(IsA16 ? True : False); 5653 Ops.push_back(TFE); 5654 Ops.push_back(LWE); 5655 if (!IsGFX10) 5656 Ops.push_back(DimInfo->DA ? True : False); 5657 if (BaseOpcode->HasD16) 5658 Ops.push_back(IsD16 ? True : False); 5659 if (isa<MemSDNode>(Op)) 5660 Ops.push_back(Op.getOperand(0)); // chain 5661 5662 int NumVAddrDwords = 5663 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5664 int Opcode = -1; 5665 5666 if (IsGFX10) { 5667 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5668 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5669 : AMDGPU::MIMGEncGfx10Default, 5670 NumVDataDwords, NumVAddrDwords); 5671 } else { 5672 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5673 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5674 NumVDataDwords, NumVAddrDwords); 5675 if (Opcode == -1) 5676 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5677 NumVDataDwords, NumVAddrDwords); 5678 } 5679 assert(Opcode != -1); 5680 5681 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5682 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5683 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5684 DAG.setNodeMemRefs(NewNode, {MemRef}); 5685 } 5686 5687 if (BaseOpcode->AtomicX2) { 5688 SmallVector<SDValue, 1> Elt; 5689 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5690 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5691 } else if (!BaseOpcode->Store) { 5692 return constructRetValue(DAG, NewNode, 5693 OrigResultTypes, IsTexFail, 5694 Subtarget->hasUnpackedD16VMem(), IsD16, 5695 DMaskLanes, NumVDataDwords, DL, 5696 *DAG.getContext()); 5697 } 5698 5699 return SDValue(NewNode, 0); 5700 } 5701 5702 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5703 SDValue Offset, SDValue CachePolicy, 5704 SelectionDAG &DAG) const { 5705 MachineFunction &MF = DAG.getMachineFunction(); 5706 5707 const DataLayout &DataLayout = DAG.getDataLayout(); 5708 Align Alignment = 5709 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 5710 5711 MachineMemOperand *MMO = MF.getMachineMemOperand( 5712 MachinePointerInfo(), 5713 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5714 MachineMemOperand::MOInvariant, 5715 VT.getStoreSize(), Alignment); 5716 5717 if (!Offset->isDivergent()) { 5718 SDValue Ops[] = { 5719 Rsrc, 5720 Offset, // Offset 5721 CachePolicy 5722 }; 5723 5724 // Widen vec3 load to vec4. 5725 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5726 EVT WidenedVT = 5727 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5728 auto WidenedOp = DAG.getMemIntrinsicNode( 5729 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5730 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5731 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5732 DAG.getVectorIdxConstant(0, DL)); 5733 return Subvector; 5734 } 5735 5736 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5737 DAG.getVTList(VT), Ops, VT, MMO); 5738 } 5739 5740 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5741 // assume that the buffer is unswizzled. 5742 SmallVector<SDValue, 4> Loads; 5743 unsigned NumLoads = 1; 5744 MVT LoadVT = VT.getSimpleVT(); 5745 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5746 assert((LoadVT.getScalarType() == MVT::i32 || 5747 LoadVT.getScalarType() == MVT::f32)); 5748 5749 if (NumElts == 8 || NumElts == 16) { 5750 NumLoads = NumElts / 4; 5751 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5752 } 5753 5754 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5755 SDValue Ops[] = { 5756 DAG.getEntryNode(), // Chain 5757 Rsrc, // rsrc 5758 DAG.getConstant(0, DL, MVT::i32), // vindex 5759 {}, // voffset 5760 {}, // soffset 5761 {}, // offset 5762 CachePolicy, // cachepolicy 5763 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5764 }; 5765 5766 // Use the alignment to ensure that the required offsets will fit into the 5767 // immediate offsets. 5768 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5769 5770 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5771 for (unsigned i = 0; i < NumLoads; ++i) { 5772 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5773 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5774 LoadVT, MMO, DAG)); 5775 } 5776 5777 if (NumElts == 8 || NumElts == 16) 5778 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5779 5780 return Loads[0]; 5781 } 5782 5783 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5784 SelectionDAG &DAG) const { 5785 MachineFunction &MF = DAG.getMachineFunction(); 5786 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5787 5788 EVT VT = Op.getValueType(); 5789 SDLoc DL(Op); 5790 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5791 5792 // TODO: Should this propagate fast-math-flags? 5793 5794 switch (IntrinsicID) { 5795 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5796 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5797 return emitNonHSAIntrinsicError(DAG, DL, VT); 5798 return getPreloadedValue(DAG, *MFI, VT, 5799 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5800 } 5801 case Intrinsic::amdgcn_dispatch_ptr: 5802 case Intrinsic::amdgcn_queue_ptr: { 5803 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5804 DiagnosticInfoUnsupported BadIntrin( 5805 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5806 DL.getDebugLoc()); 5807 DAG.getContext()->diagnose(BadIntrin); 5808 return DAG.getUNDEF(VT); 5809 } 5810 5811 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5812 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5813 return getPreloadedValue(DAG, *MFI, VT, RegID); 5814 } 5815 case Intrinsic::amdgcn_implicitarg_ptr: { 5816 if (MFI->isEntryFunction()) 5817 return getImplicitArgPtr(DAG, DL); 5818 return getPreloadedValue(DAG, *MFI, VT, 5819 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5820 } 5821 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5822 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 5823 // This only makes sense to call in a kernel, so just lower to null. 5824 return DAG.getConstant(0, DL, VT); 5825 } 5826 5827 return getPreloadedValue(DAG, *MFI, VT, 5828 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5829 } 5830 case Intrinsic::amdgcn_dispatch_id: { 5831 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5832 } 5833 case Intrinsic::amdgcn_rcp: 5834 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5835 case Intrinsic::amdgcn_rsq: 5836 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5837 case Intrinsic::amdgcn_rsq_legacy: 5838 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5839 return emitRemovedIntrinsicError(DAG, DL, VT); 5840 5841 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5842 case Intrinsic::amdgcn_rcp_legacy: 5843 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5844 return emitRemovedIntrinsicError(DAG, DL, VT); 5845 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5846 case Intrinsic::amdgcn_rsq_clamp: { 5847 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5848 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5849 5850 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5851 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5852 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5853 5854 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5855 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5856 DAG.getConstantFP(Max, DL, VT)); 5857 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5858 DAG.getConstantFP(Min, DL, VT)); 5859 } 5860 case Intrinsic::r600_read_ngroups_x: 5861 if (Subtarget->isAmdHsaOS()) 5862 return emitNonHSAIntrinsicError(DAG, DL, VT); 5863 5864 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5865 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5866 case Intrinsic::r600_read_ngroups_y: 5867 if (Subtarget->isAmdHsaOS()) 5868 return emitNonHSAIntrinsicError(DAG, DL, VT); 5869 5870 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5871 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5872 case Intrinsic::r600_read_ngroups_z: 5873 if (Subtarget->isAmdHsaOS()) 5874 return emitNonHSAIntrinsicError(DAG, DL, VT); 5875 5876 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5877 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5878 case Intrinsic::r600_read_global_size_x: 5879 if (Subtarget->isAmdHsaOS()) 5880 return emitNonHSAIntrinsicError(DAG, DL, VT); 5881 5882 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5883 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5884 case Intrinsic::r600_read_global_size_y: 5885 if (Subtarget->isAmdHsaOS()) 5886 return emitNonHSAIntrinsicError(DAG, DL, VT); 5887 5888 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5889 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5890 case Intrinsic::r600_read_global_size_z: 5891 if (Subtarget->isAmdHsaOS()) 5892 return emitNonHSAIntrinsicError(DAG, DL, VT); 5893 5894 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5895 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5896 case Intrinsic::r600_read_local_size_x: 5897 if (Subtarget->isAmdHsaOS()) 5898 return emitNonHSAIntrinsicError(DAG, DL, VT); 5899 5900 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5901 SI::KernelInputOffsets::LOCAL_SIZE_X); 5902 case Intrinsic::r600_read_local_size_y: 5903 if (Subtarget->isAmdHsaOS()) 5904 return emitNonHSAIntrinsicError(DAG, DL, VT); 5905 5906 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5907 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5908 case Intrinsic::r600_read_local_size_z: 5909 if (Subtarget->isAmdHsaOS()) 5910 return emitNonHSAIntrinsicError(DAG, DL, VT); 5911 5912 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5913 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5914 case Intrinsic::amdgcn_workgroup_id_x: 5915 return getPreloadedValue(DAG, *MFI, VT, 5916 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5917 case Intrinsic::amdgcn_workgroup_id_y: 5918 return getPreloadedValue(DAG, *MFI, VT, 5919 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5920 case Intrinsic::amdgcn_workgroup_id_z: 5921 return getPreloadedValue(DAG, *MFI, VT, 5922 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5923 case Intrinsic::amdgcn_workitem_id_x: 5924 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5925 SDLoc(DAG.getEntryNode()), 5926 MFI->getArgInfo().WorkItemIDX); 5927 case Intrinsic::amdgcn_workitem_id_y: 5928 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5929 SDLoc(DAG.getEntryNode()), 5930 MFI->getArgInfo().WorkItemIDY); 5931 case Intrinsic::amdgcn_workitem_id_z: 5932 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5933 SDLoc(DAG.getEntryNode()), 5934 MFI->getArgInfo().WorkItemIDZ); 5935 case Intrinsic::amdgcn_wavefrontsize: 5936 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5937 SDLoc(Op), MVT::i32); 5938 case Intrinsic::amdgcn_s_buffer_load: { 5939 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5940 SDValue GLC; 5941 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5942 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5943 IsGFX10 ? &DLC : nullptr)) 5944 return Op; 5945 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5946 DAG); 5947 } 5948 case Intrinsic::amdgcn_fdiv_fast: 5949 return lowerFDIV_FAST(Op, DAG); 5950 case Intrinsic::amdgcn_sin: 5951 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5952 5953 case Intrinsic::amdgcn_cos: 5954 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5955 5956 case Intrinsic::amdgcn_mul_u24: 5957 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5958 case Intrinsic::amdgcn_mul_i24: 5959 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5960 5961 case Intrinsic::amdgcn_log_clamp: { 5962 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5963 return SDValue(); 5964 5965 DiagnosticInfoUnsupported BadIntrin( 5966 MF.getFunction(), "intrinsic not supported on subtarget", 5967 DL.getDebugLoc()); 5968 DAG.getContext()->diagnose(BadIntrin); 5969 return DAG.getUNDEF(VT); 5970 } 5971 case Intrinsic::amdgcn_ldexp: 5972 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5973 Op.getOperand(1), Op.getOperand(2)); 5974 5975 case Intrinsic::amdgcn_fract: 5976 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5977 5978 case Intrinsic::amdgcn_class: 5979 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5980 Op.getOperand(1), Op.getOperand(2)); 5981 case Intrinsic::amdgcn_div_fmas: 5982 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5983 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5984 Op.getOperand(4)); 5985 5986 case Intrinsic::amdgcn_div_fixup: 5987 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5988 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5989 5990 case Intrinsic::amdgcn_trig_preop: 5991 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5992 Op.getOperand(1), Op.getOperand(2)); 5993 case Intrinsic::amdgcn_div_scale: { 5994 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5995 5996 // Translate to the operands expected by the machine instruction. The 5997 // first parameter must be the same as the first instruction. 5998 SDValue Numerator = Op.getOperand(1); 5999 SDValue Denominator = Op.getOperand(2); 6000 6001 // Note this order is opposite of the machine instruction's operations, 6002 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6003 // intrinsic has the numerator as the first operand to match a normal 6004 // division operation. 6005 6006 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6007 6008 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6009 Denominator, Numerator); 6010 } 6011 case Intrinsic::amdgcn_icmp: { 6012 // There is a Pat that handles this variant, so return it as-is. 6013 if (Op.getOperand(1).getValueType() == MVT::i1 && 6014 Op.getConstantOperandVal(2) == 0 && 6015 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6016 return Op; 6017 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6018 } 6019 case Intrinsic::amdgcn_fcmp: { 6020 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6021 } 6022 case Intrinsic::amdgcn_ballot: 6023 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6024 case Intrinsic::amdgcn_fmed3: 6025 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6026 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6027 case Intrinsic::amdgcn_fdot2: 6028 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6029 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6030 Op.getOperand(4)); 6031 case Intrinsic::amdgcn_fmul_legacy: 6032 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6033 Op.getOperand(1), Op.getOperand(2)); 6034 case Intrinsic::amdgcn_sffbh: 6035 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6036 case Intrinsic::amdgcn_sbfe: 6037 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6038 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6039 case Intrinsic::amdgcn_ubfe: 6040 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6041 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6042 case Intrinsic::amdgcn_cvt_pkrtz: 6043 case Intrinsic::amdgcn_cvt_pknorm_i16: 6044 case Intrinsic::amdgcn_cvt_pknorm_u16: 6045 case Intrinsic::amdgcn_cvt_pk_i16: 6046 case Intrinsic::amdgcn_cvt_pk_u16: { 6047 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6048 EVT VT = Op.getValueType(); 6049 unsigned Opcode; 6050 6051 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6052 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6053 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6054 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6055 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6056 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6057 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6058 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6059 else 6060 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6061 6062 if (isTypeLegal(VT)) 6063 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6064 6065 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6066 Op.getOperand(1), Op.getOperand(2)); 6067 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6068 } 6069 case Intrinsic::amdgcn_fmad_ftz: 6070 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6071 Op.getOperand(2), Op.getOperand(3)); 6072 6073 case Intrinsic::amdgcn_if_break: 6074 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6075 Op->getOperand(1), Op->getOperand(2)), 0); 6076 6077 case Intrinsic::amdgcn_groupstaticsize: { 6078 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6079 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6080 return Op; 6081 6082 const Module *M = MF.getFunction().getParent(); 6083 const GlobalValue *GV = 6084 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6085 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6086 SIInstrInfo::MO_ABS32_LO); 6087 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6088 } 6089 case Intrinsic::amdgcn_is_shared: 6090 case Intrinsic::amdgcn_is_private: { 6091 SDLoc SL(Op); 6092 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6093 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6094 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6095 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6096 Op.getOperand(1)); 6097 6098 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6099 DAG.getConstant(1, SL, MVT::i32)); 6100 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6101 } 6102 case Intrinsic::amdgcn_alignbit: 6103 return DAG.getNode(ISD::FSHR, DL, VT, 6104 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6105 case Intrinsic::amdgcn_reloc_constant: { 6106 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6107 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6108 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6109 auto RelocSymbol = cast<GlobalVariable>( 6110 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6111 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6112 SIInstrInfo::MO_ABS32_LO); 6113 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6114 } 6115 default: 6116 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6117 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6118 return lowerImage(Op, ImageDimIntr, DAG); 6119 6120 return Op; 6121 } 6122 } 6123 6124 // This function computes an appropriate offset to pass to 6125 // MachineMemOperand::setOffset() based on the offset inputs to 6126 // an intrinsic. If any of the offsets are non-contstant or 6127 // if VIndex is non-zero then this function returns 0. Otherwise, 6128 // it returns the sum of VOffset, SOffset, and Offset. 6129 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6130 SDValue SOffset, 6131 SDValue Offset, 6132 SDValue VIndex = SDValue()) { 6133 6134 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6135 !isa<ConstantSDNode>(Offset)) 6136 return 0; 6137 6138 if (VIndex) { 6139 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6140 return 0; 6141 } 6142 6143 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6144 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6145 cast<ConstantSDNode>(Offset)->getSExtValue(); 6146 } 6147 6148 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6149 switch (MF.getFunction().getCallingConv()) { 6150 case CallingConv::AMDGPU_PS: 6151 return 1; 6152 case CallingConv::AMDGPU_VS: 6153 return 2; 6154 case CallingConv::AMDGPU_GS: 6155 return 3; 6156 case CallingConv::AMDGPU_HS: 6157 case CallingConv::AMDGPU_LS: 6158 case CallingConv::AMDGPU_ES: 6159 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6160 case CallingConv::AMDGPU_CS: 6161 case CallingConv::AMDGPU_KERNEL: 6162 case CallingConv::C: 6163 case CallingConv::Fast: 6164 default: 6165 // Assume other calling conventions are various compute callable functions 6166 return 0; 6167 } 6168 } 6169 6170 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6171 SelectionDAG &DAG) const { 6172 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6173 SDLoc DL(Op); 6174 6175 switch (IntrID) { 6176 case Intrinsic::amdgcn_ds_ordered_add: 6177 case Intrinsic::amdgcn_ds_ordered_swap: { 6178 MemSDNode *M = cast<MemSDNode>(Op); 6179 SDValue Chain = M->getOperand(0); 6180 SDValue M0 = M->getOperand(2); 6181 SDValue Value = M->getOperand(3); 6182 unsigned IndexOperand = M->getConstantOperandVal(7); 6183 unsigned WaveRelease = M->getConstantOperandVal(8); 6184 unsigned WaveDone = M->getConstantOperandVal(9); 6185 6186 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6187 IndexOperand &= ~0x3f; 6188 unsigned CountDw = 0; 6189 6190 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6191 CountDw = (IndexOperand >> 24) & 0xf; 6192 IndexOperand &= ~(0xf << 24); 6193 6194 if (CountDw < 1 || CountDw > 4) { 6195 report_fatal_error( 6196 "ds_ordered_count: dword count must be between 1 and 4"); 6197 } 6198 } 6199 6200 if (IndexOperand) 6201 report_fatal_error("ds_ordered_count: bad index operand"); 6202 6203 if (WaveDone && !WaveRelease) 6204 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6205 6206 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6207 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6208 unsigned Offset0 = OrderedCountIndex << 2; 6209 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6210 (Instruction << 4); 6211 6212 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6213 Offset1 |= (CountDw - 1) << 6; 6214 6215 unsigned Offset = Offset0 | (Offset1 << 8); 6216 6217 SDValue Ops[] = { 6218 Chain, 6219 Value, 6220 DAG.getTargetConstant(Offset, DL, MVT::i16), 6221 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6222 }; 6223 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6224 M->getVTList(), Ops, M->getMemoryVT(), 6225 M->getMemOperand()); 6226 } 6227 case Intrinsic::amdgcn_ds_fadd: { 6228 MemSDNode *M = cast<MemSDNode>(Op); 6229 unsigned Opc; 6230 switch (IntrID) { 6231 case Intrinsic::amdgcn_ds_fadd: 6232 Opc = ISD::ATOMIC_LOAD_FADD; 6233 break; 6234 } 6235 6236 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6237 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6238 M->getMemOperand()); 6239 } 6240 case Intrinsic::amdgcn_atomic_inc: 6241 case Intrinsic::amdgcn_atomic_dec: 6242 case Intrinsic::amdgcn_ds_fmin: 6243 case Intrinsic::amdgcn_ds_fmax: { 6244 MemSDNode *M = cast<MemSDNode>(Op); 6245 unsigned Opc; 6246 switch (IntrID) { 6247 case Intrinsic::amdgcn_atomic_inc: 6248 Opc = AMDGPUISD::ATOMIC_INC; 6249 break; 6250 case Intrinsic::amdgcn_atomic_dec: 6251 Opc = AMDGPUISD::ATOMIC_DEC; 6252 break; 6253 case Intrinsic::amdgcn_ds_fmin: 6254 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6255 break; 6256 case Intrinsic::amdgcn_ds_fmax: 6257 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6258 break; 6259 default: 6260 llvm_unreachable("Unknown intrinsic!"); 6261 } 6262 SDValue Ops[] = { 6263 M->getOperand(0), // Chain 6264 M->getOperand(2), // Ptr 6265 M->getOperand(3) // Value 6266 }; 6267 6268 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6269 M->getMemoryVT(), M->getMemOperand()); 6270 } 6271 case Intrinsic::amdgcn_buffer_load: 6272 case Intrinsic::amdgcn_buffer_load_format: { 6273 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6274 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6275 unsigned IdxEn = 1; 6276 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6277 IdxEn = Idx->getZExtValue() != 0; 6278 SDValue Ops[] = { 6279 Op.getOperand(0), // Chain 6280 Op.getOperand(2), // rsrc 6281 Op.getOperand(3), // vindex 6282 SDValue(), // voffset -- will be set by setBufferOffsets 6283 SDValue(), // soffset -- will be set by setBufferOffsets 6284 SDValue(), // offset -- will be set by setBufferOffsets 6285 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6286 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6287 }; 6288 6289 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6290 // We don't know the offset if vindex is non-zero, so clear it. 6291 if (IdxEn) 6292 Offset = 0; 6293 6294 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6295 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6296 6297 EVT VT = Op.getValueType(); 6298 EVT IntVT = VT.changeTypeToInteger(); 6299 auto *M = cast<MemSDNode>(Op); 6300 M->getMemOperand()->setOffset(Offset); 6301 EVT LoadVT = Op.getValueType(); 6302 6303 if (LoadVT.getScalarType() == MVT::f16) 6304 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6305 M, DAG, Ops); 6306 6307 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6308 if (LoadVT.getScalarType() == MVT::i8 || 6309 LoadVT.getScalarType() == MVT::i16) 6310 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6311 6312 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6313 M->getMemOperand(), DAG); 6314 } 6315 case Intrinsic::amdgcn_raw_buffer_load: 6316 case Intrinsic::amdgcn_raw_buffer_load_format: { 6317 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6318 6319 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6320 SDValue Ops[] = { 6321 Op.getOperand(0), // Chain 6322 Op.getOperand(2), // rsrc 6323 DAG.getConstant(0, DL, MVT::i32), // vindex 6324 Offsets.first, // voffset 6325 Op.getOperand(4), // soffset 6326 Offsets.second, // offset 6327 Op.getOperand(5), // cachepolicy, swizzled buffer 6328 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6329 }; 6330 6331 auto *M = cast<MemSDNode>(Op); 6332 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6333 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6334 } 6335 case Intrinsic::amdgcn_struct_buffer_load: 6336 case Intrinsic::amdgcn_struct_buffer_load_format: { 6337 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6338 6339 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6340 SDValue Ops[] = { 6341 Op.getOperand(0), // Chain 6342 Op.getOperand(2), // rsrc 6343 Op.getOperand(3), // vindex 6344 Offsets.first, // voffset 6345 Op.getOperand(5), // soffset 6346 Offsets.second, // offset 6347 Op.getOperand(6), // cachepolicy, swizzled buffer 6348 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6349 }; 6350 6351 auto *M = cast<MemSDNode>(Op); 6352 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6353 Ops[2])); 6354 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6355 } 6356 case Intrinsic::amdgcn_tbuffer_load: { 6357 MemSDNode *M = cast<MemSDNode>(Op); 6358 EVT LoadVT = Op.getValueType(); 6359 6360 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6361 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6362 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6363 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6364 unsigned IdxEn = 1; 6365 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6366 IdxEn = Idx->getZExtValue() != 0; 6367 SDValue Ops[] = { 6368 Op.getOperand(0), // Chain 6369 Op.getOperand(2), // rsrc 6370 Op.getOperand(3), // vindex 6371 Op.getOperand(4), // voffset 6372 Op.getOperand(5), // soffset 6373 Op.getOperand(6), // offset 6374 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6375 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6376 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6377 }; 6378 6379 if (LoadVT.getScalarType() == MVT::f16) 6380 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6381 M, DAG, Ops); 6382 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6383 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6384 DAG); 6385 } 6386 case Intrinsic::amdgcn_raw_tbuffer_load: { 6387 MemSDNode *M = cast<MemSDNode>(Op); 6388 EVT LoadVT = Op.getValueType(); 6389 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6390 6391 SDValue Ops[] = { 6392 Op.getOperand(0), // Chain 6393 Op.getOperand(2), // rsrc 6394 DAG.getConstant(0, DL, MVT::i32), // vindex 6395 Offsets.first, // voffset 6396 Op.getOperand(4), // soffset 6397 Offsets.second, // offset 6398 Op.getOperand(5), // format 6399 Op.getOperand(6), // cachepolicy, swizzled buffer 6400 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6401 }; 6402 6403 if (LoadVT.getScalarType() == MVT::f16) 6404 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6405 M, DAG, Ops); 6406 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6407 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6408 DAG); 6409 } 6410 case Intrinsic::amdgcn_struct_tbuffer_load: { 6411 MemSDNode *M = cast<MemSDNode>(Op); 6412 EVT LoadVT = Op.getValueType(); 6413 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6414 6415 SDValue Ops[] = { 6416 Op.getOperand(0), // Chain 6417 Op.getOperand(2), // rsrc 6418 Op.getOperand(3), // vindex 6419 Offsets.first, // voffset 6420 Op.getOperand(5), // soffset 6421 Offsets.second, // offset 6422 Op.getOperand(6), // format 6423 Op.getOperand(7), // cachepolicy, swizzled buffer 6424 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6425 }; 6426 6427 if (LoadVT.getScalarType() == MVT::f16) 6428 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6429 M, DAG, Ops); 6430 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6431 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6432 DAG); 6433 } 6434 case Intrinsic::amdgcn_buffer_atomic_swap: 6435 case Intrinsic::amdgcn_buffer_atomic_add: 6436 case Intrinsic::amdgcn_buffer_atomic_sub: 6437 case Intrinsic::amdgcn_buffer_atomic_smin: 6438 case Intrinsic::amdgcn_buffer_atomic_umin: 6439 case Intrinsic::amdgcn_buffer_atomic_smax: 6440 case Intrinsic::amdgcn_buffer_atomic_umax: 6441 case Intrinsic::amdgcn_buffer_atomic_and: 6442 case Intrinsic::amdgcn_buffer_atomic_or: 6443 case Intrinsic::amdgcn_buffer_atomic_xor: { 6444 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6445 unsigned IdxEn = 1; 6446 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6447 IdxEn = Idx->getZExtValue() != 0; 6448 SDValue Ops[] = { 6449 Op.getOperand(0), // Chain 6450 Op.getOperand(2), // vdata 6451 Op.getOperand(3), // rsrc 6452 Op.getOperand(4), // vindex 6453 SDValue(), // voffset -- will be set by setBufferOffsets 6454 SDValue(), // soffset -- will be set by setBufferOffsets 6455 SDValue(), // offset -- will be set by setBufferOffsets 6456 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6457 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6458 }; 6459 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6460 // We don't know the offset if vindex is non-zero, so clear it. 6461 if (IdxEn) 6462 Offset = 0; 6463 EVT VT = Op.getValueType(); 6464 6465 auto *M = cast<MemSDNode>(Op); 6466 M->getMemOperand()->setOffset(Offset); 6467 unsigned Opcode = 0; 6468 6469 switch (IntrID) { 6470 case Intrinsic::amdgcn_buffer_atomic_swap: 6471 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6472 break; 6473 case Intrinsic::amdgcn_buffer_atomic_add: 6474 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6475 break; 6476 case Intrinsic::amdgcn_buffer_atomic_sub: 6477 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6478 break; 6479 case Intrinsic::amdgcn_buffer_atomic_smin: 6480 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6481 break; 6482 case Intrinsic::amdgcn_buffer_atomic_umin: 6483 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6484 break; 6485 case Intrinsic::amdgcn_buffer_atomic_smax: 6486 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6487 break; 6488 case Intrinsic::amdgcn_buffer_atomic_umax: 6489 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6490 break; 6491 case Intrinsic::amdgcn_buffer_atomic_and: 6492 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6493 break; 6494 case Intrinsic::amdgcn_buffer_atomic_or: 6495 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6496 break; 6497 case Intrinsic::amdgcn_buffer_atomic_xor: 6498 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6499 break; 6500 default: 6501 llvm_unreachable("unhandled atomic opcode"); 6502 } 6503 6504 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6505 M->getMemOperand()); 6506 } 6507 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6508 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6509 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6510 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6511 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6512 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6513 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6514 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6515 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6516 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6517 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6518 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6519 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6520 SDValue Ops[] = { 6521 Op.getOperand(0), // Chain 6522 Op.getOperand(2), // vdata 6523 Op.getOperand(3), // rsrc 6524 DAG.getConstant(0, DL, MVT::i32), // vindex 6525 Offsets.first, // voffset 6526 Op.getOperand(5), // soffset 6527 Offsets.second, // offset 6528 Op.getOperand(6), // cachepolicy 6529 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6530 }; 6531 EVT VT = Op.getValueType(); 6532 6533 auto *M = cast<MemSDNode>(Op); 6534 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6535 unsigned Opcode = 0; 6536 6537 switch (IntrID) { 6538 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6539 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6540 break; 6541 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6542 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6543 break; 6544 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6545 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6546 break; 6547 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6548 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6549 break; 6550 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6551 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6552 break; 6553 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6554 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6555 break; 6556 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6557 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6558 break; 6559 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6560 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6561 break; 6562 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6563 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6564 break; 6565 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6566 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6567 break; 6568 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6569 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6570 break; 6571 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6572 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6573 break; 6574 default: 6575 llvm_unreachable("unhandled atomic opcode"); 6576 } 6577 6578 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6579 M->getMemOperand()); 6580 } 6581 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6582 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6583 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6584 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6585 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6586 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6587 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6588 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6589 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6590 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6591 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6592 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6593 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6594 SDValue Ops[] = { 6595 Op.getOperand(0), // Chain 6596 Op.getOperand(2), // vdata 6597 Op.getOperand(3), // rsrc 6598 Op.getOperand(4), // vindex 6599 Offsets.first, // voffset 6600 Op.getOperand(6), // soffset 6601 Offsets.second, // offset 6602 Op.getOperand(7), // cachepolicy 6603 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6604 }; 6605 EVT VT = Op.getValueType(); 6606 6607 auto *M = cast<MemSDNode>(Op); 6608 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6609 Ops[3])); 6610 unsigned Opcode = 0; 6611 6612 switch (IntrID) { 6613 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6614 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6615 break; 6616 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6617 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6618 break; 6619 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6620 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6621 break; 6622 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6623 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6624 break; 6625 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6626 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6627 break; 6628 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6629 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6630 break; 6631 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6632 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6633 break; 6634 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6635 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6636 break; 6637 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6638 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6639 break; 6640 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6641 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6642 break; 6643 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6644 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6645 break; 6646 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6647 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6648 break; 6649 default: 6650 llvm_unreachable("unhandled atomic opcode"); 6651 } 6652 6653 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6654 M->getMemOperand()); 6655 } 6656 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6657 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6658 unsigned IdxEn = 1; 6659 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6660 IdxEn = Idx->getZExtValue() != 0; 6661 SDValue Ops[] = { 6662 Op.getOperand(0), // Chain 6663 Op.getOperand(2), // src 6664 Op.getOperand(3), // cmp 6665 Op.getOperand(4), // rsrc 6666 Op.getOperand(5), // vindex 6667 SDValue(), // voffset -- will be set by setBufferOffsets 6668 SDValue(), // soffset -- will be set by setBufferOffsets 6669 SDValue(), // offset -- will be set by setBufferOffsets 6670 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6671 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6672 }; 6673 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6674 // We don't know the offset if vindex is non-zero, so clear it. 6675 if (IdxEn) 6676 Offset = 0; 6677 EVT VT = Op.getValueType(); 6678 auto *M = cast<MemSDNode>(Op); 6679 M->getMemOperand()->setOffset(Offset); 6680 6681 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6682 Op->getVTList(), Ops, VT, M->getMemOperand()); 6683 } 6684 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6685 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6686 SDValue Ops[] = { 6687 Op.getOperand(0), // Chain 6688 Op.getOperand(2), // src 6689 Op.getOperand(3), // cmp 6690 Op.getOperand(4), // rsrc 6691 DAG.getConstant(0, DL, MVT::i32), // vindex 6692 Offsets.first, // voffset 6693 Op.getOperand(6), // soffset 6694 Offsets.second, // offset 6695 Op.getOperand(7), // cachepolicy 6696 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6697 }; 6698 EVT VT = Op.getValueType(); 6699 auto *M = cast<MemSDNode>(Op); 6700 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6701 6702 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6703 Op->getVTList(), Ops, VT, M->getMemOperand()); 6704 } 6705 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6706 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6707 SDValue Ops[] = { 6708 Op.getOperand(0), // Chain 6709 Op.getOperand(2), // src 6710 Op.getOperand(3), // cmp 6711 Op.getOperand(4), // rsrc 6712 Op.getOperand(5), // vindex 6713 Offsets.first, // voffset 6714 Op.getOperand(7), // soffset 6715 Offsets.second, // offset 6716 Op.getOperand(8), // cachepolicy 6717 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6718 }; 6719 EVT VT = Op.getValueType(); 6720 auto *M = cast<MemSDNode>(Op); 6721 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6722 Ops[4])); 6723 6724 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6725 Op->getVTList(), Ops, VT, M->getMemOperand()); 6726 } 6727 6728 default: 6729 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6730 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6731 return lowerImage(Op, ImageDimIntr, DAG); 6732 6733 return SDValue(); 6734 } 6735 } 6736 6737 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6738 // dwordx4 if on SI. 6739 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6740 SDVTList VTList, 6741 ArrayRef<SDValue> Ops, EVT MemVT, 6742 MachineMemOperand *MMO, 6743 SelectionDAG &DAG) const { 6744 EVT VT = VTList.VTs[0]; 6745 EVT WidenedVT = VT; 6746 EVT WidenedMemVT = MemVT; 6747 if (!Subtarget->hasDwordx3LoadStores() && 6748 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6749 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6750 WidenedVT.getVectorElementType(), 4); 6751 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6752 WidenedMemVT.getVectorElementType(), 4); 6753 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6754 } 6755 6756 assert(VTList.NumVTs == 2); 6757 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6758 6759 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6760 WidenedMemVT, MMO); 6761 if (WidenedVT != VT) { 6762 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6763 DAG.getVectorIdxConstant(0, DL)); 6764 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6765 } 6766 return NewOp; 6767 } 6768 6769 SDValue SITargetLowering::handleD16VData(SDValue VData, 6770 SelectionDAG &DAG) const { 6771 EVT StoreVT = VData.getValueType(); 6772 6773 // No change for f16 and legal vector D16 types. 6774 if (!StoreVT.isVector()) 6775 return VData; 6776 6777 SDLoc DL(VData); 6778 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6779 6780 if (Subtarget->hasUnpackedD16VMem()) { 6781 // We need to unpack the packed data to store. 6782 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6783 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6784 6785 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6786 StoreVT.getVectorNumElements()); 6787 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6788 return DAG.UnrollVectorOp(ZExt.getNode()); 6789 } 6790 6791 assert(isTypeLegal(StoreVT)); 6792 return VData; 6793 } 6794 6795 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6796 SelectionDAG &DAG) const { 6797 SDLoc DL(Op); 6798 SDValue Chain = Op.getOperand(0); 6799 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6800 MachineFunction &MF = DAG.getMachineFunction(); 6801 6802 switch (IntrinsicID) { 6803 case Intrinsic::amdgcn_exp_compr: { 6804 SDValue Src0 = Op.getOperand(4); 6805 SDValue Src1 = Op.getOperand(5); 6806 // Hack around illegal type on SI by directly selecting it. 6807 if (isTypeLegal(Src0.getValueType())) 6808 return SDValue(); 6809 6810 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6811 SDValue Undef = DAG.getUNDEF(MVT::f32); 6812 const SDValue Ops[] = { 6813 Op.getOperand(2), // tgt 6814 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6815 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6816 Undef, // src2 6817 Undef, // src3 6818 Op.getOperand(7), // vm 6819 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6820 Op.getOperand(3), // en 6821 Op.getOperand(0) // Chain 6822 }; 6823 6824 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6825 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6826 } 6827 case Intrinsic::amdgcn_s_barrier: { 6828 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6829 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6830 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6831 if (WGSize <= ST.getWavefrontSize()) 6832 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6833 Op.getOperand(0)), 0); 6834 } 6835 return SDValue(); 6836 }; 6837 case Intrinsic::amdgcn_tbuffer_store: { 6838 SDValue VData = Op.getOperand(2); 6839 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6840 if (IsD16) 6841 VData = handleD16VData(VData, DAG); 6842 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6843 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6844 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6845 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6846 unsigned IdxEn = 1; 6847 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6848 IdxEn = Idx->getZExtValue() != 0; 6849 SDValue Ops[] = { 6850 Chain, 6851 VData, // vdata 6852 Op.getOperand(3), // rsrc 6853 Op.getOperand(4), // vindex 6854 Op.getOperand(5), // voffset 6855 Op.getOperand(6), // soffset 6856 Op.getOperand(7), // offset 6857 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6858 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6859 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6860 }; 6861 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6862 AMDGPUISD::TBUFFER_STORE_FORMAT; 6863 MemSDNode *M = cast<MemSDNode>(Op); 6864 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6865 M->getMemoryVT(), M->getMemOperand()); 6866 } 6867 6868 case Intrinsic::amdgcn_struct_tbuffer_store: { 6869 SDValue VData = Op.getOperand(2); 6870 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6871 if (IsD16) 6872 VData = handleD16VData(VData, DAG); 6873 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6874 SDValue Ops[] = { 6875 Chain, 6876 VData, // vdata 6877 Op.getOperand(3), // rsrc 6878 Op.getOperand(4), // vindex 6879 Offsets.first, // voffset 6880 Op.getOperand(6), // soffset 6881 Offsets.second, // offset 6882 Op.getOperand(7), // format 6883 Op.getOperand(8), // cachepolicy, swizzled buffer 6884 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6885 }; 6886 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6887 AMDGPUISD::TBUFFER_STORE_FORMAT; 6888 MemSDNode *M = cast<MemSDNode>(Op); 6889 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6890 M->getMemoryVT(), M->getMemOperand()); 6891 } 6892 6893 case Intrinsic::amdgcn_raw_tbuffer_store: { 6894 SDValue VData = Op.getOperand(2); 6895 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6896 if (IsD16) 6897 VData = handleD16VData(VData, DAG); 6898 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6899 SDValue Ops[] = { 6900 Chain, 6901 VData, // vdata 6902 Op.getOperand(3), // rsrc 6903 DAG.getConstant(0, DL, MVT::i32), // vindex 6904 Offsets.first, // voffset 6905 Op.getOperand(5), // soffset 6906 Offsets.second, // offset 6907 Op.getOperand(6), // format 6908 Op.getOperand(7), // cachepolicy, swizzled buffer 6909 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6910 }; 6911 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6912 AMDGPUISD::TBUFFER_STORE_FORMAT; 6913 MemSDNode *M = cast<MemSDNode>(Op); 6914 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6915 M->getMemoryVT(), M->getMemOperand()); 6916 } 6917 6918 case Intrinsic::amdgcn_buffer_store: 6919 case Intrinsic::amdgcn_buffer_store_format: { 6920 SDValue VData = Op.getOperand(2); 6921 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6922 if (IsD16) 6923 VData = handleD16VData(VData, DAG); 6924 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6925 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6926 unsigned IdxEn = 1; 6927 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6928 IdxEn = Idx->getZExtValue() != 0; 6929 SDValue Ops[] = { 6930 Chain, 6931 VData, 6932 Op.getOperand(3), // rsrc 6933 Op.getOperand(4), // vindex 6934 SDValue(), // voffset -- will be set by setBufferOffsets 6935 SDValue(), // soffset -- will be set by setBufferOffsets 6936 SDValue(), // offset -- will be set by setBufferOffsets 6937 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6938 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6939 }; 6940 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6941 // We don't know the offset if vindex is non-zero, so clear it. 6942 if (IdxEn) 6943 Offset = 0; 6944 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_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(Offset); 6949 6950 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6951 EVT VDataType = VData.getValueType().getScalarType(); 6952 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6953 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6954 6955 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6956 M->getMemoryVT(), M->getMemOperand()); 6957 } 6958 6959 case Intrinsic::amdgcn_raw_buffer_store: 6960 case Intrinsic::amdgcn_raw_buffer_store_format: { 6961 const bool IsFormat = 6962 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6963 6964 SDValue VData = Op.getOperand(2); 6965 EVT VDataVT = VData.getValueType(); 6966 EVT EltType = VDataVT.getScalarType(); 6967 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6968 if (IsD16) 6969 VData = handleD16VData(VData, DAG); 6970 6971 if (!isTypeLegal(VDataVT)) { 6972 VData = 6973 DAG.getNode(ISD::BITCAST, DL, 6974 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6975 } 6976 6977 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6978 SDValue Ops[] = { 6979 Chain, 6980 VData, 6981 Op.getOperand(3), // rsrc 6982 DAG.getConstant(0, DL, MVT::i32), // vindex 6983 Offsets.first, // voffset 6984 Op.getOperand(5), // soffset 6985 Offsets.second, // offset 6986 Op.getOperand(6), // cachepolicy, swizzled buffer 6987 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6988 }; 6989 unsigned Opc = 6990 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6991 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6992 MemSDNode *M = cast<MemSDNode>(Op); 6993 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6994 6995 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6996 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6997 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 6998 6999 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7000 M->getMemoryVT(), M->getMemOperand()); 7001 } 7002 7003 case Intrinsic::amdgcn_struct_buffer_store: 7004 case Intrinsic::amdgcn_struct_buffer_store_format: { 7005 const bool IsFormat = 7006 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7007 7008 SDValue VData = Op.getOperand(2); 7009 EVT VDataVT = VData.getValueType(); 7010 EVT EltType = VDataVT.getScalarType(); 7011 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7012 7013 if (IsD16) 7014 VData = handleD16VData(VData, DAG); 7015 7016 if (!isTypeLegal(VDataVT)) { 7017 VData = 7018 DAG.getNode(ISD::BITCAST, DL, 7019 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7020 } 7021 7022 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7023 SDValue Ops[] = { 7024 Chain, 7025 VData, 7026 Op.getOperand(3), // rsrc 7027 Op.getOperand(4), // vindex 7028 Offsets.first, // voffset 7029 Op.getOperand(6), // soffset 7030 Offsets.second, // offset 7031 Op.getOperand(7), // cachepolicy, swizzled buffer 7032 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7033 }; 7034 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7035 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7036 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7037 MemSDNode *M = cast<MemSDNode>(Op); 7038 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7039 Ops[3])); 7040 7041 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7042 EVT VDataType = VData.getValueType().getScalarType(); 7043 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7044 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7045 7046 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7047 M->getMemoryVT(), M->getMemOperand()); 7048 } 7049 7050 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7051 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7052 unsigned IdxEn = 1; 7053 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7054 IdxEn = Idx->getZExtValue() != 0; 7055 SDValue Ops[] = { 7056 Chain, 7057 Op.getOperand(2), // vdata 7058 Op.getOperand(3), // rsrc 7059 Op.getOperand(4), // vindex 7060 SDValue(), // voffset -- will be set by setBufferOffsets 7061 SDValue(), // soffset -- will be set by setBufferOffsets 7062 SDValue(), // offset -- will be set by setBufferOffsets 7063 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7064 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7065 }; 7066 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7067 // We don't know the offset if vindex is non-zero, so clear it. 7068 if (IdxEn) 7069 Offset = 0; 7070 EVT VT = Op.getOperand(2).getValueType(); 7071 7072 auto *M = cast<MemSDNode>(Op); 7073 M->getMemOperand()->setOffset(Offset); 7074 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7075 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7076 7077 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7078 M->getMemOperand()); 7079 } 7080 7081 case Intrinsic::amdgcn_global_atomic_fadd: { 7082 SDValue Ops[] = { 7083 Chain, 7084 Op.getOperand(2), // ptr 7085 Op.getOperand(3) // vdata 7086 }; 7087 EVT VT = Op.getOperand(3).getValueType(); 7088 7089 auto *M = cast<MemSDNode>(Op); 7090 if (VT.isVector()) { 7091 return DAG.getMemIntrinsicNode( 7092 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7093 M->getMemOperand()); 7094 } 7095 7096 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7097 DAG.getVTList(VT, MVT::Other), Ops, 7098 M->getMemOperand()).getValue(1); 7099 } 7100 case Intrinsic::amdgcn_end_cf: 7101 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7102 Op->getOperand(2), Chain), 0); 7103 7104 default: { 7105 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7106 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7107 return lowerImage(Op, ImageDimIntr, DAG); 7108 7109 return Op; 7110 } 7111 } 7112 } 7113 7114 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7115 // offset (the offset that is included in bounds checking and swizzling, to be 7116 // split between the instruction's voffset and immoffset fields) and soffset 7117 // (the offset that is excluded from bounds checking and swizzling, to go in 7118 // the instruction's soffset field). This function takes the first kind of 7119 // offset and figures out how to split it between voffset and immoffset. 7120 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7121 SDValue Offset, SelectionDAG &DAG) const { 7122 SDLoc DL(Offset); 7123 const unsigned MaxImm = 4095; 7124 SDValue N0 = Offset; 7125 ConstantSDNode *C1 = nullptr; 7126 7127 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7128 N0 = SDValue(); 7129 else if (DAG.isBaseWithConstantOffset(N0)) { 7130 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7131 N0 = N0.getOperand(0); 7132 } 7133 7134 if (C1) { 7135 unsigned ImmOffset = C1->getZExtValue(); 7136 // If the immediate value is too big for the immoffset field, put the value 7137 // and -4096 into the immoffset field so that the value that is copied/added 7138 // for the voffset field is a multiple of 4096, and it stands more chance 7139 // of being CSEd with the copy/add for another similar load/store. 7140 // However, do not do that rounding down to a multiple of 4096 if that is a 7141 // negative number, as it appears to be illegal to have a negative offset 7142 // in the vgpr, even if adding the immediate offset makes it positive. 7143 unsigned Overflow = ImmOffset & ~MaxImm; 7144 ImmOffset -= Overflow; 7145 if ((int32_t)Overflow < 0) { 7146 Overflow += ImmOffset; 7147 ImmOffset = 0; 7148 } 7149 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7150 if (Overflow) { 7151 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7152 if (!N0) 7153 N0 = OverflowVal; 7154 else { 7155 SDValue Ops[] = { N0, OverflowVal }; 7156 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7157 } 7158 } 7159 } 7160 if (!N0) 7161 N0 = DAG.getConstant(0, DL, MVT::i32); 7162 if (!C1) 7163 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7164 return {N0, SDValue(C1, 0)}; 7165 } 7166 7167 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7168 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7169 // pointed to by Offsets. 7170 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7171 SelectionDAG &DAG, SDValue *Offsets, 7172 unsigned Align) const { 7173 SDLoc DL(CombinedOffset); 7174 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7175 uint32_t Imm = C->getZExtValue(); 7176 uint32_t SOffset, ImmOffset; 7177 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7178 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7179 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7180 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7181 return SOffset + ImmOffset; 7182 } 7183 } 7184 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7185 SDValue N0 = CombinedOffset.getOperand(0); 7186 SDValue N1 = CombinedOffset.getOperand(1); 7187 uint32_t SOffset, ImmOffset; 7188 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7189 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7190 Subtarget, Align)) { 7191 Offsets[0] = N0; 7192 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7193 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7194 return 0; 7195 } 7196 } 7197 Offsets[0] = CombinedOffset; 7198 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7199 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7200 return 0; 7201 } 7202 7203 // Handle 8 bit and 16 bit buffer loads 7204 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7205 EVT LoadVT, SDLoc DL, 7206 ArrayRef<SDValue> Ops, 7207 MemSDNode *M) const { 7208 EVT IntVT = LoadVT.changeTypeToInteger(); 7209 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7210 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7211 7212 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7213 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7214 Ops, IntVT, 7215 M->getMemOperand()); 7216 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7217 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7218 7219 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7220 } 7221 7222 // Handle 8 bit and 16 bit buffer stores 7223 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7224 EVT VDataType, SDLoc DL, 7225 SDValue Ops[], 7226 MemSDNode *M) const { 7227 if (VDataType == MVT::f16) 7228 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7229 7230 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7231 Ops[1] = BufferStoreExt; 7232 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7233 AMDGPUISD::BUFFER_STORE_SHORT; 7234 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7235 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7236 M->getMemOperand()); 7237 } 7238 7239 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7240 ISD::LoadExtType ExtType, SDValue Op, 7241 const SDLoc &SL, EVT VT) { 7242 if (VT.bitsLT(Op.getValueType())) 7243 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7244 7245 switch (ExtType) { 7246 case ISD::SEXTLOAD: 7247 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7248 case ISD::ZEXTLOAD: 7249 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7250 case ISD::EXTLOAD: 7251 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7252 case ISD::NON_EXTLOAD: 7253 return Op; 7254 } 7255 7256 llvm_unreachable("invalid ext type"); 7257 } 7258 7259 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7260 SelectionDAG &DAG = DCI.DAG; 7261 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7262 return SDValue(); 7263 7264 // FIXME: Constant loads should all be marked invariant. 7265 unsigned AS = Ld->getAddressSpace(); 7266 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7267 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7268 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7269 return SDValue(); 7270 7271 // Don't do this early, since it may interfere with adjacent load merging for 7272 // illegal types. We can avoid losing alignment information for exotic types 7273 // pre-legalize. 7274 EVT MemVT = Ld->getMemoryVT(); 7275 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7276 MemVT.getSizeInBits() >= 32) 7277 return SDValue(); 7278 7279 SDLoc SL(Ld); 7280 7281 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7282 "unexpected vector extload"); 7283 7284 // TODO: Drop only high part of range. 7285 SDValue Ptr = Ld->getBasePtr(); 7286 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7287 MVT::i32, SL, Ld->getChain(), Ptr, 7288 Ld->getOffset(), 7289 Ld->getPointerInfo(), MVT::i32, 7290 Ld->getAlignment(), 7291 Ld->getMemOperand()->getFlags(), 7292 Ld->getAAInfo(), 7293 nullptr); // Drop ranges 7294 7295 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7296 if (MemVT.isFloatingPoint()) { 7297 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7298 "unexpected fp extload"); 7299 TruncVT = MemVT.changeTypeToInteger(); 7300 } 7301 7302 SDValue Cvt = NewLoad; 7303 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7304 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7305 DAG.getValueType(TruncVT)); 7306 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7307 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7308 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7309 } else { 7310 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7311 } 7312 7313 EVT VT = Ld->getValueType(0); 7314 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7315 7316 DCI.AddToWorklist(Cvt.getNode()); 7317 7318 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7319 // the appropriate extension from the 32-bit load. 7320 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7321 DCI.AddToWorklist(Cvt.getNode()); 7322 7323 // Handle conversion back to floating point if necessary. 7324 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7325 7326 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7327 } 7328 7329 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7330 SDLoc DL(Op); 7331 LoadSDNode *Load = cast<LoadSDNode>(Op); 7332 ISD::LoadExtType ExtType = Load->getExtensionType(); 7333 EVT MemVT = Load->getMemoryVT(); 7334 7335 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7336 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7337 return SDValue(); 7338 7339 // FIXME: Copied from PPC 7340 // First, load into 32 bits, then truncate to 1 bit. 7341 7342 SDValue Chain = Load->getChain(); 7343 SDValue BasePtr = Load->getBasePtr(); 7344 MachineMemOperand *MMO = Load->getMemOperand(); 7345 7346 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7347 7348 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7349 BasePtr, RealMemVT, MMO); 7350 7351 if (!MemVT.isVector()) { 7352 SDValue Ops[] = { 7353 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7354 NewLD.getValue(1) 7355 }; 7356 7357 return DAG.getMergeValues(Ops, DL); 7358 } 7359 7360 SmallVector<SDValue, 3> Elts; 7361 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7362 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7363 DAG.getConstant(I, DL, MVT::i32)); 7364 7365 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7366 } 7367 7368 SDValue Ops[] = { 7369 DAG.getBuildVector(MemVT, DL, Elts), 7370 NewLD.getValue(1) 7371 }; 7372 7373 return DAG.getMergeValues(Ops, DL); 7374 } 7375 7376 if (!MemVT.isVector()) 7377 return SDValue(); 7378 7379 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7380 "Custom lowering for non-i32 vectors hasn't been implemented."); 7381 7382 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7383 MemVT, *Load->getMemOperand())) { 7384 SDValue Ops[2]; 7385 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7386 return DAG.getMergeValues(Ops, DL); 7387 } 7388 7389 unsigned Alignment = Load->getAlignment(); 7390 unsigned AS = Load->getAddressSpace(); 7391 if (Subtarget->hasLDSMisalignedBug() && 7392 AS == AMDGPUAS::FLAT_ADDRESS && 7393 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7394 return SplitVectorLoad(Op, DAG); 7395 } 7396 7397 MachineFunction &MF = DAG.getMachineFunction(); 7398 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7399 // If there is a possibilty that flat instruction access scratch memory 7400 // then we need to use the same legalization rules we use for private. 7401 if (AS == AMDGPUAS::FLAT_ADDRESS && 7402 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7403 AS = MFI->hasFlatScratchInit() ? 7404 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7405 7406 unsigned NumElements = MemVT.getVectorNumElements(); 7407 7408 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7409 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7410 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7411 if (MemVT.isPow2VectorType()) 7412 return SDValue(); 7413 if (NumElements == 3) 7414 return WidenVectorLoad(Op, DAG); 7415 return SplitVectorLoad(Op, DAG); 7416 } 7417 // Non-uniform loads will be selected to MUBUF instructions, so they 7418 // have the same legalization requirements as global and private 7419 // loads. 7420 // 7421 } 7422 7423 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7424 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7425 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7426 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7427 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7428 Alignment >= 4 && NumElements < 32) { 7429 if (MemVT.isPow2VectorType()) 7430 return SDValue(); 7431 if (NumElements == 3) 7432 return WidenVectorLoad(Op, DAG); 7433 return SplitVectorLoad(Op, DAG); 7434 } 7435 // Non-uniform loads will be selected to MUBUF instructions, so they 7436 // have the same legalization requirements as global and private 7437 // loads. 7438 // 7439 } 7440 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7441 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7442 AS == AMDGPUAS::GLOBAL_ADDRESS || 7443 AS == AMDGPUAS::FLAT_ADDRESS) { 7444 if (NumElements > 4) 7445 return SplitVectorLoad(Op, DAG); 7446 // v3 loads not supported on SI. 7447 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7448 return WidenVectorLoad(Op, DAG); 7449 // v3 and v4 loads are supported for private and global memory. 7450 return SDValue(); 7451 } 7452 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7453 // Depending on the setting of the private_element_size field in the 7454 // resource descriptor, we can only make private accesses up to a certain 7455 // size. 7456 switch (Subtarget->getMaxPrivateElementSize()) { 7457 case 4: { 7458 SDValue Ops[2]; 7459 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7460 return DAG.getMergeValues(Ops, DL); 7461 } 7462 case 8: 7463 if (NumElements > 2) 7464 return SplitVectorLoad(Op, DAG); 7465 return SDValue(); 7466 case 16: 7467 // Same as global/flat 7468 if (NumElements > 4) 7469 return SplitVectorLoad(Op, DAG); 7470 // v3 loads not supported on SI. 7471 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7472 return WidenVectorLoad(Op, DAG); 7473 return SDValue(); 7474 default: 7475 llvm_unreachable("unsupported private_element_size"); 7476 } 7477 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7478 // Use ds_read_b128 if possible. 7479 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7480 MemVT.getStoreSize() == 16) 7481 return SDValue(); 7482 7483 if (NumElements > 2) 7484 return SplitVectorLoad(Op, DAG); 7485 7486 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7487 // address is negative, then the instruction is incorrectly treated as 7488 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7489 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7490 // load later in the SILoadStoreOptimizer. 7491 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7492 NumElements == 2 && MemVT.getStoreSize() == 8 && 7493 Load->getAlignment() < 8) { 7494 return SplitVectorLoad(Op, DAG); 7495 } 7496 } 7497 return SDValue(); 7498 } 7499 7500 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7501 EVT VT = Op.getValueType(); 7502 assert(VT.getSizeInBits() == 64); 7503 7504 SDLoc DL(Op); 7505 SDValue Cond = Op.getOperand(0); 7506 7507 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7508 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7509 7510 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7511 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7512 7513 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7514 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7515 7516 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7517 7518 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7519 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7520 7521 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7522 7523 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7524 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7525 } 7526 7527 // Catch division cases where we can use shortcuts with rcp and rsq 7528 // instructions. 7529 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7530 SelectionDAG &DAG) const { 7531 SDLoc SL(Op); 7532 SDValue LHS = Op.getOperand(0); 7533 SDValue RHS = Op.getOperand(1); 7534 EVT VT = Op.getValueType(); 7535 const SDNodeFlags Flags = Op->getFlags(); 7536 7537 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7538 Flags.hasApproximateFuncs(); 7539 7540 // Without !fpmath accuracy information, we can't do more because we don't 7541 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7542 if (!AllowInaccurateRcp) 7543 return SDValue(); 7544 7545 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7546 if (CLHS->isExactlyValue(1.0)) { 7547 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7548 // the CI documentation has a worst case error of 1 ulp. 7549 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7550 // use it as long as we aren't trying to use denormals. 7551 // 7552 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7553 7554 // 1.0 / sqrt(x) -> rsq(x) 7555 7556 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7557 // error seems really high at 2^29 ULP. 7558 if (RHS.getOpcode() == ISD::FSQRT) 7559 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7560 7561 // 1.0 / x -> rcp(x) 7562 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7563 } 7564 7565 // Same as for 1.0, but expand the sign out of the constant. 7566 if (CLHS->isExactlyValue(-1.0)) { 7567 // -1.0 / x -> rcp (fneg x) 7568 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7569 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7570 } 7571 } 7572 7573 // Turn into multiply by the reciprocal. 7574 // x / y -> x * (1.0 / y) 7575 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7576 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7577 } 7578 7579 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7580 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7581 if (GlueChain->getNumValues() <= 1) { 7582 return DAG.getNode(Opcode, SL, VT, A, B); 7583 } 7584 7585 assert(GlueChain->getNumValues() == 3); 7586 7587 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7588 switch (Opcode) { 7589 default: llvm_unreachable("no chain equivalent for opcode"); 7590 case ISD::FMUL: 7591 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7592 break; 7593 } 7594 7595 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7596 GlueChain.getValue(2)); 7597 } 7598 7599 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7600 EVT VT, SDValue A, SDValue B, SDValue C, 7601 SDValue GlueChain) { 7602 if (GlueChain->getNumValues() <= 1) { 7603 return DAG.getNode(Opcode, SL, VT, A, B, C); 7604 } 7605 7606 assert(GlueChain->getNumValues() == 3); 7607 7608 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7609 switch (Opcode) { 7610 default: llvm_unreachable("no chain equivalent for opcode"); 7611 case ISD::FMA: 7612 Opcode = AMDGPUISD::FMA_W_CHAIN; 7613 break; 7614 } 7615 7616 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7617 GlueChain.getValue(2)); 7618 } 7619 7620 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7621 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7622 return FastLowered; 7623 7624 SDLoc SL(Op); 7625 SDValue Src0 = Op.getOperand(0); 7626 SDValue Src1 = Op.getOperand(1); 7627 7628 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7629 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7630 7631 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7632 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7633 7634 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7635 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7636 7637 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7638 } 7639 7640 // Faster 2.5 ULP division that does not support denormals. 7641 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7642 SDLoc SL(Op); 7643 SDValue LHS = Op.getOperand(1); 7644 SDValue RHS = Op.getOperand(2); 7645 7646 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7647 7648 const APFloat K0Val(BitsToFloat(0x6f800000)); 7649 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7650 7651 const APFloat K1Val(BitsToFloat(0x2f800000)); 7652 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7653 7654 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7655 7656 EVT SetCCVT = 7657 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7658 7659 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7660 7661 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7662 7663 // TODO: Should this propagate fast-math-flags? 7664 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7665 7666 // rcp does not support denormals. 7667 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7668 7669 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7670 7671 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7672 } 7673 7674 // Returns immediate value for setting the F32 denorm mode when using the 7675 // S_DENORM_MODE instruction. 7676 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7677 const SDLoc &SL, const GCNSubtarget *ST) { 7678 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7679 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7680 ? FP_DENORM_FLUSH_NONE 7681 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7682 7683 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7684 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7685 } 7686 7687 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7688 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7689 return FastLowered; 7690 7691 SDLoc SL(Op); 7692 SDValue LHS = Op.getOperand(0); 7693 SDValue RHS = Op.getOperand(1); 7694 7695 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7696 7697 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7698 7699 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7700 RHS, RHS, LHS); 7701 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7702 LHS, RHS, LHS); 7703 7704 // Denominator is scaled to not be denormal, so using rcp is ok. 7705 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7706 DenominatorScaled); 7707 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7708 DenominatorScaled); 7709 7710 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7711 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7712 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7713 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7714 7715 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7716 7717 if (!HasFP32Denormals) { 7718 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7719 7720 SDValue EnableDenorm; 7721 if (Subtarget->hasDenormModeInst()) { 7722 const SDValue EnableDenormValue = 7723 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7724 7725 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7726 DAG.getEntryNode(), EnableDenormValue); 7727 } else { 7728 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7729 SL, MVT::i32); 7730 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7731 DAG.getEntryNode(), EnableDenormValue, 7732 BitField); 7733 } 7734 7735 SDValue Ops[3] = { 7736 NegDivScale0, 7737 EnableDenorm.getValue(0), 7738 EnableDenorm.getValue(1) 7739 }; 7740 7741 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7742 } 7743 7744 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7745 ApproxRcp, One, NegDivScale0); 7746 7747 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7748 ApproxRcp, Fma0); 7749 7750 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7751 Fma1, Fma1); 7752 7753 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7754 NumeratorScaled, Mul); 7755 7756 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7757 7758 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7759 NumeratorScaled, Fma3); 7760 7761 if (!HasFP32Denormals) { 7762 SDValue DisableDenorm; 7763 if (Subtarget->hasDenormModeInst()) { 7764 const SDValue DisableDenormValue = 7765 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7766 7767 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7768 Fma4.getValue(1), DisableDenormValue, 7769 Fma4.getValue(2)); 7770 } else { 7771 const SDValue DisableDenormValue = 7772 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7773 7774 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7775 Fma4.getValue(1), DisableDenormValue, 7776 BitField, Fma4.getValue(2)); 7777 } 7778 7779 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7780 DisableDenorm, DAG.getRoot()); 7781 DAG.setRoot(OutputChain); 7782 } 7783 7784 SDValue Scale = NumeratorScaled.getValue(1); 7785 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7786 Fma4, Fma1, Fma3, Scale); 7787 7788 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7789 } 7790 7791 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7792 if (DAG.getTarget().Options.UnsafeFPMath) 7793 return lowerFastUnsafeFDIV(Op, DAG); 7794 7795 SDLoc SL(Op); 7796 SDValue X = Op.getOperand(0); 7797 SDValue Y = Op.getOperand(1); 7798 7799 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7800 7801 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7802 7803 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7804 7805 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7806 7807 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7808 7809 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7810 7811 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7812 7813 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7814 7815 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7816 7817 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7818 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7819 7820 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7821 NegDivScale0, Mul, DivScale1); 7822 7823 SDValue Scale; 7824 7825 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7826 // Workaround a hardware bug on SI where the condition output from div_scale 7827 // is not usable. 7828 7829 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7830 7831 // Figure out if the scale to use for div_fmas. 7832 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7833 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7834 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7835 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7836 7837 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7838 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7839 7840 SDValue Scale0Hi 7841 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7842 SDValue Scale1Hi 7843 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7844 7845 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7846 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7847 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7848 } else { 7849 Scale = DivScale1.getValue(1); 7850 } 7851 7852 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7853 Fma4, Fma3, Mul, Scale); 7854 7855 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7856 } 7857 7858 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7859 EVT VT = Op.getValueType(); 7860 7861 if (VT == MVT::f32) 7862 return LowerFDIV32(Op, DAG); 7863 7864 if (VT == MVT::f64) 7865 return LowerFDIV64(Op, DAG); 7866 7867 if (VT == MVT::f16) 7868 return LowerFDIV16(Op, DAG); 7869 7870 llvm_unreachable("Unexpected type for fdiv"); 7871 } 7872 7873 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7874 SDLoc DL(Op); 7875 StoreSDNode *Store = cast<StoreSDNode>(Op); 7876 EVT VT = Store->getMemoryVT(); 7877 7878 if (VT == MVT::i1) { 7879 return DAG.getTruncStore(Store->getChain(), DL, 7880 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7881 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7882 } 7883 7884 assert(VT.isVector() && 7885 Store->getValue().getValueType().getScalarType() == MVT::i32); 7886 7887 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7888 VT, *Store->getMemOperand())) { 7889 return expandUnalignedStore(Store, DAG); 7890 } 7891 7892 unsigned AS = Store->getAddressSpace(); 7893 if (Subtarget->hasLDSMisalignedBug() && 7894 AS == AMDGPUAS::FLAT_ADDRESS && 7895 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7896 return SplitVectorStore(Op, DAG); 7897 } 7898 7899 MachineFunction &MF = DAG.getMachineFunction(); 7900 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7901 // If there is a possibilty that flat instruction access scratch memory 7902 // then we need to use the same legalization rules we use for private. 7903 if (AS == AMDGPUAS::FLAT_ADDRESS && 7904 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7905 AS = MFI->hasFlatScratchInit() ? 7906 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7907 7908 unsigned NumElements = VT.getVectorNumElements(); 7909 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7910 AS == AMDGPUAS::FLAT_ADDRESS) { 7911 if (NumElements > 4) 7912 return SplitVectorStore(Op, DAG); 7913 // v3 stores not supported on SI. 7914 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7915 return SplitVectorStore(Op, DAG); 7916 return SDValue(); 7917 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7918 switch (Subtarget->getMaxPrivateElementSize()) { 7919 case 4: 7920 return scalarizeVectorStore(Store, DAG); 7921 case 8: 7922 if (NumElements > 2) 7923 return SplitVectorStore(Op, DAG); 7924 return SDValue(); 7925 case 16: 7926 if (NumElements > 4 || NumElements == 3) 7927 return SplitVectorStore(Op, DAG); 7928 return SDValue(); 7929 default: 7930 llvm_unreachable("unsupported private_element_size"); 7931 } 7932 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7933 // Use ds_write_b128 if possible. 7934 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7935 VT.getStoreSize() == 16 && NumElements != 3) 7936 return SDValue(); 7937 7938 if (NumElements > 2) 7939 return SplitVectorStore(Op, DAG); 7940 7941 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7942 // address is negative, then the instruction is incorrectly treated as 7943 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7944 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7945 // store later in the SILoadStoreOptimizer. 7946 if (!Subtarget->hasUsableDSOffset() && 7947 NumElements == 2 && VT.getStoreSize() == 8 && 7948 Store->getAlignment() < 8) { 7949 return SplitVectorStore(Op, DAG); 7950 } 7951 7952 return SDValue(); 7953 } else { 7954 llvm_unreachable("unhandled address space"); 7955 } 7956 } 7957 7958 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7959 SDLoc DL(Op); 7960 EVT VT = Op.getValueType(); 7961 SDValue Arg = Op.getOperand(0); 7962 SDValue TrigVal; 7963 7964 // TODO: Should this propagate fast-math-flags? 7965 7966 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7967 7968 if (Subtarget->hasTrigReducedRange()) { 7969 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7970 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7971 } else { 7972 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7973 } 7974 7975 switch (Op.getOpcode()) { 7976 case ISD::FCOS: 7977 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7978 case ISD::FSIN: 7979 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7980 default: 7981 llvm_unreachable("Wrong trig opcode"); 7982 } 7983 } 7984 7985 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7986 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7987 assert(AtomicNode->isCompareAndSwap()); 7988 unsigned AS = AtomicNode->getAddressSpace(); 7989 7990 // No custom lowering required for local address space 7991 if (!isFlatGlobalAddrSpace(AS)) 7992 return Op; 7993 7994 // Non-local address space requires custom lowering for atomic compare 7995 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7996 SDLoc DL(Op); 7997 SDValue ChainIn = Op.getOperand(0); 7998 SDValue Addr = Op.getOperand(1); 7999 SDValue Old = Op.getOperand(2); 8000 SDValue New = Op.getOperand(3); 8001 EVT VT = Op.getValueType(); 8002 MVT SimpleVT = VT.getSimpleVT(); 8003 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8004 8005 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8006 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8007 8008 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8009 Ops, VT, AtomicNode->getMemOperand()); 8010 } 8011 8012 //===----------------------------------------------------------------------===// 8013 // Custom DAG optimizations 8014 //===----------------------------------------------------------------------===// 8015 8016 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8017 DAGCombinerInfo &DCI) const { 8018 EVT VT = N->getValueType(0); 8019 EVT ScalarVT = VT.getScalarType(); 8020 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8021 return SDValue(); 8022 8023 SelectionDAG &DAG = DCI.DAG; 8024 SDLoc DL(N); 8025 8026 SDValue Src = N->getOperand(0); 8027 EVT SrcVT = Src.getValueType(); 8028 8029 // TODO: We could try to match extracting the higher bytes, which would be 8030 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8031 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8032 // about in practice. 8033 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8034 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8035 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8036 DCI.AddToWorklist(Cvt.getNode()); 8037 8038 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8039 if (ScalarVT != MVT::f32) { 8040 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8041 DAG.getTargetConstant(0, DL, MVT::i32)); 8042 } 8043 return Cvt; 8044 } 8045 } 8046 8047 return SDValue(); 8048 } 8049 8050 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8051 8052 // This is a variant of 8053 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8054 // 8055 // The normal DAG combiner will do this, but only if the add has one use since 8056 // that would increase the number of instructions. 8057 // 8058 // This prevents us from seeing a constant offset that can be folded into a 8059 // memory instruction's addressing mode. If we know the resulting add offset of 8060 // a pointer can be folded into an addressing offset, we can replace the pointer 8061 // operand with the add of new constant offset. This eliminates one of the uses, 8062 // and may allow the remaining use to also be simplified. 8063 // 8064 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8065 unsigned AddrSpace, 8066 EVT MemVT, 8067 DAGCombinerInfo &DCI) const { 8068 SDValue N0 = N->getOperand(0); 8069 SDValue N1 = N->getOperand(1); 8070 8071 // We only do this to handle cases where it's profitable when there are 8072 // multiple uses of the add, so defer to the standard combine. 8073 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8074 N0->hasOneUse()) 8075 return SDValue(); 8076 8077 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8078 if (!CN1) 8079 return SDValue(); 8080 8081 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8082 if (!CAdd) 8083 return SDValue(); 8084 8085 // If the resulting offset is too large, we can't fold it into the addressing 8086 // mode offset. 8087 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8088 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8089 8090 AddrMode AM; 8091 AM.HasBaseReg = true; 8092 AM.BaseOffs = Offset.getSExtValue(); 8093 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8094 return SDValue(); 8095 8096 SelectionDAG &DAG = DCI.DAG; 8097 SDLoc SL(N); 8098 EVT VT = N->getValueType(0); 8099 8100 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8101 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8102 8103 SDNodeFlags Flags; 8104 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8105 (N0.getOpcode() == ISD::OR || 8106 N0->getFlags().hasNoUnsignedWrap())); 8107 8108 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8109 } 8110 8111 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8112 DAGCombinerInfo &DCI) const { 8113 SDValue Ptr = N->getBasePtr(); 8114 SelectionDAG &DAG = DCI.DAG; 8115 SDLoc SL(N); 8116 8117 // TODO: We could also do this for multiplies. 8118 if (Ptr.getOpcode() == ISD::SHL) { 8119 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8120 N->getMemoryVT(), DCI); 8121 if (NewPtr) { 8122 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8123 8124 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8125 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8126 } 8127 } 8128 8129 return SDValue(); 8130 } 8131 8132 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8133 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8134 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8135 (Opc == ISD::XOR && Val == 0); 8136 } 8137 8138 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8139 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8140 // integer combine opportunities since most 64-bit operations are decomposed 8141 // this way. TODO: We won't want this for SALU especially if it is an inline 8142 // immediate. 8143 SDValue SITargetLowering::splitBinaryBitConstantOp( 8144 DAGCombinerInfo &DCI, 8145 const SDLoc &SL, 8146 unsigned Opc, SDValue LHS, 8147 const ConstantSDNode *CRHS) const { 8148 uint64_t Val = CRHS->getZExtValue(); 8149 uint32_t ValLo = Lo_32(Val); 8150 uint32_t ValHi = Hi_32(Val); 8151 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8152 8153 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8154 bitOpWithConstantIsReducible(Opc, ValHi)) || 8155 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8156 // If we need to materialize a 64-bit immediate, it will be split up later 8157 // anyway. Avoid creating the harder to understand 64-bit immediate 8158 // materialization. 8159 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8160 } 8161 8162 return SDValue(); 8163 } 8164 8165 // Returns true if argument is a boolean value which is not serialized into 8166 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8167 static bool isBoolSGPR(SDValue V) { 8168 if (V.getValueType() != MVT::i1) 8169 return false; 8170 switch (V.getOpcode()) { 8171 default: break; 8172 case ISD::SETCC: 8173 case ISD::AND: 8174 case ISD::OR: 8175 case ISD::XOR: 8176 case AMDGPUISD::FP_CLASS: 8177 return true; 8178 } 8179 return false; 8180 } 8181 8182 // If a constant has all zeroes or all ones within each byte return it. 8183 // Otherwise return 0. 8184 static uint32_t getConstantPermuteMask(uint32_t C) { 8185 // 0xff for any zero byte in the mask 8186 uint32_t ZeroByteMask = 0; 8187 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8188 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8189 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8190 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8191 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8192 if ((NonZeroByteMask & C) != NonZeroByteMask) 8193 return 0; // Partial bytes selected. 8194 return C; 8195 } 8196 8197 // Check if a node selects whole bytes from its operand 0 starting at a byte 8198 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8199 // or -1 if not succeeded. 8200 // Note byte select encoding: 8201 // value 0-3 selects corresponding source byte; 8202 // value 0xc selects zero; 8203 // value 0xff selects 0xff. 8204 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8205 assert(V.getValueSizeInBits() == 32); 8206 8207 if (V.getNumOperands() != 2) 8208 return ~0; 8209 8210 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8211 if (!N1) 8212 return ~0; 8213 8214 uint32_t C = N1->getZExtValue(); 8215 8216 switch (V.getOpcode()) { 8217 default: 8218 break; 8219 case ISD::AND: 8220 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8221 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8222 } 8223 break; 8224 8225 case ISD::OR: 8226 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8227 return (0x03020100 & ~ConstMask) | ConstMask; 8228 } 8229 break; 8230 8231 case ISD::SHL: 8232 if (C % 8) 8233 return ~0; 8234 8235 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8236 8237 case ISD::SRL: 8238 if (C % 8) 8239 return ~0; 8240 8241 return uint32_t(0x0c0c0c0c03020100ull >> C); 8242 } 8243 8244 return ~0; 8245 } 8246 8247 SDValue SITargetLowering::performAndCombine(SDNode *N, 8248 DAGCombinerInfo &DCI) const { 8249 if (DCI.isBeforeLegalize()) 8250 return SDValue(); 8251 8252 SelectionDAG &DAG = DCI.DAG; 8253 EVT VT = N->getValueType(0); 8254 SDValue LHS = N->getOperand(0); 8255 SDValue RHS = N->getOperand(1); 8256 8257 8258 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8259 if (VT == MVT::i64 && CRHS) { 8260 if (SDValue Split 8261 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8262 return Split; 8263 } 8264 8265 if (CRHS && VT == MVT::i32) { 8266 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8267 // nb = number of trailing zeroes in mask 8268 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8269 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8270 uint64_t Mask = CRHS->getZExtValue(); 8271 unsigned Bits = countPopulation(Mask); 8272 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8273 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8274 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8275 unsigned Shift = CShift->getZExtValue(); 8276 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8277 unsigned Offset = NB + Shift; 8278 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8279 SDLoc SL(N); 8280 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8281 LHS->getOperand(0), 8282 DAG.getConstant(Offset, SL, MVT::i32), 8283 DAG.getConstant(Bits, SL, MVT::i32)); 8284 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8285 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8286 DAG.getValueType(NarrowVT)); 8287 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8288 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8289 return Shl; 8290 } 8291 } 8292 } 8293 8294 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8295 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8296 isa<ConstantSDNode>(LHS.getOperand(2))) { 8297 uint32_t Sel = getConstantPermuteMask(Mask); 8298 if (!Sel) 8299 return SDValue(); 8300 8301 // Select 0xc for all zero bytes 8302 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8303 SDLoc DL(N); 8304 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8305 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8306 } 8307 } 8308 8309 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8310 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8311 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8312 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8313 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8314 8315 SDValue X = LHS.getOperand(0); 8316 SDValue Y = RHS.getOperand(0); 8317 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8318 return SDValue(); 8319 8320 if (LCC == ISD::SETO) { 8321 if (X != LHS.getOperand(1)) 8322 return SDValue(); 8323 8324 if (RCC == ISD::SETUNE) { 8325 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8326 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8327 return SDValue(); 8328 8329 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8330 SIInstrFlags::N_SUBNORMAL | 8331 SIInstrFlags::N_ZERO | 8332 SIInstrFlags::P_ZERO | 8333 SIInstrFlags::P_SUBNORMAL | 8334 SIInstrFlags::P_NORMAL; 8335 8336 static_assert(((~(SIInstrFlags::S_NAN | 8337 SIInstrFlags::Q_NAN | 8338 SIInstrFlags::N_INFINITY | 8339 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8340 "mask not equal"); 8341 8342 SDLoc DL(N); 8343 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8344 X, DAG.getConstant(Mask, DL, MVT::i32)); 8345 } 8346 } 8347 } 8348 8349 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8350 std::swap(LHS, RHS); 8351 8352 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8353 RHS.hasOneUse()) { 8354 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8355 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8356 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8357 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8358 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8359 (RHS.getOperand(0) == LHS.getOperand(0) && 8360 LHS.getOperand(0) == LHS.getOperand(1))) { 8361 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8362 unsigned NewMask = LCC == ISD::SETO ? 8363 Mask->getZExtValue() & ~OrdMask : 8364 Mask->getZExtValue() & OrdMask; 8365 8366 SDLoc DL(N); 8367 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8368 DAG.getConstant(NewMask, DL, MVT::i32)); 8369 } 8370 } 8371 8372 if (VT == MVT::i32 && 8373 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8374 // and x, (sext cc from i1) => select cc, x, 0 8375 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8376 std::swap(LHS, RHS); 8377 if (isBoolSGPR(RHS.getOperand(0))) 8378 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8379 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8380 } 8381 8382 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8383 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8384 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8385 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8386 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8387 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8388 if (LHSMask != ~0u && RHSMask != ~0u) { 8389 // Canonicalize the expression in an attempt to have fewer unique masks 8390 // and therefore fewer registers used to hold the masks. 8391 if (LHSMask > RHSMask) { 8392 std::swap(LHSMask, RHSMask); 8393 std::swap(LHS, RHS); 8394 } 8395 8396 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8397 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8398 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8399 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8400 8401 // Check of we need to combine values from two sources within a byte. 8402 if (!(LHSUsedLanes & RHSUsedLanes) && 8403 // If we select high and lower word keep it for SDWA. 8404 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8405 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8406 // Each byte in each mask is either selector mask 0-3, or has higher 8407 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8408 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8409 // mask which is not 0xff wins. By anding both masks we have a correct 8410 // result except that 0x0c shall be corrected to give 0x0c only. 8411 uint32_t Mask = LHSMask & RHSMask; 8412 for (unsigned I = 0; I < 32; I += 8) { 8413 uint32_t ByteSel = 0xff << I; 8414 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8415 Mask &= (0x0c << I) & 0xffffffff; 8416 } 8417 8418 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8419 // or 0x0c. 8420 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8421 SDLoc DL(N); 8422 8423 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8424 LHS.getOperand(0), RHS.getOperand(0), 8425 DAG.getConstant(Sel, DL, MVT::i32)); 8426 } 8427 } 8428 } 8429 8430 return SDValue(); 8431 } 8432 8433 SDValue SITargetLowering::performOrCombine(SDNode *N, 8434 DAGCombinerInfo &DCI) const { 8435 SelectionDAG &DAG = DCI.DAG; 8436 SDValue LHS = N->getOperand(0); 8437 SDValue RHS = N->getOperand(1); 8438 8439 EVT VT = N->getValueType(0); 8440 if (VT == MVT::i1) { 8441 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8442 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8443 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8444 SDValue Src = LHS.getOperand(0); 8445 if (Src != RHS.getOperand(0)) 8446 return SDValue(); 8447 8448 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8449 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8450 if (!CLHS || !CRHS) 8451 return SDValue(); 8452 8453 // Only 10 bits are used. 8454 static const uint32_t MaxMask = 0x3ff; 8455 8456 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8457 SDLoc DL(N); 8458 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8459 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8460 } 8461 8462 return SDValue(); 8463 } 8464 8465 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8466 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8467 LHS.getOpcode() == AMDGPUISD::PERM && 8468 isa<ConstantSDNode>(LHS.getOperand(2))) { 8469 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8470 if (!Sel) 8471 return SDValue(); 8472 8473 Sel |= LHS.getConstantOperandVal(2); 8474 SDLoc DL(N); 8475 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8476 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8477 } 8478 8479 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8480 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8481 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8482 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8483 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8484 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8485 if (LHSMask != ~0u && RHSMask != ~0u) { 8486 // Canonicalize the expression in an attempt to have fewer unique masks 8487 // and therefore fewer registers used to hold the masks. 8488 if (LHSMask > RHSMask) { 8489 std::swap(LHSMask, RHSMask); 8490 std::swap(LHS, RHS); 8491 } 8492 8493 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8494 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8495 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8496 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8497 8498 // Check of we need to combine values from two sources within a byte. 8499 if (!(LHSUsedLanes & RHSUsedLanes) && 8500 // If we select high and lower word keep it for SDWA. 8501 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8502 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8503 // Kill zero bytes selected by other mask. Zero value is 0xc. 8504 LHSMask &= ~RHSUsedLanes; 8505 RHSMask &= ~LHSUsedLanes; 8506 // Add 4 to each active LHS lane 8507 LHSMask |= LHSUsedLanes & 0x04040404; 8508 // Combine masks 8509 uint32_t Sel = LHSMask | RHSMask; 8510 SDLoc DL(N); 8511 8512 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8513 LHS.getOperand(0), RHS.getOperand(0), 8514 DAG.getConstant(Sel, DL, MVT::i32)); 8515 } 8516 } 8517 } 8518 8519 if (VT != MVT::i64) 8520 return SDValue(); 8521 8522 // TODO: This could be a generic combine with a predicate for extracting the 8523 // high half of an integer being free. 8524 8525 // (or i64:x, (zero_extend i32:y)) -> 8526 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8527 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8528 RHS.getOpcode() != ISD::ZERO_EXTEND) 8529 std::swap(LHS, RHS); 8530 8531 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8532 SDValue ExtSrc = RHS.getOperand(0); 8533 EVT SrcVT = ExtSrc.getValueType(); 8534 if (SrcVT == MVT::i32) { 8535 SDLoc SL(N); 8536 SDValue LowLHS, HiBits; 8537 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8538 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8539 8540 DCI.AddToWorklist(LowOr.getNode()); 8541 DCI.AddToWorklist(HiBits.getNode()); 8542 8543 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8544 LowOr, HiBits); 8545 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8546 } 8547 } 8548 8549 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8550 if (CRHS) { 8551 if (SDValue Split 8552 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8553 return Split; 8554 } 8555 8556 return SDValue(); 8557 } 8558 8559 SDValue SITargetLowering::performXorCombine(SDNode *N, 8560 DAGCombinerInfo &DCI) const { 8561 EVT VT = N->getValueType(0); 8562 if (VT != MVT::i64) 8563 return SDValue(); 8564 8565 SDValue LHS = N->getOperand(0); 8566 SDValue RHS = N->getOperand(1); 8567 8568 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8569 if (CRHS) { 8570 if (SDValue Split 8571 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8572 return Split; 8573 } 8574 8575 return SDValue(); 8576 } 8577 8578 // Instructions that will be lowered with a final instruction that zeros the 8579 // high result bits. 8580 // XXX - probably only need to list legal operations. 8581 static bool fp16SrcZerosHighBits(unsigned Opc) { 8582 switch (Opc) { 8583 case ISD::FADD: 8584 case ISD::FSUB: 8585 case ISD::FMUL: 8586 case ISD::FDIV: 8587 case ISD::FREM: 8588 case ISD::FMA: 8589 case ISD::FMAD: 8590 case ISD::FCANONICALIZE: 8591 case ISD::FP_ROUND: 8592 case ISD::UINT_TO_FP: 8593 case ISD::SINT_TO_FP: 8594 case ISD::FABS: 8595 // Fabs is lowered to a bit operation, but it's an and which will clear the 8596 // high bits anyway. 8597 case ISD::FSQRT: 8598 case ISD::FSIN: 8599 case ISD::FCOS: 8600 case ISD::FPOWI: 8601 case ISD::FPOW: 8602 case ISD::FLOG: 8603 case ISD::FLOG2: 8604 case ISD::FLOG10: 8605 case ISD::FEXP: 8606 case ISD::FEXP2: 8607 case ISD::FCEIL: 8608 case ISD::FTRUNC: 8609 case ISD::FRINT: 8610 case ISD::FNEARBYINT: 8611 case ISD::FROUND: 8612 case ISD::FFLOOR: 8613 case ISD::FMINNUM: 8614 case ISD::FMAXNUM: 8615 case AMDGPUISD::FRACT: 8616 case AMDGPUISD::CLAMP: 8617 case AMDGPUISD::COS_HW: 8618 case AMDGPUISD::SIN_HW: 8619 case AMDGPUISD::FMIN3: 8620 case AMDGPUISD::FMAX3: 8621 case AMDGPUISD::FMED3: 8622 case AMDGPUISD::FMAD_FTZ: 8623 case AMDGPUISD::RCP: 8624 case AMDGPUISD::RSQ: 8625 case AMDGPUISD::RCP_IFLAG: 8626 case AMDGPUISD::LDEXP: 8627 return true; 8628 default: 8629 // fcopysign, select and others may be lowered to 32-bit bit operations 8630 // which don't zero the high bits. 8631 return false; 8632 } 8633 } 8634 8635 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8636 DAGCombinerInfo &DCI) const { 8637 if (!Subtarget->has16BitInsts() || 8638 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8639 return SDValue(); 8640 8641 EVT VT = N->getValueType(0); 8642 if (VT != MVT::i32) 8643 return SDValue(); 8644 8645 SDValue Src = N->getOperand(0); 8646 if (Src.getValueType() != MVT::i16) 8647 return SDValue(); 8648 8649 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8650 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8651 if (Src.getOpcode() == ISD::BITCAST) { 8652 SDValue BCSrc = Src.getOperand(0); 8653 if (BCSrc.getValueType() == MVT::f16 && 8654 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8655 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8656 } 8657 8658 return SDValue(); 8659 } 8660 8661 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8662 DAGCombinerInfo &DCI) 8663 const { 8664 SDValue Src = N->getOperand(0); 8665 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8666 8667 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8668 VTSign->getVT() == MVT::i8) || 8669 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8670 VTSign->getVT() == MVT::i16)) && 8671 Src.hasOneUse()) { 8672 auto *M = cast<MemSDNode>(Src); 8673 SDValue Ops[] = { 8674 Src.getOperand(0), // Chain 8675 Src.getOperand(1), // rsrc 8676 Src.getOperand(2), // vindex 8677 Src.getOperand(3), // voffset 8678 Src.getOperand(4), // soffset 8679 Src.getOperand(5), // offset 8680 Src.getOperand(6), 8681 Src.getOperand(7) 8682 }; 8683 // replace with BUFFER_LOAD_BYTE/SHORT 8684 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8685 Src.getOperand(0).getValueType()); 8686 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8687 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8688 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8689 ResList, 8690 Ops, M->getMemoryVT(), 8691 M->getMemOperand()); 8692 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8693 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8694 } 8695 return SDValue(); 8696 } 8697 8698 SDValue SITargetLowering::performClassCombine(SDNode *N, 8699 DAGCombinerInfo &DCI) const { 8700 SelectionDAG &DAG = DCI.DAG; 8701 SDValue Mask = N->getOperand(1); 8702 8703 // fp_class x, 0 -> false 8704 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8705 if (CMask->isNullValue()) 8706 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8707 } 8708 8709 if (N->getOperand(0).isUndef()) 8710 return DAG.getUNDEF(MVT::i1); 8711 8712 return SDValue(); 8713 } 8714 8715 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8716 DAGCombinerInfo &DCI) const { 8717 EVT VT = N->getValueType(0); 8718 SDValue N0 = N->getOperand(0); 8719 8720 if (N0.isUndef()) 8721 return N0; 8722 8723 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8724 N0.getOpcode() == ISD::SINT_TO_FP)) { 8725 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8726 N->getFlags()); 8727 } 8728 8729 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8730 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8731 N0.getOperand(0), N->getFlags()); 8732 } 8733 8734 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8735 } 8736 8737 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8738 unsigned MaxDepth) const { 8739 unsigned Opcode = Op.getOpcode(); 8740 if (Opcode == ISD::FCANONICALIZE) 8741 return true; 8742 8743 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8744 auto F = CFP->getValueAPF(); 8745 if (F.isNaN() && F.isSignaling()) 8746 return false; 8747 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8748 } 8749 8750 // If source is a result of another standard FP operation it is already in 8751 // canonical form. 8752 if (MaxDepth == 0) 8753 return false; 8754 8755 switch (Opcode) { 8756 // These will flush denorms if required. 8757 case ISD::FADD: 8758 case ISD::FSUB: 8759 case ISD::FMUL: 8760 case ISD::FCEIL: 8761 case ISD::FFLOOR: 8762 case ISD::FMA: 8763 case ISD::FMAD: 8764 case ISD::FSQRT: 8765 case ISD::FDIV: 8766 case ISD::FREM: 8767 case ISD::FP_ROUND: 8768 case ISD::FP_EXTEND: 8769 case AMDGPUISD::FMUL_LEGACY: 8770 case AMDGPUISD::FMAD_FTZ: 8771 case AMDGPUISD::RCP: 8772 case AMDGPUISD::RSQ: 8773 case AMDGPUISD::RSQ_CLAMP: 8774 case AMDGPUISD::RCP_LEGACY: 8775 case AMDGPUISD::RSQ_LEGACY: 8776 case AMDGPUISD::RCP_IFLAG: 8777 case AMDGPUISD::TRIG_PREOP: 8778 case AMDGPUISD::DIV_SCALE: 8779 case AMDGPUISD::DIV_FMAS: 8780 case AMDGPUISD::DIV_FIXUP: 8781 case AMDGPUISD::FRACT: 8782 case AMDGPUISD::LDEXP: 8783 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8784 case AMDGPUISD::CVT_F32_UBYTE0: 8785 case AMDGPUISD::CVT_F32_UBYTE1: 8786 case AMDGPUISD::CVT_F32_UBYTE2: 8787 case AMDGPUISD::CVT_F32_UBYTE3: 8788 return true; 8789 8790 // It can/will be lowered or combined as a bit operation. 8791 // Need to check their input recursively to handle. 8792 case ISD::FNEG: 8793 case ISD::FABS: 8794 case ISD::FCOPYSIGN: 8795 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8796 8797 case ISD::FSIN: 8798 case ISD::FCOS: 8799 case ISD::FSINCOS: 8800 return Op.getValueType().getScalarType() != MVT::f16; 8801 8802 case ISD::FMINNUM: 8803 case ISD::FMAXNUM: 8804 case ISD::FMINNUM_IEEE: 8805 case ISD::FMAXNUM_IEEE: 8806 case AMDGPUISD::CLAMP: 8807 case AMDGPUISD::FMED3: 8808 case AMDGPUISD::FMAX3: 8809 case AMDGPUISD::FMIN3: { 8810 // FIXME: Shouldn't treat the generic operations different based these. 8811 // However, we aren't really required to flush the result from 8812 // minnum/maxnum.. 8813 8814 // snans will be quieted, so we only need to worry about denormals. 8815 if (Subtarget->supportsMinMaxDenormModes() || 8816 denormalsEnabledForType(DAG, Op.getValueType())) 8817 return true; 8818 8819 // Flushing may be required. 8820 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8821 // targets need to check their input recursively. 8822 8823 // FIXME: Does this apply with clamp? It's implemented with max. 8824 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8825 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8826 return false; 8827 } 8828 8829 return true; 8830 } 8831 case ISD::SELECT: { 8832 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8833 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8834 } 8835 case ISD::BUILD_VECTOR: { 8836 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8837 SDValue SrcOp = Op.getOperand(i); 8838 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8839 return false; 8840 } 8841 8842 return true; 8843 } 8844 case ISD::EXTRACT_VECTOR_ELT: 8845 case ISD::EXTRACT_SUBVECTOR: { 8846 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8847 } 8848 case ISD::INSERT_VECTOR_ELT: { 8849 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8850 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8851 } 8852 case ISD::UNDEF: 8853 // Could be anything. 8854 return false; 8855 8856 case ISD::BITCAST: { 8857 // Hack round the mess we make when legalizing extract_vector_elt 8858 SDValue Src = Op.getOperand(0); 8859 if (Src.getValueType() == MVT::i16 && 8860 Src.getOpcode() == ISD::TRUNCATE) { 8861 SDValue TruncSrc = Src.getOperand(0); 8862 if (TruncSrc.getValueType() == MVT::i32 && 8863 TruncSrc.getOpcode() == ISD::BITCAST && 8864 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8865 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8866 } 8867 } 8868 8869 return false; 8870 } 8871 case ISD::INTRINSIC_WO_CHAIN: { 8872 unsigned IntrinsicID 8873 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8874 // TODO: Handle more intrinsics 8875 switch (IntrinsicID) { 8876 case Intrinsic::amdgcn_cvt_pkrtz: 8877 case Intrinsic::amdgcn_cubeid: 8878 case Intrinsic::amdgcn_frexp_mant: 8879 case Intrinsic::amdgcn_fdot2: 8880 return true; 8881 default: 8882 break; 8883 } 8884 8885 LLVM_FALLTHROUGH; 8886 } 8887 default: 8888 return denormalsEnabledForType(DAG, Op.getValueType()) && 8889 DAG.isKnownNeverSNaN(Op); 8890 } 8891 8892 llvm_unreachable("invalid operation"); 8893 } 8894 8895 // Constant fold canonicalize. 8896 SDValue SITargetLowering::getCanonicalConstantFP( 8897 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8898 // Flush denormals to 0 if not enabled. 8899 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8900 return DAG.getConstantFP(0.0, SL, VT); 8901 8902 if (C.isNaN()) { 8903 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8904 if (C.isSignaling()) { 8905 // Quiet a signaling NaN. 8906 // FIXME: Is this supposed to preserve payload bits? 8907 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8908 } 8909 8910 // Make sure it is the canonical NaN bitpattern. 8911 // 8912 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8913 // immediate? 8914 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8915 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8916 } 8917 8918 // Already canonical. 8919 return DAG.getConstantFP(C, SL, VT); 8920 } 8921 8922 static bool vectorEltWillFoldAway(SDValue Op) { 8923 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8924 } 8925 8926 SDValue SITargetLowering::performFCanonicalizeCombine( 8927 SDNode *N, 8928 DAGCombinerInfo &DCI) const { 8929 SelectionDAG &DAG = DCI.DAG; 8930 SDValue N0 = N->getOperand(0); 8931 EVT VT = N->getValueType(0); 8932 8933 // fcanonicalize undef -> qnan 8934 if (N0.isUndef()) { 8935 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8936 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8937 } 8938 8939 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8940 EVT VT = N->getValueType(0); 8941 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8942 } 8943 8944 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8945 // (fcanonicalize k) 8946 // 8947 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8948 8949 // TODO: This could be better with wider vectors that will be split to v2f16, 8950 // and to consider uses since there aren't that many packed operations. 8951 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8952 isTypeLegal(MVT::v2f16)) { 8953 SDLoc SL(N); 8954 SDValue NewElts[2]; 8955 SDValue Lo = N0.getOperand(0); 8956 SDValue Hi = N0.getOperand(1); 8957 EVT EltVT = Lo.getValueType(); 8958 8959 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8960 for (unsigned I = 0; I != 2; ++I) { 8961 SDValue Op = N0.getOperand(I); 8962 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8963 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8964 CFP->getValueAPF()); 8965 } else if (Op.isUndef()) { 8966 // Handled below based on what the other operand is. 8967 NewElts[I] = Op; 8968 } else { 8969 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8970 } 8971 } 8972 8973 // If one half is undef, and one is constant, perfer a splat vector rather 8974 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8975 // cheaper to use and may be free with a packed operation. 8976 if (NewElts[0].isUndef()) { 8977 if (isa<ConstantFPSDNode>(NewElts[1])) 8978 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8979 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8980 } 8981 8982 if (NewElts[1].isUndef()) { 8983 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8984 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8985 } 8986 8987 return DAG.getBuildVector(VT, SL, NewElts); 8988 } 8989 } 8990 8991 unsigned SrcOpc = N0.getOpcode(); 8992 8993 // If it's free to do so, push canonicalizes further up the source, which may 8994 // find a canonical source. 8995 // 8996 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8997 // sNaNs. 8998 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8999 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9000 if (CRHS && N0.hasOneUse()) { 9001 SDLoc SL(N); 9002 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9003 N0.getOperand(0)); 9004 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9005 DCI.AddToWorklist(Canon0.getNode()); 9006 9007 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9008 } 9009 } 9010 9011 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9012 } 9013 9014 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9015 switch (Opc) { 9016 case ISD::FMAXNUM: 9017 case ISD::FMAXNUM_IEEE: 9018 return AMDGPUISD::FMAX3; 9019 case ISD::SMAX: 9020 return AMDGPUISD::SMAX3; 9021 case ISD::UMAX: 9022 return AMDGPUISD::UMAX3; 9023 case ISD::FMINNUM: 9024 case ISD::FMINNUM_IEEE: 9025 return AMDGPUISD::FMIN3; 9026 case ISD::SMIN: 9027 return AMDGPUISD::SMIN3; 9028 case ISD::UMIN: 9029 return AMDGPUISD::UMIN3; 9030 default: 9031 llvm_unreachable("Not a min/max opcode"); 9032 } 9033 } 9034 9035 SDValue SITargetLowering::performIntMed3ImmCombine( 9036 SelectionDAG &DAG, const SDLoc &SL, 9037 SDValue Op0, SDValue Op1, bool Signed) const { 9038 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9039 if (!K1) 9040 return SDValue(); 9041 9042 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9043 if (!K0) 9044 return SDValue(); 9045 9046 if (Signed) { 9047 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9048 return SDValue(); 9049 } else { 9050 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9051 return SDValue(); 9052 } 9053 9054 EVT VT = K0->getValueType(0); 9055 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9056 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9057 return DAG.getNode(Med3Opc, SL, VT, 9058 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9059 } 9060 9061 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9062 MVT NVT = MVT::i32; 9063 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9064 9065 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9066 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9067 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9068 9069 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9070 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9071 } 9072 9073 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9074 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9075 return C; 9076 9077 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9078 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9079 return C; 9080 } 9081 9082 return nullptr; 9083 } 9084 9085 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9086 const SDLoc &SL, 9087 SDValue Op0, 9088 SDValue Op1) const { 9089 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9090 if (!K1) 9091 return SDValue(); 9092 9093 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9094 if (!K0) 9095 return SDValue(); 9096 9097 // Ordered >= (although NaN inputs should have folded away by now). 9098 if (K0->getValueAPF() > K1->getValueAPF()) 9099 return SDValue(); 9100 9101 const MachineFunction &MF = DAG.getMachineFunction(); 9102 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9103 9104 // TODO: Check IEEE bit enabled? 9105 EVT VT = Op0.getValueType(); 9106 if (Info->getMode().DX10Clamp) { 9107 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9108 // hardware fmed3 behavior converting to a min. 9109 // FIXME: Should this be allowing -0.0? 9110 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9111 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9112 } 9113 9114 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9115 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9116 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9117 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9118 // then give the other result, which is different from med3 with a NaN 9119 // input. 9120 SDValue Var = Op0.getOperand(0); 9121 if (!DAG.isKnownNeverSNaN(Var)) 9122 return SDValue(); 9123 9124 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9125 9126 if ((!K0->hasOneUse() || 9127 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9128 (!K1->hasOneUse() || 9129 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9130 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9131 Var, SDValue(K0, 0), SDValue(K1, 0)); 9132 } 9133 } 9134 9135 return SDValue(); 9136 } 9137 9138 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9139 DAGCombinerInfo &DCI) const { 9140 SelectionDAG &DAG = DCI.DAG; 9141 9142 EVT VT = N->getValueType(0); 9143 unsigned Opc = N->getOpcode(); 9144 SDValue Op0 = N->getOperand(0); 9145 SDValue Op1 = N->getOperand(1); 9146 9147 // Only do this if the inner op has one use since this will just increases 9148 // register pressure for no benefit. 9149 9150 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9151 !VT.isVector() && 9152 (VT == MVT::i32 || VT == MVT::f32 || 9153 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9154 // max(max(a, b), c) -> max3(a, b, c) 9155 // min(min(a, b), c) -> min3(a, b, c) 9156 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9157 SDLoc DL(N); 9158 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9159 DL, 9160 N->getValueType(0), 9161 Op0.getOperand(0), 9162 Op0.getOperand(1), 9163 Op1); 9164 } 9165 9166 // Try commuted. 9167 // max(a, max(b, c)) -> max3(a, b, c) 9168 // min(a, min(b, c)) -> min3(a, b, c) 9169 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9170 SDLoc DL(N); 9171 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9172 DL, 9173 N->getValueType(0), 9174 Op0, 9175 Op1.getOperand(0), 9176 Op1.getOperand(1)); 9177 } 9178 } 9179 9180 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9181 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9182 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9183 return Med3; 9184 } 9185 9186 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9187 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9188 return Med3; 9189 } 9190 9191 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9192 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9193 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9194 (Opc == AMDGPUISD::FMIN_LEGACY && 9195 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9196 (VT == MVT::f32 || VT == MVT::f64 || 9197 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9198 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9199 Op0.hasOneUse()) { 9200 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9201 return Res; 9202 } 9203 9204 return SDValue(); 9205 } 9206 9207 static bool isClampZeroToOne(SDValue A, SDValue B) { 9208 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9209 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9210 // FIXME: Should this be allowing -0.0? 9211 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9212 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9213 } 9214 } 9215 9216 return false; 9217 } 9218 9219 // FIXME: Should only worry about snans for version with chain. 9220 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9221 DAGCombinerInfo &DCI) const { 9222 EVT VT = N->getValueType(0); 9223 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9224 // NaNs. With a NaN input, the order of the operands may change the result. 9225 9226 SelectionDAG &DAG = DCI.DAG; 9227 SDLoc SL(N); 9228 9229 SDValue Src0 = N->getOperand(0); 9230 SDValue Src1 = N->getOperand(1); 9231 SDValue Src2 = N->getOperand(2); 9232 9233 if (isClampZeroToOne(Src0, Src1)) { 9234 // const_a, const_b, x -> clamp is safe in all cases including signaling 9235 // nans. 9236 // FIXME: Should this be allowing -0.0? 9237 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9238 } 9239 9240 const MachineFunction &MF = DAG.getMachineFunction(); 9241 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9242 9243 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9244 // handling no dx10-clamp? 9245 if (Info->getMode().DX10Clamp) { 9246 // If NaNs is clamped to 0, we are free to reorder the inputs. 9247 9248 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9249 std::swap(Src0, Src1); 9250 9251 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9252 std::swap(Src1, Src2); 9253 9254 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9255 std::swap(Src0, Src1); 9256 9257 if (isClampZeroToOne(Src1, Src2)) 9258 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9259 } 9260 9261 return SDValue(); 9262 } 9263 9264 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9265 DAGCombinerInfo &DCI) const { 9266 SDValue Src0 = N->getOperand(0); 9267 SDValue Src1 = N->getOperand(1); 9268 if (Src0.isUndef() && Src1.isUndef()) 9269 return DCI.DAG.getUNDEF(N->getValueType(0)); 9270 return SDValue(); 9271 } 9272 9273 SDValue SITargetLowering::performExtractVectorEltCombine( 9274 SDNode *N, DAGCombinerInfo &DCI) const { 9275 SDValue Vec = N->getOperand(0); 9276 SelectionDAG &DAG = DCI.DAG; 9277 9278 EVT VecVT = Vec.getValueType(); 9279 EVT EltVT = VecVT.getVectorElementType(); 9280 9281 if ((Vec.getOpcode() == ISD::FNEG || 9282 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9283 SDLoc SL(N); 9284 EVT EltVT = N->getValueType(0); 9285 SDValue Idx = N->getOperand(1); 9286 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9287 Vec.getOperand(0), Idx); 9288 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9289 } 9290 9291 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9292 // => 9293 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9294 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9295 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9296 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9297 SDLoc SL(N); 9298 EVT EltVT = N->getValueType(0); 9299 SDValue Idx = N->getOperand(1); 9300 unsigned Opc = Vec.getOpcode(); 9301 9302 switch(Opc) { 9303 default: 9304 break; 9305 // TODO: Support other binary operations. 9306 case ISD::FADD: 9307 case ISD::FSUB: 9308 case ISD::FMUL: 9309 case ISD::ADD: 9310 case ISD::UMIN: 9311 case ISD::UMAX: 9312 case ISD::SMIN: 9313 case ISD::SMAX: 9314 case ISD::FMAXNUM: 9315 case ISD::FMINNUM: 9316 case ISD::FMAXNUM_IEEE: 9317 case ISD::FMINNUM_IEEE: { 9318 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9319 Vec.getOperand(0), Idx); 9320 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9321 Vec.getOperand(1), Idx); 9322 9323 DCI.AddToWorklist(Elt0.getNode()); 9324 DCI.AddToWorklist(Elt1.getNode()); 9325 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9326 } 9327 } 9328 } 9329 9330 unsigned VecSize = VecVT.getSizeInBits(); 9331 unsigned EltSize = EltVT.getSizeInBits(); 9332 9333 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9334 // This elminates non-constant index and subsequent movrel or scratch access. 9335 // Sub-dword vectors of size 2 dword or less have better implementation. 9336 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9337 // instructions. 9338 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9339 !isa<ConstantSDNode>(N->getOperand(1))) { 9340 SDLoc SL(N); 9341 SDValue Idx = N->getOperand(1); 9342 SDValue V; 9343 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9344 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9345 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9346 if (I == 0) 9347 V = Elt; 9348 else 9349 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9350 } 9351 return V; 9352 } 9353 9354 if (!DCI.isBeforeLegalize()) 9355 return SDValue(); 9356 9357 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9358 // elements. This exposes more load reduction opportunities by replacing 9359 // multiple small extract_vector_elements with a single 32-bit extract. 9360 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9361 if (isa<MemSDNode>(Vec) && 9362 EltSize <= 16 && 9363 EltVT.isByteSized() && 9364 VecSize > 32 && 9365 VecSize % 32 == 0 && 9366 Idx) { 9367 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9368 9369 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9370 unsigned EltIdx = BitIndex / 32; 9371 unsigned LeftoverBitIdx = BitIndex % 32; 9372 SDLoc SL(N); 9373 9374 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9375 DCI.AddToWorklist(Cast.getNode()); 9376 9377 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9378 DAG.getConstant(EltIdx, SL, MVT::i32)); 9379 DCI.AddToWorklist(Elt.getNode()); 9380 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9381 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9382 DCI.AddToWorklist(Srl.getNode()); 9383 9384 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9385 DCI.AddToWorklist(Trunc.getNode()); 9386 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9387 } 9388 9389 return SDValue(); 9390 } 9391 9392 SDValue 9393 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9394 DAGCombinerInfo &DCI) const { 9395 SDValue Vec = N->getOperand(0); 9396 SDValue Idx = N->getOperand(2); 9397 EVT VecVT = Vec.getValueType(); 9398 EVT EltVT = VecVT.getVectorElementType(); 9399 unsigned VecSize = VecVT.getSizeInBits(); 9400 unsigned EltSize = EltVT.getSizeInBits(); 9401 9402 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9403 // => BUILD_VECTOR n x select (e, const-idx) 9404 // This elminates non-constant index and subsequent movrel or scratch access. 9405 // Sub-dword vectors of size 2 dword or less have better implementation. 9406 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9407 // instructions. 9408 if (isa<ConstantSDNode>(Idx) || 9409 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9410 return SDValue(); 9411 9412 SelectionDAG &DAG = DCI.DAG; 9413 SDLoc SL(N); 9414 SDValue Ins = N->getOperand(1); 9415 EVT IdxVT = Idx.getValueType(); 9416 9417 SmallVector<SDValue, 16> Ops; 9418 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9419 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9420 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9421 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9422 Ops.push_back(V); 9423 } 9424 9425 return DAG.getBuildVector(VecVT, SL, Ops); 9426 } 9427 9428 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9429 const SDNode *N0, 9430 const SDNode *N1) const { 9431 EVT VT = N0->getValueType(0); 9432 9433 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9434 // support denormals ever. 9435 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9436 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9437 getSubtarget()->hasMadF16())) && 9438 isOperationLegal(ISD::FMAD, VT)) 9439 return ISD::FMAD; 9440 9441 const TargetOptions &Options = DAG.getTarget().Options; 9442 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9443 (N0->getFlags().hasAllowContract() && 9444 N1->getFlags().hasAllowContract())) && 9445 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9446 return ISD::FMA; 9447 } 9448 9449 return 0; 9450 } 9451 9452 // For a reassociatable opcode perform: 9453 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9454 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9455 SelectionDAG &DAG) const { 9456 EVT VT = N->getValueType(0); 9457 if (VT != MVT::i32 && VT != MVT::i64) 9458 return SDValue(); 9459 9460 unsigned Opc = N->getOpcode(); 9461 SDValue Op0 = N->getOperand(0); 9462 SDValue Op1 = N->getOperand(1); 9463 9464 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9465 return SDValue(); 9466 9467 if (Op0->isDivergent()) 9468 std::swap(Op0, Op1); 9469 9470 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9471 return SDValue(); 9472 9473 SDValue Op2 = Op1.getOperand(1); 9474 Op1 = Op1.getOperand(0); 9475 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9476 return SDValue(); 9477 9478 if (Op1->isDivergent()) 9479 std::swap(Op1, Op2); 9480 9481 // If either operand is constant this will conflict with 9482 // DAGCombiner::ReassociateOps(). 9483 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9484 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9485 return SDValue(); 9486 9487 SDLoc SL(N); 9488 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9489 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9490 } 9491 9492 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9493 EVT VT, 9494 SDValue N0, SDValue N1, SDValue N2, 9495 bool Signed) { 9496 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9497 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9498 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9499 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9500 } 9501 9502 SDValue SITargetLowering::performAddCombine(SDNode *N, 9503 DAGCombinerInfo &DCI) const { 9504 SelectionDAG &DAG = DCI.DAG; 9505 EVT VT = N->getValueType(0); 9506 SDLoc SL(N); 9507 SDValue LHS = N->getOperand(0); 9508 SDValue RHS = N->getOperand(1); 9509 9510 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9511 && Subtarget->hasMad64_32() && 9512 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9513 VT.getScalarSizeInBits() <= 64) { 9514 if (LHS.getOpcode() != ISD::MUL) 9515 std::swap(LHS, RHS); 9516 9517 SDValue MulLHS = LHS.getOperand(0); 9518 SDValue MulRHS = LHS.getOperand(1); 9519 SDValue AddRHS = RHS; 9520 9521 // TODO: Maybe restrict if SGPR inputs. 9522 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9523 numBitsUnsigned(MulRHS, DAG) <= 32) { 9524 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9525 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9526 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9527 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9528 } 9529 9530 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9531 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9532 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9533 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9534 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9535 } 9536 9537 return SDValue(); 9538 } 9539 9540 if (SDValue V = reassociateScalarOps(N, DAG)) { 9541 return V; 9542 } 9543 9544 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9545 return SDValue(); 9546 9547 // add x, zext (setcc) => addcarry x, 0, setcc 9548 // add x, sext (setcc) => subcarry x, 0, setcc 9549 unsigned Opc = LHS.getOpcode(); 9550 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9551 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9552 std::swap(RHS, LHS); 9553 9554 Opc = RHS.getOpcode(); 9555 switch (Opc) { 9556 default: break; 9557 case ISD::ZERO_EXTEND: 9558 case ISD::SIGN_EXTEND: 9559 case ISD::ANY_EXTEND: { 9560 auto Cond = RHS.getOperand(0); 9561 // If this won't be a real VOPC output, we would still need to insert an 9562 // extra instruction anyway. 9563 if (!isBoolSGPR(Cond)) 9564 break; 9565 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9566 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9567 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9568 return DAG.getNode(Opc, SL, VTList, Args); 9569 } 9570 case ISD::ADDCARRY: { 9571 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9572 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9573 if (!C || C->getZExtValue() != 0) break; 9574 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9575 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9576 } 9577 } 9578 return SDValue(); 9579 } 9580 9581 SDValue SITargetLowering::performSubCombine(SDNode *N, 9582 DAGCombinerInfo &DCI) const { 9583 SelectionDAG &DAG = DCI.DAG; 9584 EVT VT = N->getValueType(0); 9585 9586 if (VT != MVT::i32) 9587 return SDValue(); 9588 9589 SDLoc SL(N); 9590 SDValue LHS = N->getOperand(0); 9591 SDValue RHS = N->getOperand(1); 9592 9593 // sub x, zext (setcc) => subcarry x, 0, setcc 9594 // sub x, sext (setcc) => addcarry x, 0, setcc 9595 unsigned Opc = RHS.getOpcode(); 9596 switch (Opc) { 9597 default: break; 9598 case ISD::ZERO_EXTEND: 9599 case ISD::SIGN_EXTEND: 9600 case ISD::ANY_EXTEND: { 9601 auto Cond = RHS.getOperand(0); 9602 // If this won't be a real VOPC output, we would still need to insert an 9603 // extra instruction anyway. 9604 if (!isBoolSGPR(Cond)) 9605 break; 9606 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9607 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9608 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9609 return DAG.getNode(Opc, SL, VTList, Args); 9610 } 9611 } 9612 9613 if (LHS.getOpcode() == ISD::SUBCARRY) { 9614 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9615 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9616 if (!C || !C->isNullValue()) 9617 return SDValue(); 9618 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9619 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9620 } 9621 return SDValue(); 9622 } 9623 9624 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9625 DAGCombinerInfo &DCI) const { 9626 9627 if (N->getValueType(0) != MVT::i32) 9628 return SDValue(); 9629 9630 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9631 if (!C || C->getZExtValue() != 0) 9632 return SDValue(); 9633 9634 SelectionDAG &DAG = DCI.DAG; 9635 SDValue LHS = N->getOperand(0); 9636 9637 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9638 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9639 unsigned LHSOpc = LHS.getOpcode(); 9640 unsigned Opc = N->getOpcode(); 9641 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9642 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9643 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9644 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9645 } 9646 return SDValue(); 9647 } 9648 9649 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9650 DAGCombinerInfo &DCI) const { 9651 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9652 return SDValue(); 9653 9654 SelectionDAG &DAG = DCI.DAG; 9655 EVT VT = N->getValueType(0); 9656 9657 SDLoc SL(N); 9658 SDValue LHS = N->getOperand(0); 9659 SDValue RHS = N->getOperand(1); 9660 9661 // These should really be instruction patterns, but writing patterns with 9662 // source modiifiers is a pain. 9663 9664 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9665 if (LHS.getOpcode() == ISD::FADD) { 9666 SDValue A = LHS.getOperand(0); 9667 if (A == LHS.getOperand(1)) { 9668 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9669 if (FusedOp != 0) { 9670 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9671 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9672 } 9673 } 9674 } 9675 9676 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9677 if (RHS.getOpcode() == ISD::FADD) { 9678 SDValue A = RHS.getOperand(0); 9679 if (A == RHS.getOperand(1)) { 9680 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9681 if (FusedOp != 0) { 9682 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9683 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9684 } 9685 } 9686 } 9687 9688 return SDValue(); 9689 } 9690 9691 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9692 DAGCombinerInfo &DCI) const { 9693 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9694 return SDValue(); 9695 9696 SelectionDAG &DAG = DCI.DAG; 9697 SDLoc SL(N); 9698 EVT VT = N->getValueType(0); 9699 assert(!VT.isVector()); 9700 9701 // Try to get the fneg to fold into the source modifier. This undoes generic 9702 // DAG combines and folds them into the mad. 9703 // 9704 // Only do this if we are not trying to support denormals. v_mad_f32 does 9705 // not support denormals ever. 9706 SDValue LHS = N->getOperand(0); 9707 SDValue RHS = N->getOperand(1); 9708 if (LHS.getOpcode() == ISD::FADD) { 9709 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9710 SDValue A = LHS.getOperand(0); 9711 if (A == LHS.getOperand(1)) { 9712 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9713 if (FusedOp != 0){ 9714 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9715 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9716 9717 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9718 } 9719 } 9720 } 9721 9722 if (RHS.getOpcode() == ISD::FADD) { 9723 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9724 9725 SDValue A = RHS.getOperand(0); 9726 if (A == RHS.getOperand(1)) { 9727 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9728 if (FusedOp != 0){ 9729 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9730 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9731 } 9732 } 9733 } 9734 9735 return SDValue(); 9736 } 9737 9738 SDValue SITargetLowering::performFMACombine(SDNode *N, 9739 DAGCombinerInfo &DCI) const { 9740 SelectionDAG &DAG = DCI.DAG; 9741 EVT VT = N->getValueType(0); 9742 SDLoc SL(N); 9743 9744 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9745 return SDValue(); 9746 9747 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9748 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9749 SDValue Op1 = N->getOperand(0); 9750 SDValue Op2 = N->getOperand(1); 9751 SDValue FMA = N->getOperand(2); 9752 9753 if (FMA.getOpcode() != ISD::FMA || 9754 Op1.getOpcode() != ISD::FP_EXTEND || 9755 Op2.getOpcode() != ISD::FP_EXTEND) 9756 return SDValue(); 9757 9758 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9759 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9760 // is sufficient to allow generaing fdot2. 9761 const TargetOptions &Options = DAG.getTarget().Options; 9762 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9763 (N->getFlags().hasAllowContract() && 9764 FMA->getFlags().hasAllowContract())) { 9765 Op1 = Op1.getOperand(0); 9766 Op2 = Op2.getOperand(0); 9767 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9768 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9769 return SDValue(); 9770 9771 SDValue Vec1 = Op1.getOperand(0); 9772 SDValue Idx1 = Op1.getOperand(1); 9773 SDValue Vec2 = Op2.getOperand(0); 9774 9775 SDValue FMAOp1 = FMA.getOperand(0); 9776 SDValue FMAOp2 = FMA.getOperand(1); 9777 SDValue FMAAcc = FMA.getOperand(2); 9778 9779 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9780 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9781 return SDValue(); 9782 9783 FMAOp1 = FMAOp1.getOperand(0); 9784 FMAOp2 = FMAOp2.getOperand(0); 9785 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9786 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9787 return SDValue(); 9788 9789 SDValue Vec3 = FMAOp1.getOperand(0); 9790 SDValue Vec4 = FMAOp2.getOperand(0); 9791 SDValue Idx2 = FMAOp1.getOperand(1); 9792 9793 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9794 // Idx1 and Idx2 cannot be the same. 9795 Idx1 == Idx2) 9796 return SDValue(); 9797 9798 if (Vec1 == Vec2 || Vec3 == Vec4) 9799 return SDValue(); 9800 9801 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9802 return SDValue(); 9803 9804 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9805 (Vec1 == Vec4 && Vec2 == Vec3)) { 9806 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9807 DAG.getTargetConstant(0, SL, MVT::i1)); 9808 } 9809 } 9810 return SDValue(); 9811 } 9812 9813 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9814 DAGCombinerInfo &DCI) const { 9815 SelectionDAG &DAG = DCI.DAG; 9816 SDLoc SL(N); 9817 9818 SDValue LHS = N->getOperand(0); 9819 SDValue RHS = N->getOperand(1); 9820 EVT VT = LHS.getValueType(); 9821 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9822 9823 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9824 if (!CRHS) { 9825 CRHS = dyn_cast<ConstantSDNode>(LHS); 9826 if (CRHS) { 9827 std::swap(LHS, RHS); 9828 CC = getSetCCSwappedOperands(CC); 9829 } 9830 } 9831 9832 if (CRHS) { 9833 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9834 isBoolSGPR(LHS.getOperand(0))) { 9835 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9836 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9837 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9838 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9839 if ((CRHS->isAllOnesValue() && 9840 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9841 (CRHS->isNullValue() && 9842 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9843 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9844 DAG.getConstant(-1, SL, MVT::i1)); 9845 if ((CRHS->isAllOnesValue() && 9846 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9847 (CRHS->isNullValue() && 9848 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9849 return LHS.getOperand(0); 9850 } 9851 9852 uint64_t CRHSVal = CRHS->getZExtValue(); 9853 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9854 LHS.getOpcode() == ISD::SELECT && 9855 isa<ConstantSDNode>(LHS.getOperand(1)) && 9856 isa<ConstantSDNode>(LHS.getOperand(2)) && 9857 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9858 isBoolSGPR(LHS.getOperand(0))) { 9859 // Given CT != FT: 9860 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9861 // setcc (select cc, CT, CF), CF, ne => cc 9862 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9863 // setcc (select cc, CT, CF), CT, eq => cc 9864 uint64_t CT = LHS.getConstantOperandVal(1); 9865 uint64_t CF = LHS.getConstantOperandVal(2); 9866 9867 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9868 (CT == CRHSVal && CC == ISD::SETNE)) 9869 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9870 DAG.getConstant(-1, SL, MVT::i1)); 9871 if ((CF == CRHSVal && CC == ISD::SETNE) || 9872 (CT == CRHSVal && CC == ISD::SETEQ)) 9873 return LHS.getOperand(0); 9874 } 9875 } 9876 9877 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9878 VT != MVT::f16)) 9879 return SDValue(); 9880 9881 // Match isinf/isfinite pattern 9882 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9883 // (fcmp one (fabs x), inf) -> (fp_class x, 9884 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9885 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9886 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9887 if (!CRHS) 9888 return SDValue(); 9889 9890 const APFloat &APF = CRHS->getValueAPF(); 9891 if (APF.isInfinity() && !APF.isNegative()) { 9892 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9893 SIInstrFlags::N_INFINITY; 9894 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9895 SIInstrFlags::P_ZERO | 9896 SIInstrFlags::N_NORMAL | 9897 SIInstrFlags::P_NORMAL | 9898 SIInstrFlags::N_SUBNORMAL | 9899 SIInstrFlags::P_SUBNORMAL; 9900 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9901 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9902 DAG.getConstant(Mask, SL, MVT::i32)); 9903 } 9904 } 9905 9906 return SDValue(); 9907 } 9908 9909 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9910 DAGCombinerInfo &DCI) const { 9911 SelectionDAG &DAG = DCI.DAG; 9912 SDLoc SL(N); 9913 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9914 9915 SDValue Src = N->getOperand(0); 9916 SDValue Shift = N->getOperand(0); 9917 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 9918 Shift = Shift.getOperand(0); 9919 9920 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 9921 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 9922 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 9923 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9924 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9925 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9926 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 9927 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 9928 SDLoc(Shift.getOperand(0)), MVT::i32); 9929 9930 unsigned ShiftOffset = 8 * Offset; 9931 if (Shift.getOpcode() == ISD::SHL) 9932 ShiftOffset -= C->getZExtValue(); 9933 else 9934 ShiftOffset += C->getZExtValue(); 9935 9936 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 9937 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 9938 MVT::f32, Shift); 9939 } 9940 } 9941 } 9942 9943 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9944 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9945 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 9946 // We simplified Src. If this node is not dead, visit it again so it is 9947 // folded properly. 9948 if (N->getOpcode() != ISD::DELETED_NODE) 9949 DCI.AddToWorklist(N); 9950 return SDValue(N, 0); 9951 } 9952 9953 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 9954 if (SDValue DemandedSrc = 9955 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 9956 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 9957 9958 return SDValue(); 9959 } 9960 9961 SDValue SITargetLowering::performClampCombine(SDNode *N, 9962 DAGCombinerInfo &DCI) const { 9963 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9964 if (!CSrc) 9965 return SDValue(); 9966 9967 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9968 const APFloat &F = CSrc->getValueAPF(); 9969 APFloat Zero = APFloat::getZero(F.getSemantics()); 9970 if (F < Zero || 9971 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9972 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9973 } 9974 9975 APFloat One(F.getSemantics(), "1.0"); 9976 if (F > One) 9977 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9978 9979 return SDValue(CSrc, 0); 9980 } 9981 9982 9983 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9984 DAGCombinerInfo &DCI) const { 9985 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9986 return SDValue(); 9987 switch (N->getOpcode()) { 9988 default: 9989 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9990 case ISD::ADD: 9991 return performAddCombine(N, DCI); 9992 case ISD::SUB: 9993 return performSubCombine(N, DCI); 9994 case ISD::ADDCARRY: 9995 case ISD::SUBCARRY: 9996 return performAddCarrySubCarryCombine(N, DCI); 9997 case ISD::FADD: 9998 return performFAddCombine(N, DCI); 9999 case ISD::FSUB: 10000 return performFSubCombine(N, DCI); 10001 case ISD::SETCC: 10002 return performSetCCCombine(N, DCI); 10003 case ISD::FMAXNUM: 10004 case ISD::FMINNUM: 10005 case ISD::FMAXNUM_IEEE: 10006 case ISD::FMINNUM_IEEE: 10007 case ISD::SMAX: 10008 case ISD::SMIN: 10009 case ISD::UMAX: 10010 case ISD::UMIN: 10011 case AMDGPUISD::FMIN_LEGACY: 10012 case AMDGPUISD::FMAX_LEGACY: 10013 return performMinMaxCombine(N, DCI); 10014 case ISD::FMA: 10015 return performFMACombine(N, DCI); 10016 case ISD::LOAD: { 10017 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10018 return Widended; 10019 LLVM_FALLTHROUGH; 10020 } 10021 case ISD::STORE: 10022 case ISD::ATOMIC_LOAD: 10023 case ISD::ATOMIC_STORE: 10024 case ISD::ATOMIC_CMP_SWAP: 10025 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10026 case ISD::ATOMIC_SWAP: 10027 case ISD::ATOMIC_LOAD_ADD: 10028 case ISD::ATOMIC_LOAD_SUB: 10029 case ISD::ATOMIC_LOAD_AND: 10030 case ISD::ATOMIC_LOAD_OR: 10031 case ISD::ATOMIC_LOAD_XOR: 10032 case ISD::ATOMIC_LOAD_NAND: 10033 case ISD::ATOMIC_LOAD_MIN: 10034 case ISD::ATOMIC_LOAD_MAX: 10035 case ISD::ATOMIC_LOAD_UMIN: 10036 case ISD::ATOMIC_LOAD_UMAX: 10037 case ISD::ATOMIC_LOAD_FADD: 10038 case AMDGPUISD::ATOMIC_INC: 10039 case AMDGPUISD::ATOMIC_DEC: 10040 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10041 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10042 if (DCI.isBeforeLegalize()) 10043 break; 10044 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10045 case ISD::AND: 10046 return performAndCombine(N, DCI); 10047 case ISD::OR: 10048 return performOrCombine(N, DCI); 10049 case ISD::XOR: 10050 return performXorCombine(N, DCI); 10051 case ISD::ZERO_EXTEND: 10052 return performZeroExtendCombine(N, DCI); 10053 case ISD::SIGN_EXTEND_INREG: 10054 return performSignExtendInRegCombine(N , DCI); 10055 case AMDGPUISD::FP_CLASS: 10056 return performClassCombine(N, DCI); 10057 case ISD::FCANONICALIZE: 10058 return performFCanonicalizeCombine(N, DCI); 10059 case AMDGPUISD::RCP: 10060 return performRcpCombine(N, DCI); 10061 case AMDGPUISD::FRACT: 10062 case AMDGPUISD::RSQ: 10063 case AMDGPUISD::RCP_LEGACY: 10064 case AMDGPUISD::RSQ_LEGACY: 10065 case AMDGPUISD::RCP_IFLAG: 10066 case AMDGPUISD::RSQ_CLAMP: 10067 case AMDGPUISD::LDEXP: { 10068 SDValue Src = N->getOperand(0); 10069 if (Src.isUndef()) 10070 return Src; 10071 break; 10072 } 10073 case ISD::SINT_TO_FP: 10074 case ISD::UINT_TO_FP: 10075 return performUCharToFloatCombine(N, DCI); 10076 case AMDGPUISD::CVT_F32_UBYTE0: 10077 case AMDGPUISD::CVT_F32_UBYTE1: 10078 case AMDGPUISD::CVT_F32_UBYTE2: 10079 case AMDGPUISD::CVT_F32_UBYTE3: 10080 return performCvtF32UByteNCombine(N, DCI); 10081 case AMDGPUISD::FMED3: 10082 return performFMed3Combine(N, DCI); 10083 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10084 return performCvtPkRTZCombine(N, DCI); 10085 case AMDGPUISD::CLAMP: 10086 return performClampCombine(N, DCI); 10087 case ISD::SCALAR_TO_VECTOR: { 10088 SelectionDAG &DAG = DCI.DAG; 10089 EVT VT = N->getValueType(0); 10090 10091 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10092 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10093 SDLoc SL(N); 10094 SDValue Src = N->getOperand(0); 10095 EVT EltVT = Src.getValueType(); 10096 if (EltVT == MVT::f16) 10097 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10098 10099 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10100 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10101 } 10102 10103 break; 10104 } 10105 case ISD::EXTRACT_VECTOR_ELT: 10106 return performExtractVectorEltCombine(N, DCI); 10107 case ISD::INSERT_VECTOR_ELT: 10108 return performInsertVectorEltCombine(N, DCI); 10109 } 10110 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10111 } 10112 10113 /// Helper function for adjustWritemask 10114 static unsigned SubIdx2Lane(unsigned Idx) { 10115 switch (Idx) { 10116 default: return 0; 10117 case AMDGPU::sub0: return 0; 10118 case AMDGPU::sub1: return 1; 10119 case AMDGPU::sub2: return 2; 10120 case AMDGPU::sub3: return 3; 10121 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10122 } 10123 } 10124 10125 /// Adjust the writemask of MIMG instructions 10126 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10127 SelectionDAG &DAG) const { 10128 unsigned Opcode = Node->getMachineOpcode(); 10129 10130 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10131 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10132 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10133 return Node; // not implemented for D16 10134 10135 SDNode *Users[5] = { nullptr }; 10136 unsigned Lane = 0; 10137 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10138 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10139 unsigned NewDmask = 0; 10140 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10141 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10142 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10143 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10144 unsigned TFCLane = 0; 10145 bool HasChain = Node->getNumValues() > 1; 10146 10147 if (OldDmask == 0) { 10148 // These are folded out, but on the chance it happens don't assert. 10149 return Node; 10150 } 10151 10152 unsigned OldBitsSet = countPopulation(OldDmask); 10153 // Work out which is the TFE/LWE lane if that is enabled. 10154 if (UsesTFC) { 10155 TFCLane = OldBitsSet; 10156 } 10157 10158 // Try to figure out the used register components 10159 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10160 I != E; ++I) { 10161 10162 // Don't look at users of the chain. 10163 if (I.getUse().getResNo() != 0) 10164 continue; 10165 10166 // Abort if we can't understand the usage 10167 if (!I->isMachineOpcode() || 10168 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10169 return Node; 10170 10171 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10172 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10173 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10174 // set, etc. 10175 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10176 10177 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10178 if (UsesTFC && Lane == TFCLane) { 10179 Users[Lane] = *I; 10180 } else { 10181 // Set which texture component corresponds to the lane. 10182 unsigned Comp; 10183 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10184 Comp = countTrailingZeros(Dmask); 10185 Dmask &= ~(1 << Comp); 10186 } 10187 10188 // Abort if we have more than one user per component. 10189 if (Users[Lane]) 10190 return Node; 10191 10192 Users[Lane] = *I; 10193 NewDmask |= 1 << Comp; 10194 } 10195 } 10196 10197 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10198 bool NoChannels = !NewDmask; 10199 if (NoChannels) { 10200 if (!UsesTFC) { 10201 // No uses of the result and not using TFC. Then do nothing. 10202 return Node; 10203 } 10204 // If the original dmask has one channel - then nothing to do 10205 if (OldBitsSet == 1) 10206 return Node; 10207 // Use an arbitrary dmask - required for the instruction to work 10208 NewDmask = 1; 10209 } 10210 // Abort if there's no change 10211 if (NewDmask == OldDmask) 10212 return Node; 10213 10214 unsigned BitsSet = countPopulation(NewDmask); 10215 10216 // Check for TFE or LWE - increase the number of channels by one to account 10217 // for the extra return value 10218 // This will need adjustment for D16 if this is also included in 10219 // adjustWriteMask (this function) but at present D16 are excluded. 10220 unsigned NewChannels = BitsSet + UsesTFC; 10221 10222 int NewOpcode = 10223 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10224 assert(NewOpcode != -1 && 10225 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10226 "failed to find equivalent MIMG op"); 10227 10228 // Adjust the writemask in the node 10229 SmallVector<SDValue, 12> Ops; 10230 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10231 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10232 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10233 10234 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10235 10236 MVT ResultVT = NewChannels == 1 ? 10237 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10238 NewChannels == 5 ? 8 : NewChannels); 10239 SDVTList NewVTList = HasChain ? 10240 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10241 10242 10243 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10244 NewVTList, Ops); 10245 10246 if (HasChain) { 10247 // Update chain. 10248 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10249 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10250 } 10251 10252 if (NewChannels == 1) { 10253 assert(Node->hasNUsesOfValue(1, 0)); 10254 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10255 SDLoc(Node), Users[Lane]->getValueType(0), 10256 SDValue(NewNode, 0)); 10257 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10258 return nullptr; 10259 } 10260 10261 // Update the users of the node with the new indices 10262 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10263 SDNode *User = Users[i]; 10264 if (!User) { 10265 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10266 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10267 if (i || !NoChannels) 10268 continue; 10269 } else { 10270 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10271 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10272 } 10273 10274 switch (Idx) { 10275 default: break; 10276 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10277 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10278 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10279 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10280 } 10281 } 10282 10283 DAG.RemoveDeadNode(Node); 10284 return nullptr; 10285 } 10286 10287 static bool isFrameIndexOp(SDValue Op) { 10288 if (Op.getOpcode() == ISD::AssertZext) 10289 Op = Op.getOperand(0); 10290 10291 return isa<FrameIndexSDNode>(Op); 10292 } 10293 10294 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10295 /// with frame index operands. 10296 /// LLVM assumes that inputs are to these instructions are registers. 10297 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10298 SelectionDAG &DAG) const { 10299 if (Node->getOpcode() == ISD::CopyToReg) { 10300 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10301 SDValue SrcVal = Node->getOperand(2); 10302 10303 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10304 // to try understanding copies to physical registers. 10305 if (SrcVal.getValueType() == MVT::i1 && 10306 Register::isPhysicalRegister(DestReg->getReg())) { 10307 SDLoc SL(Node); 10308 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10309 SDValue VReg = DAG.getRegister( 10310 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10311 10312 SDNode *Glued = Node->getGluedNode(); 10313 SDValue ToVReg 10314 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10315 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10316 SDValue ToResultReg 10317 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10318 VReg, ToVReg.getValue(1)); 10319 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10320 DAG.RemoveDeadNode(Node); 10321 return ToResultReg.getNode(); 10322 } 10323 } 10324 10325 SmallVector<SDValue, 8> Ops; 10326 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10327 if (!isFrameIndexOp(Node->getOperand(i))) { 10328 Ops.push_back(Node->getOperand(i)); 10329 continue; 10330 } 10331 10332 SDLoc DL(Node); 10333 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10334 Node->getOperand(i).getValueType(), 10335 Node->getOperand(i)), 0)); 10336 } 10337 10338 return DAG.UpdateNodeOperands(Node, Ops); 10339 } 10340 10341 /// Fold the instructions after selecting them. 10342 /// Returns null if users were already updated. 10343 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10344 SelectionDAG &DAG) const { 10345 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10346 unsigned Opcode = Node->getMachineOpcode(); 10347 10348 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10349 !TII->isGather4(Opcode)) { 10350 return adjustWritemask(Node, DAG); 10351 } 10352 10353 if (Opcode == AMDGPU::INSERT_SUBREG || 10354 Opcode == AMDGPU::REG_SEQUENCE) { 10355 legalizeTargetIndependentNode(Node, DAG); 10356 return Node; 10357 } 10358 10359 switch (Opcode) { 10360 case AMDGPU::V_DIV_SCALE_F32: 10361 case AMDGPU::V_DIV_SCALE_F64: { 10362 // Satisfy the operand register constraint when one of the inputs is 10363 // undefined. Ordinarily each undef value will have its own implicit_def of 10364 // a vreg, so force these to use a single register. 10365 SDValue Src0 = Node->getOperand(0); 10366 SDValue Src1 = Node->getOperand(1); 10367 SDValue Src2 = Node->getOperand(2); 10368 10369 if ((Src0.isMachineOpcode() && 10370 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10371 (Src0 == Src1 || Src0 == Src2)) 10372 break; 10373 10374 MVT VT = Src0.getValueType().getSimpleVT(); 10375 const TargetRegisterClass *RC = 10376 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10377 10378 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10379 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10380 10381 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10382 UndefReg, Src0, SDValue()); 10383 10384 // src0 must be the same register as src1 or src2, even if the value is 10385 // undefined, so make sure we don't violate this constraint. 10386 if (Src0.isMachineOpcode() && 10387 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10388 if (Src1.isMachineOpcode() && 10389 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10390 Src0 = Src1; 10391 else if (Src2.isMachineOpcode() && 10392 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10393 Src0 = Src2; 10394 else { 10395 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10396 Src0 = UndefReg; 10397 Src1 = UndefReg; 10398 } 10399 } else 10400 break; 10401 10402 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10403 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10404 Ops.push_back(Node->getOperand(I)); 10405 10406 Ops.push_back(ImpDef.getValue(1)); 10407 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10408 } 10409 default: 10410 break; 10411 } 10412 10413 return Node; 10414 } 10415 10416 /// Assign the register class depending on the number of 10417 /// bits set in the writemask 10418 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10419 SDNode *Node) const { 10420 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10421 10422 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10423 10424 if (TII->isVOP3(MI.getOpcode())) { 10425 // Make sure constant bus requirements are respected. 10426 TII->legalizeOperandsVOP3(MRI, MI); 10427 10428 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10429 // This saves a chain-copy of registers and better ballance register 10430 // use between vgpr and agpr as agpr tuples tend to be big. 10431 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10432 unsigned Opc = MI.getOpcode(); 10433 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10434 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10435 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10436 if (I == -1) 10437 break; 10438 MachineOperand &Op = MI.getOperand(I); 10439 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10440 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10441 !Register::isVirtualRegister(Op.getReg()) || 10442 !TRI->isAGPR(MRI, Op.getReg())) 10443 continue; 10444 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10445 if (!Src || !Src->isCopy() || 10446 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10447 continue; 10448 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10449 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10450 // All uses of agpr64 and agpr32 can also accept vgpr except for 10451 // v_accvgpr_read, but we do not produce agpr reads during selection, 10452 // so no use checks are needed. 10453 MRI.setRegClass(Op.getReg(), NewRC); 10454 } 10455 } 10456 10457 return; 10458 } 10459 10460 // Replace unused atomics with the no return version. 10461 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10462 if (NoRetAtomicOp != -1) { 10463 if (!Node->hasAnyUseOfValue(0)) { 10464 MI.setDesc(TII->get(NoRetAtomicOp)); 10465 MI.RemoveOperand(0); 10466 return; 10467 } 10468 10469 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10470 // instruction, because the return type of these instructions is a vec2 of 10471 // the memory type, so it can be tied to the input operand. 10472 // This means these instructions always have a use, so we need to add a 10473 // special case to check if the atomic has only one extract_subreg use, 10474 // which itself has no uses. 10475 if ((Node->hasNUsesOfValue(1, 0) && 10476 Node->use_begin()->isMachineOpcode() && 10477 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10478 !Node->use_begin()->hasAnyUseOfValue(0))) { 10479 Register Def = MI.getOperand(0).getReg(); 10480 10481 // Change this into a noret atomic. 10482 MI.setDesc(TII->get(NoRetAtomicOp)); 10483 MI.RemoveOperand(0); 10484 10485 // If we only remove the def operand from the atomic instruction, the 10486 // extract_subreg will be left with a use of a vreg without a def. 10487 // So we need to insert an implicit_def to avoid machine verifier 10488 // errors. 10489 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10490 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10491 } 10492 return; 10493 } 10494 } 10495 10496 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10497 uint64_t Val) { 10498 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10499 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10500 } 10501 10502 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10503 const SDLoc &DL, 10504 SDValue Ptr) const { 10505 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10506 10507 // Build the half of the subregister with the constants before building the 10508 // full 128-bit register. If we are building multiple resource descriptors, 10509 // this will allow CSEing of the 2-component register. 10510 const SDValue Ops0[] = { 10511 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10512 buildSMovImm32(DAG, DL, 0), 10513 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10514 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10515 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10516 }; 10517 10518 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10519 MVT::v2i32, Ops0), 0); 10520 10521 // Combine the constants and the pointer. 10522 const SDValue Ops1[] = { 10523 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10524 Ptr, 10525 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10526 SubRegHi, 10527 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10528 }; 10529 10530 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10531 } 10532 10533 /// Return a resource descriptor with the 'Add TID' bit enabled 10534 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10535 /// of the resource descriptor) to create an offset, which is added to 10536 /// the resource pointer. 10537 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10538 SDValue Ptr, uint32_t RsrcDword1, 10539 uint64_t RsrcDword2And3) const { 10540 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10541 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10542 if (RsrcDword1) { 10543 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10544 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10545 0); 10546 } 10547 10548 SDValue DataLo = buildSMovImm32(DAG, DL, 10549 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10550 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10551 10552 const SDValue Ops[] = { 10553 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10554 PtrLo, 10555 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10556 PtrHi, 10557 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10558 DataLo, 10559 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10560 DataHi, 10561 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10562 }; 10563 10564 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10565 } 10566 10567 //===----------------------------------------------------------------------===// 10568 // SI Inline Assembly Support 10569 //===----------------------------------------------------------------------===// 10570 10571 std::pair<unsigned, const TargetRegisterClass *> 10572 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10573 StringRef Constraint, 10574 MVT VT) const { 10575 const TargetRegisterClass *RC = nullptr; 10576 if (Constraint.size() == 1) { 10577 switch (Constraint[0]) { 10578 default: 10579 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10580 case 's': 10581 case 'r': 10582 switch (VT.getSizeInBits()) { 10583 default: 10584 return std::make_pair(0U, nullptr); 10585 case 32: 10586 case 16: 10587 RC = &AMDGPU::SReg_32RegClass; 10588 break; 10589 case 64: 10590 RC = &AMDGPU::SGPR_64RegClass; 10591 break; 10592 case 96: 10593 RC = &AMDGPU::SReg_96RegClass; 10594 break; 10595 case 128: 10596 RC = &AMDGPU::SGPR_128RegClass; 10597 break; 10598 case 160: 10599 RC = &AMDGPU::SReg_160RegClass; 10600 break; 10601 case 256: 10602 RC = &AMDGPU::SReg_256RegClass; 10603 break; 10604 case 512: 10605 RC = &AMDGPU::SReg_512RegClass; 10606 break; 10607 } 10608 break; 10609 case 'v': 10610 switch (VT.getSizeInBits()) { 10611 default: 10612 return std::make_pair(0U, nullptr); 10613 case 32: 10614 case 16: 10615 RC = &AMDGPU::VGPR_32RegClass; 10616 break; 10617 case 64: 10618 RC = &AMDGPU::VReg_64RegClass; 10619 break; 10620 case 96: 10621 RC = &AMDGPU::VReg_96RegClass; 10622 break; 10623 case 128: 10624 RC = &AMDGPU::VReg_128RegClass; 10625 break; 10626 case 160: 10627 RC = &AMDGPU::VReg_160RegClass; 10628 break; 10629 case 256: 10630 RC = &AMDGPU::VReg_256RegClass; 10631 break; 10632 case 512: 10633 RC = &AMDGPU::VReg_512RegClass; 10634 break; 10635 } 10636 break; 10637 case 'a': 10638 if (!Subtarget->hasMAIInsts()) 10639 break; 10640 switch (VT.getSizeInBits()) { 10641 default: 10642 return std::make_pair(0U, nullptr); 10643 case 32: 10644 case 16: 10645 RC = &AMDGPU::AGPR_32RegClass; 10646 break; 10647 case 64: 10648 RC = &AMDGPU::AReg_64RegClass; 10649 break; 10650 case 128: 10651 RC = &AMDGPU::AReg_128RegClass; 10652 break; 10653 case 512: 10654 RC = &AMDGPU::AReg_512RegClass; 10655 break; 10656 case 1024: 10657 RC = &AMDGPU::AReg_1024RegClass; 10658 // v32 types are not legal but we support them here. 10659 return std::make_pair(0U, RC); 10660 } 10661 break; 10662 } 10663 // We actually support i128, i16 and f16 as inline parameters 10664 // even if they are not reported as legal 10665 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10666 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10667 return std::make_pair(0U, RC); 10668 } 10669 10670 if (Constraint.size() > 1) { 10671 if (Constraint[1] == 'v') { 10672 RC = &AMDGPU::VGPR_32RegClass; 10673 } else if (Constraint[1] == 's') { 10674 RC = &AMDGPU::SGPR_32RegClass; 10675 } else if (Constraint[1] == 'a') { 10676 RC = &AMDGPU::AGPR_32RegClass; 10677 } 10678 10679 if (RC) { 10680 uint32_t Idx; 10681 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10682 if (!Failed && Idx < RC->getNumRegs()) 10683 return std::make_pair(RC->getRegister(Idx), RC); 10684 } 10685 } 10686 10687 // FIXME: Returns VS_32 for physical SGPR constraints 10688 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10689 } 10690 10691 SITargetLowering::ConstraintType 10692 SITargetLowering::getConstraintType(StringRef Constraint) const { 10693 if (Constraint.size() == 1) { 10694 switch (Constraint[0]) { 10695 default: break; 10696 case 's': 10697 case 'v': 10698 case 'a': 10699 return C_RegisterClass; 10700 } 10701 } 10702 return TargetLowering::getConstraintType(Constraint); 10703 } 10704 10705 // Figure out which registers should be reserved for stack access. Only after 10706 // the function is legalized do we know all of the non-spill stack objects or if 10707 // calls are present. 10708 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10709 MachineRegisterInfo &MRI = MF.getRegInfo(); 10710 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10711 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10712 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10713 10714 if (Info->isEntryFunction()) { 10715 // Callable functions have fixed registers used for stack access. 10716 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10717 } 10718 10719 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10720 Info->getStackPtrOffsetReg())); 10721 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10722 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10723 10724 // We need to worry about replacing the default register with itself in case 10725 // of MIR testcases missing the MFI. 10726 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10727 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10728 10729 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10730 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10731 10732 Info->limitOccupancy(MF); 10733 10734 if (ST.isWave32() && !MF.empty()) { 10735 // Add VCC_HI def because many instructions marked as imp-use VCC where 10736 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10737 // having a use of undef. 10738 10739 const SIInstrInfo *TII = ST.getInstrInfo(); 10740 DebugLoc DL; 10741 10742 MachineBasicBlock &MBB = MF.front(); 10743 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10744 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10745 10746 for (auto &MBB : MF) { 10747 for (auto &MI : MBB) { 10748 TII->fixImplicitOperands(MI); 10749 } 10750 } 10751 } 10752 10753 TargetLoweringBase::finalizeLowering(MF); 10754 } 10755 10756 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10757 KnownBits &Known, 10758 const APInt &DemandedElts, 10759 const SelectionDAG &DAG, 10760 unsigned Depth) const { 10761 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10762 DAG, Depth); 10763 10764 // Set the high bits to zero based on the maximum allowed scratch size per 10765 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10766 // calculation won't overflow, so assume the sign bit is never set. 10767 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10768 } 10769 10770 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10771 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10772 const Align CacheLineAlign = Align(64); 10773 10774 // Pre-GFX10 target did not benefit from loop alignment 10775 if (!ML || DisableLoopAlignment || 10776 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10777 getSubtarget()->hasInstFwdPrefetchBug()) 10778 return PrefAlign; 10779 10780 // On GFX10 I$ is 4 x 64 bytes cache lines. 10781 // By default prefetcher keeps one cache line behind and reads two ahead. 10782 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10783 // behind and one ahead. 10784 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10785 // If loop fits 64 bytes it always spans no more than two cache lines and 10786 // does not need an alignment. 10787 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10788 // Else if loop is less or equal 192 bytes we need two lines behind. 10789 10790 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10791 const MachineBasicBlock *Header = ML->getHeader(); 10792 if (Header->getAlignment() != PrefAlign) 10793 return Header->getAlignment(); // Already processed. 10794 10795 unsigned LoopSize = 0; 10796 for (const MachineBasicBlock *MBB : ML->blocks()) { 10797 // If inner loop block is aligned assume in average half of the alignment 10798 // size to be added as nops. 10799 if (MBB != Header) 10800 LoopSize += MBB->getAlignment().value() / 2; 10801 10802 for (const MachineInstr &MI : *MBB) { 10803 LoopSize += TII->getInstSizeInBytes(MI); 10804 if (LoopSize > 192) 10805 return PrefAlign; 10806 } 10807 } 10808 10809 if (LoopSize <= 64) 10810 return PrefAlign; 10811 10812 if (LoopSize <= 128) 10813 return CacheLineAlign; 10814 10815 // If any of parent loops is surrounded by prefetch instructions do not 10816 // insert new for inner loop, which would reset parent's settings. 10817 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10818 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10819 auto I = Exit->getFirstNonDebugInstr(); 10820 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10821 return CacheLineAlign; 10822 } 10823 } 10824 10825 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10826 MachineBasicBlock *Exit = ML->getExitBlock(); 10827 10828 if (Pre && Exit) { 10829 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10830 TII->get(AMDGPU::S_INST_PREFETCH)) 10831 .addImm(1); // prefetch 2 lines behind PC 10832 10833 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10834 TII->get(AMDGPU::S_INST_PREFETCH)) 10835 .addImm(2); // prefetch 1 line behind PC 10836 } 10837 10838 return CacheLineAlign; 10839 } 10840 10841 LLVM_ATTRIBUTE_UNUSED 10842 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10843 assert(N->getOpcode() == ISD::CopyFromReg); 10844 do { 10845 // Follow the chain until we find an INLINEASM node. 10846 N = N->getOperand(0).getNode(); 10847 if (N->getOpcode() == ISD::INLINEASM || 10848 N->getOpcode() == ISD::INLINEASM_BR) 10849 return true; 10850 } while (N->getOpcode() == ISD::CopyFromReg); 10851 return false; 10852 } 10853 10854 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10855 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10856 { 10857 switch (N->getOpcode()) { 10858 case ISD::CopyFromReg: 10859 { 10860 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10861 const MachineFunction * MF = FLI->MF; 10862 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10863 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10864 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10865 unsigned Reg = R->getReg(); 10866 if (Register::isPhysicalRegister(Reg)) 10867 return !TRI.isSGPRReg(MRI, Reg); 10868 10869 if (MRI.isLiveIn(Reg)) { 10870 // workitem.id.x workitem.id.y workitem.id.z 10871 // Any VGPR formal argument is also considered divergent 10872 if (!TRI.isSGPRReg(MRI, Reg)) 10873 return true; 10874 // Formal arguments of non-entry functions 10875 // are conservatively considered divergent 10876 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10877 return true; 10878 return false; 10879 } 10880 const Value *V = FLI->getValueFromVirtualReg(Reg); 10881 if (V) 10882 return KDA->isDivergent(V); 10883 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10884 return !TRI.isSGPRReg(MRI, Reg); 10885 } 10886 break; 10887 case ISD::LOAD: { 10888 const LoadSDNode *L = cast<LoadSDNode>(N); 10889 unsigned AS = L->getAddressSpace(); 10890 // A flat load may access private memory. 10891 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10892 } break; 10893 case ISD::CALLSEQ_END: 10894 return true; 10895 break; 10896 case ISD::INTRINSIC_WO_CHAIN: 10897 { 10898 10899 } 10900 return AMDGPU::isIntrinsicSourceOfDivergence( 10901 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10902 case ISD::INTRINSIC_W_CHAIN: 10903 return AMDGPU::isIntrinsicSourceOfDivergence( 10904 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10905 } 10906 return false; 10907 } 10908 10909 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10910 EVT VT) const { 10911 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10912 case MVT::f32: 10913 return hasFP32Denormals(DAG.getMachineFunction()); 10914 case MVT::f64: 10915 case MVT::f16: 10916 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10917 default: 10918 return false; 10919 } 10920 } 10921 10922 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10923 const SelectionDAG &DAG, 10924 bool SNaN, 10925 unsigned Depth) const { 10926 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10927 const MachineFunction &MF = DAG.getMachineFunction(); 10928 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10929 10930 if (Info->getMode().DX10Clamp) 10931 return true; // Clamped to 0. 10932 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10933 } 10934 10935 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10936 SNaN, Depth); 10937 } 10938 10939 TargetLowering::AtomicExpansionKind 10940 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10941 switch (RMW->getOperation()) { 10942 case AtomicRMWInst::FAdd: { 10943 Type *Ty = RMW->getType(); 10944 10945 // We don't have a way to support 16-bit atomics now, so just leave them 10946 // as-is. 10947 if (Ty->isHalfTy()) 10948 return AtomicExpansionKind::None; 10949 10950 if (!Ty->isFloatTy()) 10951 return AtomicExpansionKind::CmpXChg; 10952 10953 // TODO: Do have these for flat. Older targets also had them for buffers. 10954 unsigned AS = RMW->getPointerAddressSpace(); 10955 10956 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10957 return RMW->use_empty() ? AtomicExpansionKind::None : 10958 AtomicExpansionKind::CmpXChg; 10959 } 10960 10961 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10962 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10963 } 10964 default: 10965 break; 10966 } 10967 10968 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10969 } 10970 10971 const TargetRegisterClass * 10972 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10973 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10974 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10975 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10976 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10977 : &AMDGPU::SReg_32RegClass; 10978 if (!TRI->isSGPRClass(RC) && !isDivergent) 10979 return TRI->getEquivalentSGPRClass(RC); 10980 else if (TRI->isSGPRClass(RC) && isDivergent) 10981 return TRI->getEquivalentVGPRClass(RC); 10982 10983 return RC; 10984 } 10985 10986 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 10987 unsigned WaveSize) { 10988 // FIXME: We asssume we never cast the mask results of a control flow 10989 // intrinsic. 10990 // Early exit if the type won't be consistent as a compile time hack. 10991 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 10992 if (!IT || IT->getBitWidth() != WaveSize) 10993 return false; 10994 10995 if (!isa<Instruction>(V)) 10996 return false; 10997 if (!Visited.insert(V).second) 10998 return false; 10999 bool Result = false; 11000 for (auto U : V->users()) { 11001 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11002 if (V == U->getOperand(1)) { 11003 switch (Intrinsic->getIntrinsicID()) { 11004 default: 11005 Result = false; 11006 break; 11007 case Intrinsic::amdgcn_if_break: 11008 case Intrinsic::amdgcn_if: 11009 case Intrinsic::amdgcn_else: 11010 Result = true; 11011 break; 11012 } 11013 } 11014 if (V == U->getOperand(0)) { 11015 switch (Intrinsic->getIntrinsicID()) { 11016 default: 11017 Result = false; 11018 break; 11019 case Intrinsic::amdgcn_end_cf: 11020 case Intrinsic::amdgcn_loop: 11021 Result = true; 11022 break; 11023 } 11024 } 11025 } else { 11026 Result = hasCFUser(U, Visited, WaveSize); 11027 } 11028 if (Result) 11029 break; 11030 } 11031 return Result; 11032 } 11033 11034 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11035 const Value *V) const { 11036 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 11037 switch (Intrinsic->getIntrinsicID()) { 11038 default: 11039 return false; 11040 case Intrinsic::amdgcn_if_break: 11041 return true; 11042 } 11043 } 11044 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 11045 if (const IntrinsicInst *Intrinsic = 11046 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 11047 switch (Intrinsic->getIntrinsicID()) { 11048 default: 11049 return false; 11050 case Intrinsic::amdgcn_if: 11051 case Intrinsic::amdgcn_else: { 11052 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 11053 if (Indices.size() == 1 && Indices[0] == 1) { 11054 return true; 11055 } 11056 } 11057 } 11058 } 11059 } 11060 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11061 if (isa<InlineAsm>(CI->getCalledValue())) { 11062 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11063 ImmutableCallSite CS(CI); 11064 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11065 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 11066 for (auto &TC : TargetConstraints) { 11067 if (TC.Type == InlineAsm::isOutput) { 11068 ComputeConstraintToUse(TC, SDValue()); 11069 unsigned AssignedReg; 11070 const TargetRegisterClass *RC; 11071 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11072 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11073 if (RC) { 11074 MachineRegisterInfo &MRI = MF.getRegInfo(); 11075 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11076 return true; 11077 else if (SIRI->isSGPRClass(RC)) 11078 return true; 11079 } 11080 } 11081 } 11082 } 11083 } 11084 SmallPtrSet<const Value *, 16> Visited; 11085 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11086 } 11087