1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #if defined(_MSC_VER) || defined(__MINGW32__) 15 // Provide M_PI. 16 #define _USE_MATH_DEFINES 17 #endif 18 19 #include "SIISelLowering.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "SIDefines.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.h" 28 #include "Utils/AMDGPUBaseInfo.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/BitVector.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> DisableLoopAlignment( 94 "amdgpu-disable-loop-alignment", 95 cl::desc("Do not align and prefetch loops"), 96 cl::init(false)); 97 98 static bool hasFP32Denormals(const MachineFunction &MF) { 99 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 100 return Info->getMode().allFP32Denormals(); 101 } 102 103 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().allFP64FP16Denormals(); 106 } 107 108 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 109 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 110 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 111 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 112 return AMDGPU::SGPR0 + Reg; 113 } 114 } 115 llvm_unreachable("Cannot allocate sgpr"); 116 } 117 118 SITargetLowering::SITargetLowering(const TargetMachine &TM, 119 const GCNSubtarget &STI) 120 : AMDGPUTargetLowering(TM, STI), 121 Subtarget(&STI) { 122 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 123 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 124 125 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 126 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 127 128 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 129 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 130 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 131 132 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 133 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 134 135 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 136 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 137 138 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 139 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 140 141 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 142 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 143 144 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 145 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 146 147 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 148 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 149 150 if (Subtarget->has16BitInsts()) { 151 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 152 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 153 154 // Unless there are also VOP3P operations, not operations are really legal. 155 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 156 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 157 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 158 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 159 } 160 161 if (Subtarget->hasMAIInsts()) { 162 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 163 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 164 } 165 166 computeRegisterProperties(Subtarget->getRegisterInfo()); 167 168 // The boolean content concept here is too inflexible. Compares only ever 169 // really produce a 1-bit result. Any copy/extend from these will turn into a 170 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 171 // it's what most targets use. 172 setBooleanContents(ZeroOrOneBooleanContent); 173 setBooleanVectorContents(ZeroOrOneBooleanContent); 174 175 // We need to custom lower vector stores from local memory 176 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 177 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 178 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 179 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 180 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 181 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 182 setOperationAction(ISD::LOAD, MVT::i1, Custom); 183 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 184 185 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 186 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 187 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 188 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 189 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 190 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 191 setOperationAction(ISD::STORE, MVT::i1, Custom); 192 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 193 194 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 195 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 197 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 198 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 199 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 200 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 201 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 202 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 203 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 204 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 205 206 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 208 209 setOperationAction(ISD::SELECT, MVT::i1, Promote); 210 setOperationAction(ISD::SELECT, MVT::i64, Custom); 211 setOperationAction(ISD::SELECT, MVT::f64, Promote); 212 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 213 214 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 216 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 217 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 218 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 219 220 setOperationAction(ISD::SETCC, MVT::i1, Promote); 221 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 222 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 224 225 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 227 228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 236 237 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 238 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 239 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 240 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 241 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 242 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 243 244 setOperationAction(ISD::UADDO, MVT::i32, Legal); 245 setOperationAction(ISD::USUBO, MVT::i32, Legal); 246 247 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 248 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 249 250 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 251 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 252 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 253 254 #if 0 255 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 256 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 257 #endif 258 259 // We only support LOAD/STORE and vector manipulation ops for vectors 260 // with > 4 elements. 261 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 262 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 263 MVT::v32i32, MVT::v32f32 }) { 264 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 265 switch (Op) { 266 case ISD::LOAD: 267 case ISD::STORE: 268 case ISD::BUILD_VECTOR: 269 case ISD::BITCAST: 270 case ISD::EXTRACT_VECTOR_ELT: 271 case ISD::INSERT_VECTOR_ELT: 272 case ISD::INSERT_SUBVECTOR: 273 case ISD::EXTRACT_SUBVECTOR: 274 case ISD::SCALAR_TO_VECTOR: 275 break; 276 case ISD::CONCAT_VECTORS: 277 setOperationAction(Op, VT, Custom); 278 break; 279 default: 280 setOperationAction(Op, VT, Expand); 281 break; 282 } 283 } 284 } 285 286 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 287 288 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 289 // is expanded to avoid having two separate loops in case the index is a VGPR. 290 291 // Most operations are naturally 32-bit vector operations. We only support 292 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 293 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 294 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 295 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 296 297 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 298 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 299 300 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 301 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 302 303 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 305 } 306 307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 311 312 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 314 315 // Avoid stack access for these. 316 // TODO: Generalize to more vector types. 317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 321 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 331 332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 336 337 // Deal with vec3 vector operations when widened to vec4. 338 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 342 343 // Deal with vec5 vector operations when widened to vec8. 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 348 349 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 350 // and output demarshalling 351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 353 354 // We can't return success/failure, only the old value, 355 // let LLVM add the comparison 356 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 358 359 if (Subtarget->hasFlatAddressSpace()) { 360 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 361 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 362 } 363 364 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 365 366 // FIXME: This should be narrowed to i32, but that only happens if i64 is 367 // illegal. 368 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 369 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 370 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 371 372 // On SI this is s_memtime and s_memrealtime on VI. 373 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 374 setOperationAction(ISD::TRAP, MVT::Other, Custom); 375 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 376 377 if (Subtarget->has16BitInsts()) { 378 setOperationAction(ISD::FPOW, MVT::f16, Promote); 379 setOperationAction(ISD::FLOG, MVT::f16, Custom); 380 setOperationAction(ISD::FEXP, MVT::f16, Custom); 381 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 382 } 383 384 // v_mad_f32 does not support denormals. We report it as unconditionally 385 // legal, and the context where it is formed will disallow it when fp32 386 // denormals are enabled. 387 setOperationAction(ISD::FMAD, MVT::f32, Legal); 388 389 if (!Subtarget->hasBFI()) { 390 // fcopysign can be done in a single instruction with BFI. 391 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 392 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 393 } 394 395 if (!Subtarget->hasBCNT(32)) 396 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 397 398 if (!Subtarget->hasBCNT(64)) 399 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 400 401 if (Subtarget->hasFFBH()) 402 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 403 404 if (Subtarget->hasFFBL()) 405 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 406 407 // We only really have 32-bit BFE instructions (and 16-bit on VI). 408 // 409 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 410 // effort to match them now. We want this to be false for i64 cases when the 411 // extraction isn't restricted to the upper or lower half. Ideally we would 412 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 413 // span the midpoint are probably relatively rare, so don't worry about them 414 // for now. 415 if (Subtarget->hasBFE()) 416 setHasExtractBitsInsn(true); 417 418 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 419 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 420 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 421 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 422 423 424 // These are really only legal for ieee_mode functions. We should be avoiding 425 // them for functions that don't have ieee_mode enabled, so just say they are 426 // legal. 427 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 428 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 429 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 430 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 431 432 433 if (Subtarget->haveRoundOpsF64()) { 434 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 435 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 436 setOperationAction(ISD::FRINT, MVT::f64, Legal); 437 } else { 438 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 439 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 440 setOperationAction(ISD::FRINT, MVT::f64, Custom); 441 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 442 } 443 444 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 445 446 setOperationAction(ISD::FSIN, MVT::f32, Custom); 447 setOperationAction(ISD::FCOS, MVT::f32, Custom); 448 setOperationAction(ISD::FDIV, MVT::f32, Custom); 449 setOperationAction(ISD::FDIV, MVT::f64, Custom); 450 451 if (Subtarget->has16BitInsts()) { 452 setOperationAction(ISD::Constant, MVT::i16, Legal); 453 454 setOperationAction(ISD::SMIN, MVT::i16, Legal); 455 setOperationAction(ISD::SMAX, MVT::i16, Legal); 456 457 setOperationAction(ISD::UMIN, MVT::i16, Legal); 458 setOperationAction(ISD::UMAX, MVT::i16, Legal); 459 460 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 461 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 462 463 setOperationAction(ISD::ROTR, MVT::i16, Promote); 464 setOperationAction(ISD::ROTL, MVT::i16, Promote); 465 466 setOperationAction(ISD::SDIV, MVT::i16, Promote); 467 setOperationAction(ISD::UDIV, MVT::i16, Promote); 468 setOperationAction(ISD::SREM, MVT::i16, Promote); 469 setOperationAction(ISD::UREM, MVT::i16, Promote); 470 471 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 472 473 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 475 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 477 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 478 479 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 480 481 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 482 483 setOperationAction(ISD::LOAD, MVT::i16, Custom); 484 485 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 486 487 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 488 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 489 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 490 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 491 492 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 493 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 494 495 // F16 - Constant Actions. 496 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 497 498 // F16 - Load/Store Actions. 499 setOperationAction(ISD::LOAD, MVT::f16, Promote); 500 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 501 setOperationAction(ISD::STORE, MVT::f16, Promote); 502 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 503 504 // F16 - VOP1 Actions. 505 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 506 setOperationAction(ISD::FCOS, MVT::f16, Custom); 507 setOperationAction(ISD::FSIN, MVT::f16, Custom); 508 509 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 510 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 511 512 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 513 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 514 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 515 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 516 setOperationAction(ISD::FROUND, MVT::f16, Custom); 517 518 // F16 - VOP2 Actions. 519 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 520 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 521 522 setOperationAction(ISD::FDIV, MVT::f16, Custom); 523 524 // F16 - VOP3 Actions. 525 setOperationAction(ISD::FMA, MVT::f16, Legal); 526 if (STI.hasMadF16()) 527 setOperationAction(ISD::FMAD, MVT::f16, Legal); 528 529 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 530 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 531 switch (Op) { 532 case ISD::LOAD: 533 case ISD::STORE: 534 case ISD::BUILD_VECTOR: 535 case ISD::BITCAST: 536 case ISD::EXTRACT_VECTOR_ELT: 537 case ISD::INSERT_VECTOR_ELT: 538 case ISD::INSERT_SUBVECTOR: 539 case ISD::EXTRACT_SUBVECTOR: 540 case ISD::SCALAR_TO_VECTOR: 541 break; 542 case ISD::CONCAT_VECTORS: 543 setOperationAction(Op, VT, Custom); 544 break; 545 default: 546 setOperationAction(Op, VT, Expand); 547 break; 548 } 549 } 550 } 551 552 // v_perm_b32 can handle either of these. 553 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 554 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 555 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 556 557 // XXX - Do these do anything? Vector constants turn into build_vector. 558 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 559 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 560 561 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 562 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 563 564 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 565 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 566 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 567 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 568 569 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 571 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 572 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 573 574 setOperationAction(ISD::AND, MVT::v2i16, Promote); 575 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 576 setOperationAction(ISD::OR, MVT::v2i16, Promote); 577 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 578 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 579 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 580 581 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 582 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 583 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 584 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 585 586 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 587 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 588 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 589 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 590 591 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 592 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 593 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 594 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 595 596 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 597 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 598 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 599 600 if (!Subtarget->hasVOP3PInsts()) { 601 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 602 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 603 } 604 605 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 606 // This isn't really legal, but this avoids the legalizer unrolling it (and 607 // allows matching fneg (fabs x) patterns) 608 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 609 610 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 611 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 612 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 613 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 614 615 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 616 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 617 618 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 619 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 620 } 621 622 if (Subtarget->hasVOP3PInsts()) { 623 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 624 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 625 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 626 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 627 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 628 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 629 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 630 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 631 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 632 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 633 634 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 635 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 636 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 637 638 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 639 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 640 641 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 642 643 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 644 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 645 646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 647 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 648 649 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 650 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 651 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 652 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 653 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 654 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 655 656 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 657 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 658 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 659 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 660 661 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 662 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 663 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 664 665 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 666 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 667 668 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 669 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 670 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 671 672 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 673 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 674 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 675 } 676 677 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 678 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 679 680 if (Subtarget->has16BitInsts()) { 681 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 682 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 683 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 684 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 685 } else { 686 // Legalization hack. 687 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 688 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 689 690 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 691 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 692 } 693 694 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 695 setOperationAction(ISD::SELECT, VT, Custom); 696 } 697 698 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 699 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 700 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 701 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 702 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 703 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 704 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 705 706 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 707 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 708 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 709 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 710 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 711 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 712 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 713 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 714 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 715 716 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 717 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 718 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 719 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 720 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 721 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 722 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 723 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 724 725 setTargetDAGCombine(ISD::ADD); 726 setTargetDAGCombine(ISD::ADDCARRY); 727 setTargetDAGCombine(ISD::SUB); 728 setTargetDAGCombine(ISD::SUBCARRY); 729 setTargetDAGCombine(ISD::FADD); 730 setTargetDAGCombine(ISD::FSUB); 731 setTargetDAGCombine(ISD::FMINNUM); 732 setTargetDAGCombine(ISD::FMAXNUM); 733 setTargetDAGCombine(ISD::FMINNUM_IEEE); 734 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 735 setTargetDAGCombine(ISD::FMA); 736 setTargetDAGCombine(ISD::SMIN); 737 setTargetDAGCombine(ISD::SMAX); 738 setTargetDAGCombine(ISD::UMIN); 739 setTargetDAGCombine(ISD::UMAX); 740 setTargetDAGCombine(ISD::SETCC); 741 setTargetDAGCombine(ISD::AND); 742 setTargetDAGCombine(ISD::OR); 743 setTargetDAGCombine(ISD::XOR); 744 setTargetDAGCombine(ISD::SINT_TO_FP); 745 setTargetDAGCombine(ISD::UINT_TO_FP); 746 setTargetDAGCombine(ISD::FCANONICALIZE); 747 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 748 setTargetDAGCombine(ISD::ZERO_EXTEND); 749 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 750 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 751 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 752 753 // All memory operations. Some folding on the pointer operand is done to help 754 // matching the constant offsets in the addressing modes. 755 setTargetDAGCombine(ISD::LOAD); 756 setTargetDAGCombine(ISD::STORE); 757 setTargetDAGCombine(ISD::ATOMIC_LOAD); 758 setTargetDAGCombine(ISD::ATOMIC_STORE); 759 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 760 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 761 setTargetDAGCombine(ISD::ATOMIC_SWAP); 762 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 763 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 764 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 765 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 766 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 767 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 768 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 769 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 770 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 771 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 772 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 773 774 setSchedulingPreference(Sched::RegPressure); 775 } 776 777 const GCNSubtarget *SITargetLowering::getSubtarget() const { 778 return Subtarget; 779 } 780 781 //===----------------------------------------------------------------------===// 782 // TargetLowering queries 783 //===----------------------------------------------------------------------===// 784 785 // v_mad_mix* support a conversion from f16 to f32. 786 // 787 // There is only one special case when denormals are enabled we don't currently, 788 // where this is OK to use. 789 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 790 EVT DestVT, EVT SrcVT) const { 791 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 792 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 793 DestVT.getScalarType() == MVT::f32 && 794 SrcVT.getScalarType() == MVT::f16 && 795 // TODO: This probably only requires no input flushing? 796 !hasFP32Denormals(DAG.getMachineFunction()); 797 } 798 799 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 800 // SI has some legal vector types, but no legal vector operations. Say no 801 // shuffles are legal in order to prefer scalarizing some vector operations. 802 return false; 803 } 804 805 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 806 CallingConv::ID CC, 807 EVT VT) const { 808 if (CC == CallingConv::AMDGPU_KERNEL) 809 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 810 811 if (VT.isVector()) { 812 EVT ScalarVT = VT.getScalarType(); 813 unsigned Size = ScalarVT.getSizeInBits(); 814 if (Size == 32) 815 return ScalarVT.getSimpleVT(); 816 817 if (Size > 32) 818 return MVT::i32; 819 820 if (Size == 16 && Subtarget->has16BitInsts()) 821 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 822 } else if (VT.getSizeInBits() > 32) 823 return MVT::i32; 824 825 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 826 } 827 828 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 829 CallingConv::ID CC, 830 EVT VT) const { 831 if (CC == CallingConv::AMDGPU_KERNEL) 832 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 833 834 if (VT.isVector()) { 835 unsigned NumElts = VT.getVectorNumElements(); 836 EVT ScalarVT = VT.getScalarType(); 837 unsigned Size = ScalarVT.getSizeInBits(); 838 839 if (Size == 32) 840 return NumElts; 841 842 if (Size > 32) 843 return NumElts * ((Size + 31) / 32); 844 845 if (Size == 16 && Subtarget->has16BitInsts()) 846 return (NumElts + 1) / 2; 847 } else if (VT.getSizeInBits() > 32) 848 return (VT.getSizeInBits() + 31) / 32; 849 850 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 851 } 852 853 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 854 LLVMContext &Context, CallingConv::ID CC, 855 EVT VT, EVT &IntermediateVT, 856 unsigned &NumIntermediates, MVT &RegisterVT) const { 857 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 858 unsigned NumElts = VT.getVectorNumElements(); 859 EVT ScalarVT = VT.getScalarType(); 860 unsigned Size = ScalarVT.getSizeInBits(); 861 if (Size == 32) { 862 RegisterVT = ScalarVT.getSimpleVT(); 863 IntermediateVT = RegisterVT; 864 NumIntermediates = NumElts; 865 return NumIntermediates; 866 } 867 868 if (Size > 32) { 869 RegisterVT = MVT::i32; 870 IntermediateVT = RegisterVT; 871 NumIntermediates = NumElts * ((Size + 31) / 32); 872 return NumIntermediates; 873 } 874 875 // FIXME: We should fix the ABI to be the same on targets without 16-bit 876 // support, but unless we can properly handle 3-vectors, it will be still be 877 // inconsistent. 878 if (Size == 16 && Subtarget->has16BitInsts()) { 879 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 880 IntermediateVT = RegisterVT; 881 NumIntermediates = (NumElts + 1) / 2; 882 return NumIntermediates; 883 } 884 } 885 886 return TargetLowering::getVectorTypeBreakdownForCallingConv( 887 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 888 } 889 890 // Peek through TFE struct returns to only use the data size. 891 static EVT memVTFromImageReturn(Type *Ty) { 892 auto *ST = dyn_cast<StructType>(Ty); 893 if (!ST) 894 return EVT::getEVT(Ty, true); 895 896 // Some intrinsics return an aggregate type - special case to work out the 897 // correct memVT. 898 // 899 // Only limited forms of aggregate type currently expected. 900 if (ST->getNumContainedTypes() != 2 || 901 !ST->getContainedType(1)->isIntegerTy(32)) 902 return EVT(); 903 return EVT::getEVT(ST->getContainedType(0)); 904 } 905 906 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 907 const CallInst &CI, 908 MachineFunction &MF, 909 unsigned IntrID) const { 910 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 911 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 912 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 913 (Intrinsic::ID)IntrID); 914 if (Attr.hasFnAttribute(Attribute::ReadNone)) 915 return false; 916 917 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 918 919 if (RsrcIntr->IsImage) { 920 Info.ptrVal = MFI->getImagePSV( 921 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 922 CI.getArgOperand(RsrcIntr->RsrcArg)); 923 Info.align.reset(); 924 } else { 925 Info.ptrVal = MFI->getBufferPSV( 926 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 927 CI.getArgOperand(RsrcIntr->RsrcArg)); 928 } 929 930 Info.flags = MachineMemOperand::MODereferenceable; 931 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 932 Info.opc = ISD::INTRINSIC_W_CHAIN; 933 // TODO: Account for dmask reducing loaded size. 934 Info.memVT = memVTFromImageReturn(CI.getType()); 935 Info.flags |= MachineMemOperand::MOLoad; 936 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 937 Info.opc = ISD::INTRINSIC_VOID; 938 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 939 Info.flags |= MachineMemOperand::MOStore; 940 } else { 941 // Atomic 942 Info.opc = ISD::INTRINSIC_W_CHAIN; 943 Info.memVT = MVT::getVT(CI.getType()); 944 Info.flags = MachineMemOperand::MOLoad | 945 MachineMemOperand::MOStore | 946 MachineMemOperand::MODereferenceable; 947 948 // XXX - Should this be volatile without known ordering? 949 Info.flags |= MachineMemOperand::MOVolatile; 950 } 951 return true; 952 } 953 954 switch (IntrID) { 955 case Intrinsic::amdgcn_atomic_inc: 956 case Intrinsic::amdgcn_atomic_dec: 957 case Intrinsic::amdgcn_ds_ordered_add: 958 case Intrinsic::amdgcn_ds_ordered_swap: 959 case Intrinsic::amdgcn_ds_fadd: 960 case Intrinsic::amdgcn_ds_fmin: 961 case Intrinsic::amdgcn_ds_fmax: { 962 Info.opc = ISD::INTRINSIC_W_CHAIN; 963 Info.memVT = MVT::getVT(CI.getType()); 964 Info.ptrVal = CI.getOperand(0); 965 Info.align.reset(); 966 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 967 968 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 969 if (!Vol->isZero()) 970 Info.flags |= MachineMemOperand::MOVolatile; 971 972 return true; 973 } 974 case Intrinsic::amdgcn_buffer_atomic_fadd: { 975 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 976 977 Info.opc = ISD::INTRINSIC_VOID; 978 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 979 Info.ptrVal = MFI->getBufferPSV( 980 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 981 CI.getArgOperand(1)); 982 Info.align.reset(); 983 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 984 985 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 986 if (!Vol || !Vol->isZero()) 987 Info.flags |= MachineMemOperand::MOVolatile; 988 989 return true; 990 } 991 case Intrinsic::amdgcn_global_atomic_fadd: { 992 Info.opc = ISD::INTRINSIC_VOID; 993 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 994 ->getPointerElementType()); 995 Info.ptrVal = CI.getOperand(0); 996 Info.align.reset(); 997 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 998 999 return true; 1000 } 1001 case Intrinsic::amdgcn_ds_append: 1002 case Intrinsic::amdgcn_ds_consume: { 1003 Info.opc = ISD::INTRINSIC_W_CHAIN; 1004 Info.memVT = MVT::getVT(CI.getType()); 1005 Info.ptrVal = CI.getOperand(0); 1006 Info.align.reset(); 1007 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1008 1009 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1010 if (!Vol->isZero()) 1011 Info.flags |= MachineMemOperand::MOVolatile; 1012 1013 return true; 1014 } 1015 case Intrinsic::amdgcn_ds_gws_init: 1016 case Intrinsic::amdgcn_ds_gws_barrier: 1017 case Intrinsic::amdgcn_ds_gws_sema_v: 1018 case Intrinsic::amdgcn_ds_gws_sema_br: 1019 case Intrinsic::amdgcn_ds_gws_sema_p: 1020 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1021 Info.opc = ISD::INTRINSIC_VOID; 1022 1023 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1024 Info.ptrVal = 1025 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1026 1027 // This is an abstract access, but we need to specify a type and size. 1028 Info.memVT = MVT::i32; 1029 Info.size = 4; 1030 Info.align = Align(4); 1031 1032 Info.flags = MachineMemOperand::MOStore; 1033 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1034 Info.flags = MachineMemOperand::MOLoad; 1035 return true; 1036 } 1037 default: 1038 return false; 1039 } 1040 } 1041 1042 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1043 SmallVectorImpl<Value*> &Ops, 1044 Type *&AccessTy) const { 1045 switch (II->getIntrinsicID()) { 1046 case Intrinsic::amdgcn_atomic_inc: 1047 case Intrinsic::amdgcn_atomic_dec: 1048 case Intrinsic::amdgcn_ds_ordered_add: 1049 case Intrinsic::amdgcn_ds_ordered_swap: 1050 case Intrinsic::amdgcn_ds_fadd: 1051 case Intrinsic::amdgcn_ds_fmin: 1052 case Intrinsic::amdgcn_ds_fmax: { 1053 Value *Ptr = II->getArgOperand(0); 1054 AccessTy = II->getType(); 1055 Ops.push_back(Ptr); 1056 return true; 1057 } 1058 default: 1059 return false; 1060 } 1061 } 1062 1063 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1064 if (!Subtarget->hasFlatInstOffsets()) { 1065 // Flat instructions do not have offsets, and only have the register 1066 // address. 1067 return AM.BaseOffs == 0 && AM.Scale == 0; 1068 } 1069 1070 return AM.Scale == 0 && 1071 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1072 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1073 /*Signed=*/false)); 1074 } 1075 1076 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1077 if (Subtarget->hasFlatGlobalInsts()) 1078 return AM.Scale == 0 && 1079 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1080 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1081 /*Signed=*/true)); 1082 1083 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1084 // Assume the we will use FLAT for all global memory accesses 1085 // on VI. 1086 // FIXME: This assumption is currently wrong. On VI we still use 1087 // MUBUF instructions for the r + i addressing mode. As currently 1088 // implemented, the MUBUF instructions only work on buffer < 4GB. 1089 // It may be possible to support > 4GB buffers with MUBUF instructions, 1090 // by setting the stride value in the resource descriptor which would 1091 // increase the size limit to (stride * 4GB). However, this is risky, 1092 // because it has never been validated. 1093 return isLegalFlatAddressingMode(AM); 1094 } 1095 1096 return isLegalMUBUFAddressingMode(AM); 1097 } 1098 1099 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1100 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1101 // additionally can do r + r + i with addr64. 32-bit has more addressing 1102 // mode options. Depending on the resource constant, it can also do 1103 // (i64 r0) + (i32 r1) * (i14 i). 1104 // 1105 // Private arrays end up using a scratch buffer most of the time, so also 1106 // assume those use MUBUF instructions. Scratch loads / stores are currently 1107 // implemented as mubuf instructions with offen bit set, so slightly 1108 // different than the normal addr64. 1109 if (!isUInt<12>(AM.BaseOffs)) 1110 return false; 1111 1112 // FIXME: Since we can split immediate into soffset and immediate offset, 1113 // would it make sense to allow any immediate? 1114 1115 switch (AM.Scale) { 1116 case 0: // r + i or just i, depending on HasBaseReg. 1117 return true; 1118 case 1: 1119 return true; // We have r + r or r + i. 1120 case 2: 1121 if (AM.HasBaseReg) { 1122 // Reject 2 * r + r. 1123 return false; 1124 } 1125 1126 // Allow 2 * r as r + r 1127 // Or 2 * r + i is allowed as r + r + i. 1128 return true; 1129 default: // Don't allow n * r 1130 return false; 1131 } 1132 } 1133 1134 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1135 const AddrMode &AM, Type *Ty, 1136 unsigned AS, Instruction *I) const { 1137 // No global is ever allowed as a base. 1138 if (AM.BaseGV) 1139 return false; 1140 1141 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1142 return isLegalGlobalAddressingMode(AM); 1143 1144 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1145 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1146 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1147 // If the offset isn't a multiple of 4, it probably isn't going to be 1148 // correctly aligned. 1149 // FIXME: Can we get the real alignment here? 1150 if (AM.BaseOffs % 4 != 0) 1151 return isLegalMUBUFAddressingMode(AM); 1152 1153 // There are no SMRD extloads, so if we have to do a small type access we 1154 // will use a MUBUF load. 1155 // FIXME?: We also need to do this if unaligned, but we don't know the 1156 // alignment here. 1157 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1158 return isLegalGlobalAddressingMode(AM); 1159 1160 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1161 // SMRD instructions have an 8-bit, dword offset on SI. 1162 if (!isUInt<8>(AM.BaseOffs / 4)) 1163 return false; 1164 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1165 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1166 // in 8-bits, it can use a smaller encoding. 1167 if (!isUInt<32>(AM.BaseOffs / 4)) 1168 return false; 1169 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1170 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1171 if (!isUInt<20>(AM.BaseOffs)) 1172 return false; 1173 } else 1174 llvm_unreachable("unhandled generation"); 1175 1176 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1177 return true; 1178 1179 if (AM.Scale == 1 && AM.HasBaseReg) 1180 return true; 1181 1182 return false; 1183 1184 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1185 return isLegalMUBUFAddressingMode(AM); 1186 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1187 AS == AMDGPUAS::REGION_ADDRESS) { 1188 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1189 // field. 1190 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1191 // an 8-bit dword offset but we don't know the alignment here. 1192 if (!isUInt<16>(AM.BaseOffs)) 1193 return false; 1194 1195 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1196 return true; 1197 1198 if (AM.Scale == 1 && AM.HasBaseReg) 1199 return true; 1200 1201 return false; 1202 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1203 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1204 // For an unknown address space, this usually means that this is for some 1205 // reason being used for pure arithmetic, and not based on some addressing 1206 // computation. We don't have instructions that compute pointers with any 1207 // addressing modes, so treat them as having no offset like flat 1208 // instructions. 1209 return isLegalFlatAddressingMode(AM); 1210 } else { 1211 llvm_unreachable("unhandled address space"); 1212 } 1213 } 1214 1215 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1216 const SelectionDAG &DAG) const { 1217 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1218 return (MemVT.getSizeInBits() <= 4 * 32); 1219 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1220 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1221 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1222 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1223 return (MemVT.getSizeInBits() <= 2 * 32); 1224 } 1225 return true; 1226 } 1227 1228 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1229 unsigned Size, unsigned AddrSpace, unsigned Align, 1230 MachineMemOperand::Flags Flags, bool *IsFast) const { 1231 if (IsFast) 1232 *IsFast = false; 1233 1234 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1235 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1236 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1237 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1238 // with adjacent offsets. 1239 bool AlignedBy4 = (Align % 4 == 0); 1240 if (IsFast) 1241 *IsFast = AlignedBy4; 1242 1243 return AlignedBy4; 1244 } 1245 1246 // FIXME: We have to be conservative here and assume that flat operations 1247 // will access scratch. If we had access to the IR function, then we 1248 // could determine if any private memory was used in the function. 1249 if (!Subtarget->hasUnalignedScratchAccess() && 1250 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1251 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1252 bool AlignedBy4 = Align >= 4; 1253 if (IsFast) 1254 *IsFast = AlignedBy4; 1255 1256 return AlignedBy4; 1257 } 1258 1259 if (Subtarget->hasUnalignedBufferAccess()) { 1260 // If we have an uniform constant load, it still requires using a slow 1261 // buffer instruction if unaligned. 1262 if (IsFast) { 1263 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1264 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1265 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1266 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1267 Align >= 4 : Align != 2; 1268 } 1269 1270 return true; 1271 } 1272 1273 // Smaller than dword value must be aligned. 1274 if (Size < 32) 1275 return false; 1276 1277 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1278 // byte-address are ignored, thus forcing Dword alignment. 1279 // This applies to private, global, and constant memory. 1280 if (IsFast) 1281 *IsFast = true; 1282 1283 return Size >= 32 && Align >= 4; 1284 } 1285 1286 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1287 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1288 bool *IsFast) const { 1289 if (IsFast) 1290 *IsFast = false; 1291 1292 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1293 // which isn't a simple VT. 1294 // Until MVT is extended to handle this, simply check for the size and 1295 // rely on the condition below: allow accesses if the size is a multiple of 4. 1296 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1297 VT.getStoreSize() > 16)) { 1298 return false; 1299 } 1300 1301 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1302 Align, Flags, IsFast); 1303 } 1304 1305 EVT SITargetLowering::getOptimalMemOpType( 1306 const MemOp &Op, const AttributeList &FuncAttributes) const { 1307 // FIXME: Should account for address space here. 1308 1309 // The default fallback uses the private pointer size as a guess for a type to 1310 // use. Make sure we switch these to 64-bit accesses. 1311 1312 if (Op.size() >= 16 && 1313 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1314 return MVT::v4i32; 1315 1316 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1317 return MVT::v2i32; 1318 1319 // Use the default. 1320 return MVT::Other; 1321 } 1322 1323 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1324 unsigned DestAS) const { 1325 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1326 } 1327 1328 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1329 const MemSDNode *MemNode = cast<MemSDNode>(N); 1330 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1331 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1332 return I && I->getMetadata("amdgpu.noclobber"); 1333 } 1334 1335 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1336 unsigned DestAS) const { 1337 // Flat -> private/local is a simple truncate. 1338 // Flat -> global is no-op 1339 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1340 return true; 1341 1342 return isNoopAddrSpaceCast(SrcAS, DestAS); 1343 } 1344 1345 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1346 const MemSDNode *MemNode = cast<MemSDNode>(N); 1347 1348 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1349 } 1350 1351 TargetLoweringBase::LegalizeTypeAction 1352 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1353 int NumElts = VT.getVectorNumElements(); 1354 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1355 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1356 return TargetLoweringBase::getPreferredVectorAction(VT); 1357 } 1358 1359 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1360 Type *Ty) const { 1361 // FIXME: Could be smarter if called for vector constants. 1362 return true; 1363 } 1364 1365 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1366 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1367 switch (Op) { 1368 case ISD::LOAD: 1369 case ISD::STORE: 1370 1371 // These operations are done with 32-bit instructions anyway. 1372 case ISD::AND: 1373 case ISD::OR: 1374 case ISD::XOR: 1375 case ISD::SELECT: 1376 // TODO: Extensions? 1377 return true; 1378 default: 1379 return false; 1380 } 1381 } 1382 1383 // SimplifySetCC uses this function to determine whether or not it should 1384 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1385 if (VT == MVT::i1 && Op == ISD::SETCC) 1386 return false; 1387 1388 return TargetLowering::isTypeDesirableForOp(Op, VT); 1389 } 1390 1391 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1392 const SDLoc &SL, 1393 SDValue Chain, 1394 uint64_t Offset) const { 1395 const DataLayout &DL = DAG.getDataLayout(); 1396 MachineFunction &MF = DAG.getMachineFunction(); 1397 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1398 1399 const ArgDescriptor *InputPtrReg; 1400 const TargetRegisterClass *RC; 1401 1402 std::tie(InputPtrReg, RC) 1403 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1404 1405 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1406 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1407 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1408 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1409 1410 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1411 } 1412 1413 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1414 const SDLoc &SL) const { 1415 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1416 FIRST_IMPLICIT); 1417 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1418 } 1419 1420 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1421 const SDLoc &SL, SDValue Val, 1422 bool Signed, 1423 const ISD::InputArg *Arg) const { 1424 // First, if it is a widened vector, narrow it. 1425 if (VT.isVector() && 1426 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1427 EVT NarrowedVT = 1428 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1429 VT.getVectorNumElements()); 1430 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1431 DAG.getConstant(0, SL, MVT::i32)); 1432 } 1433 1434 // Then convert the vector elements or scalar value. 1435 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1436 VT.bitsLT(MemVT)) { 1437 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1438 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1439 } 1440 1441 if (MemVT.isFloatingPoint()) 1442 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1443 else if (Signed) 1444 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1445 else 1446 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1447 1448 return Val; 1449 } 1450 1451 SDValue SITargetLowering::lowerKernargMemParameter( 1452 SelectionDAG &DAG, EVT VT, EVT MemVT, 1453 const SDLoc &SL, SDValue Chain, 1454 uint64_t Offset, unsigned Align, bool Signed, 1455 const ISD::InputArg *Arg) const { 1456 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1457 1458 // Try to avoid using an extload by loading earlier than the argument address, 1459 // and extracting the relevant bits. The load should hopefully be merged with 1460 // the previous argument. 1461 if (MemVT.getStoreSize() < 4 && Align < 4) { 1462 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1463 int64_t AlignDownOffset = alignDown(Offset, 4); 1464 int64_t OffsetDiff = Offset - AlignDownOffset; 1465 1466 EVT IntVT = MemVT.changeTypeToInteger(); 1467 1468 // TODO: If we passed in the base kernel offset we could have a better 1469 // alignment than 4, but we don't really need it. 1470 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1471 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1472 MachineMemOperand::MODereferenceable | 1473 MachineMemOperand::MOInvariant); 1474 1475 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1476 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1477 1478 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1479 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1480 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1481 1482 1483 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1484 } 1485 1486 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1487 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1488 MachineMemOperand::MODereferenceable | 1489 MachineMemOperand::MOInvariant); 1490 1491 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1492 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1493 } 1494 1495 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1496 const SDLoc &SL, SDValue Chain, 1497 const ISD::InputArg &Arg) const { 1498 MachineFunction &MF = DAG.getMachineFunction(); 1499 MachineFrameInfo &MFI = MF.getFrameInfo(); 1500 1501 if (Arg.Flags.isByVal()) { 1502 unsigned Size = Arg.Flags.getByValSize(); 1503 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1504 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1505 } 1506 1507 unsigned ArgOffset = VA.getLocMemOffset(); 1508 unsigned ArgSize = VA.getValVT().getStoreSize(); 1509 1510 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1511 1512 // Create load nodes to retrieve arguments from the stack. 1513 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1514 SDValue ArgValue; 1515 1516 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1517 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1518 MVT MemVT = VA.getValVT(); 1519 1520 switch (VA.getLocInfo()) { 1521 default: 1522 break; 1523 case CCValAssign::BCvt: 1524 MemVT = VA.getLocVT(); 1525 break; 1526 case CCValAssign::SExt: 1527 ExtType = ISD::SEXTLOAD; 1528 break; 1529 case CCValAssign::ZExt: 1530 ExtType = ISD::ZEXTLOAD; 1531 break; 1532 case CCValAssign::AExt: 1533 ExtType = ISD::EXTLOAD; 1534 break; 1535 } 1536 1537 ArgValue = DAG.getExtLoad( 1538 ExtType, SL, VA.getLocVT(), Chain, FIN, 1539 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1540 MemVT); 1541 return ArgValue; 1542 } 1543 1544 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1545 const SIMachineFunctionInfo &MFI, 1546 EVT VT, 1547 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1548 const ArgDescriptor *Reg; 1549 const TargetRegisterClass *RC; 1550 1551 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1552 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1553 } 1554 1555 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1556 CallingConv::ID CallConv, 1557 ArrayRef<ISD::InputArg> Ins, 1558 BitVector &Skipped, 1559 FunctionType *FType, 1560 SIMachineFunctionInfo *Info) { 1561 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1562 const ISD::InputArg *Arg = &Ins[I]; 1563 1564 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1565 "vector type argument should have been split"); 1566 1567 // First check if it's a PS input addr. 1568 if (CallConv == CallingConv::AMDGPU_PS && 1569 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1570 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1571 1572 // Inconveniently only the first part of the split is marked as isSplit, 1573 // so skip to the end. We only want to increment PSInputNum once for the 1574 // entire split argument. 1575 if (Arg->Flags.isSplit()) { 1576 while (!Arg->Flags.isSplitEnd()) { 1577 assert((!Arg->VT.isVector() || 1578 Arg->VT.getScalarSizeInBits() == 16) && 1579 "unexpected vector split in ps argument type"); 1580 if (!SkipArg) 1581 Splits.push_back(*Arg); 1582 Arg = &Ins[++I]; 1583 } 1584 } 1585 1586 if (SkipArg) { 1587 // We can safely skip PS inputs. 1588 Skipped.set(Arg->getOrigArgIndex()); 1589 ++PSInputNum; 1590 continue; 1591 } 1592 1593 Info->markPSInputAllocated(PSInputNum); 1594 if (Arg->Used) 1595 Info->markPSInputEnabled(PSInputNum); 1596 1597 ++PSInputNum; 1598 } 1599 1600 Splits.push_back(*Arg); 1601 } 1602 } 1603 1604 // Allocate special inputs passed in VGPRs. 1605 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1606 MachineFunction &MF, 1607 const SIRegisterInfo &TRI, 1608 SIMachineFunctionInfo &Info) const { 1609 const LLT S32 = LLT::scalar(32); 1610 MachineRegisterInfo &MRI = MF.getRegInfo(); 1611 1612 if (Info.hasWorkItemIDX()) { 1613 Register Reg = AMDGPU::VGPR0; 1614 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1615 1616 CCInfo.AllocateReg(Reg); 1617 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1618 } 1619 1620 if (Info.hasWorkItemIDY()) { 1621 Register Reg = AMDGPU::VGPR1; 1622 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1623 1624 CCInfo.AllocateReg(Reg); 1625 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1626 } 1627 1628 if (Info.hasWorkItemIDZ()) { 1629 Register Reg = AMDGPU::VGPR2; 1630 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1631 1632 CCInfo.AllocateReg(Reg); 1633 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1634 } 1635 } 1636 1637 // Try to allocate a VGPR at the end of the argument list, or if no argument 1638 // VGPRs are left allocating a stack slot. 1639 // If \p Mask is is given it indicates bitfield position in the register. 1640 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1641 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1642 ArgDescriptor Arg = ArgDescriptor()) { 1643 if (Arg.isSet()) 1644 return ArgDescriptor::createArg(Arg, Mask); 1645 1646 ArrayRef<MCPhysReg> ArgVGPRs 1647 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1648 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1649 if (RegIdx == ArgVGPRs.size()) { 1650 // Spill to stack required. 1651 int64_t Offset = CCInfo.AllocateStack(4, 4); 1652 1653 return ArgDescriptor::createStack(Offset, Mask); 1654 } 1655 1656 unsigned Reg = ArgVGPRs[RegIdx]; 1657 Reg = CCInfo.AllocateReg(Reg); 1658 assert(Reg != AMDGPU::NoRegister); 1659 1660 MachineFunction &MF = CCInfo.getMachineFunction(); 1661 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1662 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1663 return ArgDescriptor::createRegister(Reg, Mask); 1664 } 1665 1666 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1667 const TargetRegisterClass *RC, 1668 unsigned NumArgRegs) { 1669 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1670 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1671 if (RegIdx == ArgSGPRs.size()) 1672 report_fatal_error("ran out of SGPRs for arguments"); 1673 1674 unsigned Reg = ArgSGPRs[RegIdx]; 1675 Reg = CCInfo.AllocateReg(Reg); 1676 assert(Reg != AMDGPU::NoRegister); 1677 1678 MachineFunction &MF = CCInfo.getMachineFunction(); 1679 MF.addLiveIn(Reg, RC); 1680 return ArgDescriptor::createRegister(Reg); 1681 } 1682 1683 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1684 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1685 } 1686 1687 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1688 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1689 } 1690 1691 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo, 1692 MachineFunction &MF, 1693 const SIRegisterInfo &TRI, 1694 SIMachineFunctionInfo &Info) const { 1695 const unsigned Mask = 0x3ff; 1696 ArgDescriptor Arg; 1697 1698 if (Info.hasWorkItemIDX()) { 1699 Arg = allocateVGPR32Input(CCInfo, Mask); 1700 Info.setWorkItemIDX(Arg); 1701 } 1702 1703 if (Info.hasWorkItemIDY()) { 1704 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1705 Info.setWorkItemIDY(Arg); 1706 } 1707 1708 if (Info.hasWorkItemIDZ()) 1709 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1710 } 1711 1712 void SITargetLowering::allocateSpecialInputSGPRs( 1713 CCState &CCInfo, 1714 MachineFunction &MF, 1715 const SIRegisterInfo &TRI, 1716 SIMachineFunctionInfo &Info) const { 1717 auto &ArgInfo = Info.getArgInfo(); 1718 1719 // TODO: Unify handling with private memory pointers. 1720 1721 if (Info.hasDispatchPtr()) 1722 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1723 1724 if (Info.hasQueuePtr()) 1725 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1726 1727 if (Info.hasKernargSegmentPtr()) 1728 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1729 1730 if (Info.hasDispatchID()) 1731 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1732 1733 // flat_scratch_init is not applicable for non-kernel functions. 1734 1735 if (Info.hasWorkGroupIDX()) 1736 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1737 1738 if (Info.hasWorkGroupIDY()) 1739 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1740 1741 if (Info.hasWorkGroupIDZ()) 1742 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1743 1744 if (Info.hasImplicitArgPtr()) 1745 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1746 } 1747 1748 // Allocate special inputs passed in user SGPRs. 1749 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1750 MachineFunction &MF, 1751 const SIRegisterInfo &TRI, 1752 SIMachineFunctionInfo &Info) const { 1753 if (Info.hasImplicitBufferPtr()) { 1754 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1755 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1756 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1757 } 1758 1759 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1760 if (Info.hasPrivateSegmentBuffer()) { 1761 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1762 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1763 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1764 } 1765 1766 if (Info.hasDispatchPtr()) { 1767 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1768 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1769 CCInfo.AllocateReg(DispatchPtrReg); 1770 } 1771 1772 if (Info.hasQueuePtr()) { 1773 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1774 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1775 CCInfo.AllocateReg(QueuePtrReg); 1776 } 1777 1778 if (Info.hasKernargSegmentPtr()) { 1779 MachineRegisterInfo &MRI = MF.getRegInfo(); 1780 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1781 CCInfo.AllocateReg(InputPtrReg); 1782 1783 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1784 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1785 } 1786 1787 if (Info.hasDispatchID()) { 1788 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1789 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1790 CCInfo.AllocateReg(DispatchIDReg); 1791 } 1792 1793 if (Info.hasFlatScratchInit()) { 1794 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1795 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1796 CCInfo.AllocateReg(FlatScratchInitReg); 1797 } 1798 1799 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1800 // these from the dispatch pointer. 1801 } 1802 1803 // Allocate special input registers that are initialized per-wave. 1804 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1805 MachineFunction &MF, 1806 SIMachineFunctionInfo &Info, 1807 CallingConv::ID CallConv, 1808 bool IsShader) const { 1809 if (Info.hasWorkGroupIDX()) { 1810 unsigned Reg = Info.addWorkGroupIDX(); 1811 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1812 CCInfo.AllocateReg(Reg); 1813 } 1814 1815 if (Info.hasWorkGroupIDY()) { 1816 unsigned Reg = Info.addWorkGroupIDY(); 1817 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1818 CCInfo.AllocateReg(Reg); 1819 } 1820 1821 if (Info.hasWorkGroupIDZ()) { 1822 unsigned Reg = Info.addWorkGroupIDZ(); 1823 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1824 CCInfo.AllocateReg(Reg); 1825 } 1826 1827 if (Info.hasWorkGroupInfo()) { 1828 unsigned Reg = Info.addWorkGroupInfo(); 1829 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1830 CCInfo.AllocateReg(Reg); 1831 } 1832 1833 if (Info.hasPrivateSegmentWaveByteOffset()) { 1834 // Scratch wave offset passed in system SGPR. 1835 unsigned PrivateSegmentWaveByteOffsetReg; 1836 1837 if (IsShader) { 1838 PrivateSegmentWaveByteOffsetReg = 1839 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1840 1841 // This is true if the scratch wave byte offset doesn't have a fixed 1842 // location. 1843 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1844 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1845 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1846 } 1847 } else 1848 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1849 1850 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1851 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1852 } 1853 } 1854 1855 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1856 MachineFunction &MF, 1857 const SIRegisterInfo &TRI, 1858 SIMachineFunctionInfo &Info) { 1859 // Now that we've figured out where the scratch register inputs are, see if 1860 // should reserve the arguments and use them directly. 1861 MachineFrameInfo &MFI = MF.getFrameInfo(); 1862 bool HasStackObjects = MFI.hasStackObjects(); 1863 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1864 1865 // Record that we know we have non-spill stack objects so we don't need to 1866 // check all stack objects later. 1867 if (HasStackObjects) 1868 Info.setHasNonSpillStackObjects(true); 1869 1870 // Everything live out of a block is spilled with fast regalloc, so it's 1871 // almost certain that spilling will be required. 1872 if (TM.getOptLevel() == CodeGenOpt::None) 1873 HasStackObjects = true; 1874 1875 // For now assume stack access is needed in any callee functions, so we need 1876 // the scratch registers to pass in. 1877 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1878 1879 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1880 // If we have stack objects, we unquestionably need the private buffer 1881 // resource. For the Code Object V2 ABI, this will be the first 4 user 1882 // SGPR inputs. We can reserve those and use them directly. 1883 1884 Register PrivateSegmentBufferReg = 1885 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1886 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1887 } else { 1888 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1889 // We tentatively reserve the last registers (skipping the last registers 1890 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1891 // we'll replace these with the ones immediately after those which were 1892 // really allocated. In the prologue copies will be inserted from the 1893 // argument to these reserved registers. 1894 1895 // Without HSA, relocations are used for the scratch pointer and the 1896 // buffer resource setup is always inserted in the prologue. Scratch wave 1897 // offset is still in an input SGPR. 1898 Info.setScratchRSrcReg(ReservedBufferReg); 1899 } 1900 1901 // hasFP should be accurate for kernels even before the frame is finalized. 1902 if (ST.getFrameLowering()->hasFP(MF)) { 1903 MachineRegisterInfo &MRI = MF.getRegInfo(); 1904 1905 // Try to use s32 as the SP, but move it if it would interfere with input 1906 // arguments. This won't work with calls though. 1907 // 1908 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1909 // registers. 1910 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1911 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1912 } else { 1913 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1914 1915 if (MFI.hasCalls()) 1916 report_fatal_error("call in graphics shader with too many input SGPRs"); 1917 1918 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1919 if (!MRI.isLiveIn(Reg)) { 1920 Info.setStackPtrOffsetReg(Reg); 1921 break; 1922 } 1923 } 1924 1925 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1926 report_fatal_error("failed to find register for SP"); 1927 } 1928 1929 if (MFI.hasCalls()) { 1930 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1931 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1932 } else { 1933 unsigned ReservedOffsetReg = 1934 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1935 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1936 Info.setFrameOffsetReg(ReservedOffsetReg); 1937 } 1938 } else if (RequiresStackAccess) { 1939 assert(!MFI.hasCalls()); 1940 // We know there are accesses and they will be done relative to SP, so just 1941 // pin it to the input. 1942 // 1943 // FIXME: Should not do this if inline asm is reading/writing these 1944 // registers. 1945 Register PreloadedSP = Info.getPreloadedReg( 1946 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1947 1948 Info.setStackPtrOffsetReg(PreloadedSP); 1949 Info.setScratchWaveOffsetReg(PreloadedSP); 1950 Info.setFrameOffsetReg(PreloadedSP); 1951 } else { 1952 assert(!MFI.hasCalls()); 1953 1954 // There may not be stack access at all. There may still be spills, or 1955 // access of a constant pointer (in which cases an extra copy will be 1956 // emitted in the prolog). 1957 unsigned ReservedOffsetReg 1958 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1959 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1960 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1961 Info.setFrameOffsetReg(ReservedOffsetReg); 1962 } 1963 } 1964 1965 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1966 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1967 return !Info->isEntryFunction(); 1968 } 1969 1970 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1971 1972 } 1973 1974 void SITargetLowering::insertCopiesSplitCSR( 1975 MachineBasicBlock *Entry, 1976 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1977 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1978 1979 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1980 if (!IStart) 1981 return; 1982 1983 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1984 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 1985 MachineBasicBlock::iterator MBBI = Entry->begin(); 1986 for (const MCPhysReg *I = IStart; *I; ++I) { 1987 const TargetRegisterClass *RC = nullptr; 1988 if (AMDGPU::SReg_64RegClass.contains(*I)) 1989 RC = &AMDGPU::SGPR_64RegClass; 1990 else if (AMDGPU::SReg_32RegClass.contains(*I)) 1991 RC = &AMDGPU::SGPR_32RegClass; 1992 else 1993 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 1994 1995 Register NewVR = MRI->createVirtualRegister(RC); 1996 // Create copy from CSR to a virtual register. 1997 Entry->addLiveIn(*I); 1998 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 1999 .addReg(*I); 2000 2001 // Insert the copy-back instructions right before the terminator. 2002 for (auto *Exit : Exits) 2003 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2004 TII->get(TargetOpcode::COPY), *I) 2005 .addReg(NewVR); 2006 } 2007 } 2008 2009 SDValue SITargetLowering::LowerFormalArguments( 2010 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2011 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2012 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2013 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2014 2015 MachineFunction &MF = DAG.getMachineFunction(); 2016 const Function &Fn = MF.getFunction(); 2017 FunctionType *FType = MF.getFunction().getFunctionType(); 2018 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2019 2020 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2021 DiagnosticInfoUnsupported NoGraphicsHSA( 2022 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2023 DAG.getContext()->diagnose(NoGraphicsHSA); 2024 return DAG.getEntryNode(); 2025 } 2026 2027 SmallVector<ISD::InputArg, 16> Splits; 2028 SmallVector<CCValAssign, 16> ArgLocs; 2029 BitVector Skipped(Ins.size()); 2030 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2031 *DAG.getContext()); 2032 2033 bool IsShader = AMDGPU::isShader(CallConv); 2034 bool IsKernel = AMDGPU::isKernel(CallConv); 2035 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2036 2037 if (IsShader) { 2038 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2039 2040 // At least one interpolation mode must be enabled or else the GPU will 2041 // hang. 2042 // 2043 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2044 // set PSInputAddr, the user wants to enable some bits after the compilation 2045 // based on run-time states. Since we can't know what the final PSInputEna 2046 // will look like, so we shouldn't do anything here and the user should take 2047 // responsibility for the correct programming. 2048 // 2049 // Otherwise, the following restrictions apply: 2050 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2051 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2052 // enabled too. 2053 if (CallConv == CallingConv::AMDGPU_PS) { 2054 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2055 ((Info->getPSInputAddr() & 0xF) == 0 && 2056 Info->isPSInputAllocated(11))) { 2057 CCInfo.AllocateReg(AMDGPU::VGPR0); 2058 CCInfo.AllocateReg(AMDGPU::VGPR1); 2059 Info->markPSInputAllocated(0); 2060 Info->markPSInputEnabled(0); 2061 } 2062 if (Subtarget->isAmdPalOS()) { 2063 // For isAmdPalOS, the user does not enable some bits after compilation 2064 // based on run-time states; the register values being generated here are 2065 // the final ones set in hardware. Therefore we need to apply the 2066 // workaround to PSInputAddr and PSInputEnable together. (The case where 2067 // a bit is set in PSInputAddr but not PSInputEnable is where the 2068 // frontend set up an input arg for a particular interpolation mode, but 2069 // nothing uses that input arg. Really we should have an earlier pass 2070 // that removes such an arg.) 2071 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2072 if ((PsInputBits & 0x7F) == 0 || 2073 ((PsInputBits & 0xF) == 0 && 2074 (PsInputBits >> 11 & 1))) 2075 Info->markPSInputEnabled( 2076 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2077 } 2078 } 2079 2080 assert(!Info->hasDispatchPtr() && 2081 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2082 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2083 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2084 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2085 !Info->hasWorkItemIDZ()); 2086 } else if (IsKernel) { 2087 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2088 } else { 2089 Splits.append(Ins.begin(), Ins.end()); 2090 } 2091 2092 if (IsEntryFunc) { 2093 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2094 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2095 } 2096 2097 if (IsKernel) { 2098 analyzeFormalArgumentsCompute(CCInfo, Ins); 2099 } else { 2100 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2101 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2102 } 2103 2104 SmallVector<SDValue, 16> Chains; 2105 2106 // FIXME: This is the minimum kernel argument alignment. We should improve 2107 // this to the maximum alignment of the arguments. 2108 // 2109 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2110 // kern arg offset. 2111 const unsigned KernelArgBaseAlign = 16; 2112 2113 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2114 const ISD::InputArg &Arg = Ins[i]; 2115 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2116 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2117 continue; 2118 } 2119 2120 CCValAssign &VA = ArgLocs[ArgIdx++]; 2121 MVT VT = VA.getLocVT(); 2122 2123 if (IsEntryFunc && VA.isMemLoc()) { 2124 VT = Ins[i].VT; 2125 EVT MemVT = VA.getLocVT(); 2126 2127 const uint64_t Offset = VA.getLocMemOffset(); 2128 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2129 2130 SDValue Arg = lowerKernargMemParameter( 2131 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2132 Chains.push_back(Arg.getValue(1)); 2133 2134 auto *ParamTy = 2135 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2136 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2137 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2138 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2139 // On SI local pointers are just offsets into LDS, so they are always 2140 // less than 16-bits. On CI and newer they could potentially be 2141 // real pointers, so we can't guarantee their size. 2142 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2143 DAG.getValueType(MVT::i16)); 2144 } 2145 2146 InVals.push_back(Arg); 2147 continue; 2148 } else if (!IsEntryFunc && VA.isMemLoc()) { 2149 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2150 InVals.push_back(Val); 2151 if (!Arg.Flags.isByVal()) 2152 Chains.push_back(Val.getValue(1)); 2153 continue; 2154 } 2155 2156 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2157 2158 Register Reg = VA.getLocReg(); 2159 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2160 EVT ValVT = VA.getValVT(); 2161 2162 Reg = MF.addLiveIn(Reg, RC); 2163 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2164 2165 if (Arg.Flags.isSRet()) { 2166 // The return object should be reasonably addressable. 2167 2168 // FIXME: This helps when the return is a real sret. If it is a 2169 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2170 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2171 unsigned NumBits 2172 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2173 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2174 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2175 } 2176 2177 // If this is an 8 or 16-bit value, it is really passed promoted 2178 // to 32 bits. Insert an assert[sz]ext to capture this, then 2179 // truncate to the right size. 2180 switch (VA.getLocInfo()) { 2181 case CCValAssign::Full: 2182 break; 2183 case CCValAssign::BCvt: 2184 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2185 break; 2186 case CCValAssign::SExt: 2187 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2188 DAG.getValueType(ValVT)); 2189 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2190 break; 2191 case CCValAssign::ZExt: 2192 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2193 DAG.getValueType(ValVT)); 2194 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2195 break; 2196 case CCValAssign::AExt: 2197 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2198 break; 2199 default: 2200 llvm_unreachable("Unknown loc info!"); 2201 } 2202 2203 InVals.push_back(Val); 2204 } 2205 2206 if (!IsEntryFunc) { 2207 // Special inputs come after user arguments. 2208 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2209 } 2210 2211 // Start adding system SGPRs. 2212 if (IsEntryFunc) { 2213 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2214 } else { 2215 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2216 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2217 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2218 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2219 } 2220 2221 auto &ArgUsageInfo = 2222 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2223 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2224 2225 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2226 Info->setBytesInStackArgArea(StackArgSize); 2227 2228 return Chains.empty() ? Chain : 2229 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2230 } 2231 2232 // TODO: If return values can't fit in registers, we should return as many as 2233 // possible in registers before passing on stack. 2234 bool SITargetLowering::CanLowerReturn( 2235 CallingConv::ID CallConv, 2236 MachineFunction &MF, bool IsVarArg, 2237 const SmallVectorImpl<ISD::OutputArg> &Outs, 2238 LLVMContext &Context) const { 2239 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2240 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2241 // for shaders. Vector types should be explicitly handled by CC. 2242 if (AMDGPU::isEntryFunctionCC(CallConv)) 2243 return true; 2244 2245 SmallVector<CCValAssign, 16> RVLocs; 2246 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2247 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2248 } 2249 2250 SDValue 2251 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2252 bool isVarArg, 2253 const SmallVectorImpl<ISD::OutputArg> &Outs, 2254 const SmallVectorImpl<SDValue> &OutVals, 2255 const SDLoc &DL, SelectionDAG &DAG) const { 2256 MachineFunction &MF = DAG.getMachineFunction(); 2257 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2258 2259 if (AMDGPU::isKernel(CallConv)) { 2260 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2261 OutVals, DL, DAG); 2262 } 2263 2264 bool IsShader = AMDGPU::isShader(CallConv); 2265 2266 Info->setIfReturnsVoid(Outs.empty()); 2267 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2268 2269 // CCValAssign - represent the assignment of the return value to a location. 2270 SmallVector<CCValAssign, 48> RVLocs; 2271 SmallVector<ISD::OutputArg, 48> Splits; 2272 2273 // CCState - Info about the registers and stack slots. 2274 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2275 *DAG.getContext()); 2276 2277 // Analyze outgoing return values. 2278 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2279 2280 SDValue Flag; 2281 SmallVector<SDValue, 48> RetOps; 2282 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2283 2284 // Add return address for callable functions. 2285 if (!Info->isEntryFunction()) { 2286 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2287 SDValue ReturnAddrReg = CreateLiveInRegister( 2288 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2289 2290 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2291 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2292 MVT::i64); 2293 Chain = 2294 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2295 Flag = Chain.getValue(1); 2296 RetOps.push_back(ReturnAddrVirtualReg); 2297 } 2298 2299 // Copy the result values into the output registers. 2300 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2301 ++I, ++RealRVLocIdx) { 2302 CCValAssign &VA = RVLocs[I]; 2303 assert(VA.isRegLoc() && "Can only return in registers!"); 2304 // TODO: Partially return in registers if return values don't fit. 2305 SDValue Arg = OutVals[RealRVLocIdx]; 2306 2307 // Copied from other backends. 2308 switch (VA.getLocInfo()) { 2309 case CCValAssign::Full: 2310 break; 2311 case CCValAssign::BCvt: 2312 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2313 break; 2314 case CCValAssign::SExt: 2315 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2316 break; 2317 case CCValAssign::ZExt: 2318 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2319 break; 2320 case CCValAssign::AExt: 2321 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2322 break; 2323 default: 2324 llvm_unreachable("Unknown loc info!"); 2325 } 2326 2327 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2328 Flag = Chain.getValue(1); 2329 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2330 } 2331 2332 // FIXME: Does sret work properly? 2333 if (!Info->isEntryFunction()) { 2334 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2335 const MCPhysReg *I = 2336 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2337 if (I) { 2338 for (; *I; ++I) { 2339 if (AMDGPU::SReg_64RegClass.contains(*I)) 2340 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2341 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2342 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2343 else 2344 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2345 } 2346 } 2347 } 2348 2349 // Update chain and glue. 2350 RetOps[0] = Chain; 2351 if (Flag.getNode()) 2352 RetOps.push_back(Flag); 2353 2354 unsigned Opc = AMDGPUISD::ENDPGM; 2355 if (!IsWaveEnd) 2356 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2357 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2358 } 2359 2360 SDValue SITargetLowering::LowerCallResult( 2361 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2362 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2363 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2364 SDValue ThisVal) const { 2365 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2366 2367 // Assign locations to each value returned by this call. 2368 SmallVector<CCValAssign, 16> RVLocs; 2369 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2370 *DAG.getContext()); 2371 CCInfo.AnalyzeCallResult(Ins, RetCC); 2372 2373 // Copy all of the result registers out of their specified physreg. 2374 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2375 CCValAssign VA = RVLocs[i]; 2376 SDValue Val; 2377 2378 if (VA.isRegLoc()) { 2379 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2380 Chain = Val.getValue(1); 2381 InFlag = Val.getValue(2); 2382 } else if (VA.isMemLoc()) { 2383 report_fatal_error("TODO: return values in memory"); 2384 } else 2385 llvm_unreachable("unknown argument location type"); 2386 2387 switch (VA.getLocInfo()) { 2388 case CCValAssign::Full: 2389 break; 2390 case CCValAssign::BCvt: 2391 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2392 break; 2393 case CCValAssign::ZExt: 2394 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2395 DAG.getValueType(VA.getValVT())); 2396 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2397 break; 2398 case CCValAssign::SExt: 2399 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2400 DAG.getValueType(VA.getValVT())); 2401 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2402 break; 2403 case CCValAssign::AExt: 2404 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2405 break; 2406 default: 2407 llvm_unreachable("Unknown loc info!"); 2408 } 2409 2410 InVals.push_back(Val); 2411 } 2412 2413 return Chain; 2414 } 2415 2416 // Add code to pass special inputs required depending on used features separate 2417 // from the explicit user arguments present in the IR. 2418 void SITargetLowering::passSpecialInputs( 2419 CallLoweringInfo &CLI, 2420 CCState &CCInfo, 2421 const SIMachineFunctionInfo &Info, 2422 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2423 SmallVectorImpl<SDValue> &MemOpChains, 2424 SDValue Chain) const { 2425 // If we don't have a call site, this was a call inserted by 2426 // legalization. These can never use special inputs. 2427 if (!CLI.CS) 2428 return; 2429 2430 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2431 assert(CalleeFunc); 2432 2433 SelectionDAG &DAG = CLI.DAG; 2434 const SDLoc &DL = CLI.DL; 2435 2436 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2437 2438 auto &ArgUsageInfo = 2439 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2440 const AMDGPUFunctionArgInfo &CalleeArgInfo 2441 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2442 2443 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2444 2445 // TODO: Unify with private memory register handling. This is complicated by 2446 // the fact that at least in kernels, the input argument is not necessarily 2447 // in the same location as the input. 2448 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2449 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2450 AMDGPUFunctionArgInfo::QUEUE_PTR, 2451 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2452 AMDGPUFunctionArgInfo::DISPATCH_ID, 2453 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2454 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2455 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2456 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2457 }; 2458 2459 for (auto InputID : InputRegs) { 2460 const ArgDescriptor *OutgoingArg; 2461 const TargetRegisterClass *ArgRC; 2462 2463 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2464 if (!OutgoingArg) 2465 continue; 2466 2467 const ArgDescriptor *IncomingArg; 2468 const TargetRegisterClass *IncomingArgRC; 2469 std::tie(IncomingArg, IncomingArgRC) 2470 = CallerArgInfo.getPreloadedValue(InputID); 2471 assert(IncomingArgRC == ArgRC); 2472 2473 // All special arguments are ints for now. 2474 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2475 SDValue InputReg; 2476 2477 if (IncomingArg) { 2478 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2479 } else { 2480 // The implicit arg ptr is special because it doesn't have a corresponding 2481 // input for kernels, and is computed from the kernarg segment pointer. 2482 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2483 InputReg = getImplicitArgPtr(DAG, DL); 2484 } 2485 2486 if (OutgoingArg->isRegister()) { 2487 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2488 } else { 2489 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2490 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2491 SpecialArgOffset); 2492 MemOpChains.push_back(ArgStore); 2493 } 2494 } 2495 2496 // Pack workitem IDs into a single register or pass it as is if already 2497 // packed. 2498 const ArgDescriptor *OutgoingArg; 2499 const TargetRegisterClass *ArgRC; 2500 2501 std::tie(OutgoingArg, ArgRC) = 2502 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2503 if (!OutgoingArg) 2504 std::tie(OutgoingArg, ArgRC) = 2505 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2506 if (!OutgoingArg) 2507 std::tie(OutgoingArg, ArgRC) = 2508 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2509 if (!OutgoingArg) 2510 return; 2511 2512 const ArgDescriptor *IncomingArgX 2513 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2514 const ArgDescriptor *IncomingArgY 2515 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2516 const ArgDescriptor *IncomingArgZ 2517 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2518 2519 SDValue InputReg; 2520 SDLoc SL; 2521 2522 // If incoming ids are not packed we need to pack them. 2523 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2524 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2525 2526 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2527 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2528 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2529 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2530 InputReg = InputReg.getNode() ? 2531 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2532 } 2533 2534 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2535 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2536 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2537 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2538 InputReg = InputReg.getNode() ? 2539 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2540 } 2541 2542 if (!InputReg.getNode()) { 2543 // Workitem ids are already packed, any of present incoming arguments 2544 // will carry all required fields. 2545 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2546 IncomingArgX ? *IncomingArgX : 2547 IncomingArgY ? *IncomingArgY : 2548 *IncomingArgZ, ~0u); 2549 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2550 } 2551 2552 if (OutgoingArg->isRegister()) { 2553 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2554 } else { 2555 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2556 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2557 SpecialArgOffset); 2558 MemOpChains.push_back(ArgStore); 2559 } 2560 } 2561 2562 static bool canGuaranteeTCO(CallingConv::ID CC) { 2563 return CC == CallingConv::Fast; 2564 } 2565 2566 /// Return true if we might ever do TCO for calls with this calling convention. 2567 static bool mayTailCallThisCC(CallingConv::ID CC) { 2568 switch (CC) { 2569 case CallingConv::C: 2570 return true; 2571 default: 2572 return canGuaranteeTCO(CC); 2573 } 2574 } 2575 2576 bool SITargetLowering::isEligibleForTailCallOptimization( 2577 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2578 const SmallVectorImpl<ISD::OutputArg> &Outs, 2579 const SmallVectorImpl<SDValue> &OutVals, 2580 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2581 if (!mayTailCallThisCC(CalleeCC)) 2582 return false; 2583 2584 MachineFunction &MF = DAG.getMachineFunction(); 2585 const Function &CallerF = MF.getFunction(); 2586 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2587 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2588 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2589 2590 // Kernels aren't callable, and don't have a live in return address so it 2591 // doesn't make sense to do a tail call with entry functions. 2592 if (!CallerPreserved) 2593 return false; 2594 2595 bool CCMatch = CallerCC == CalleeCC; 2596 2597 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2598 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2599 return true; 2600 return false; 2601 } 2602 2603 // TODO: Can we handle var args? 2604 if (IsVarArg) 2605 return false; 2606 2607 for (const Argument &Arg : CallerF.args()) { 2608 if (Arg.hasByValAttr()) 2609 return false; 2610 } 2611 2612 LLVMContext &Ctx = *DAG.getContext(); 2613 2614 // Check that the call results are passed in the same way. 2615 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2616 CCAssignFnForCall(CalleeCC, IsVarArg), 2617 CCAssignFnForCall(CallerCC, IsVarArg))) 2618 return false; 2619 2620 // The callee has to preserve all registers the caller needs to preserve. 2621 if (!CCMatch) { 2622 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2623 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2624 return false; 2625 } 2626 2627 // Nothing more to check if the callee is taking no arguments. 2628 if (Outs.empty()) 2629 return true; 2630 2631 SmallVector<CCValAssign, 16> ArgLocs; 2632 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2633 2634 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2635 2636 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2637 // If the stack arguments for this call do not fit into our own save area then 2638 // the call cannot be made tail. 2639 // TODO: Is this really necessary? 2640 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2641 return false; 2642 2643 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2644 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2645 } 2646 2647 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2648 if (!CI->isTailCall()) 2649 return false; 2650 2651 const Function *ParentFn = CI->getParent()->getParent(); 2652 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2653 return false; 2654 return true; 2655 } 2656 2657 // The wave scratch offset register is used as the global base pointer. 2658 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2659 SmallVectorImpl<SDValue> &InVals) const { 2660 SelectionDAG &DAG = CLI.DAG; 2661 const SDLoc &DL = CLI.DL; 2662 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2663 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2664 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2665 SDValue Chain = CLI.Chain; 2666 SDValue Callee = CLI.Callee; 2667 bool &IsTailCall = CLI.IsTailCall; 2668 CallingConv::ID CallConv = CLI.CallConv; 2669 bool IsVarArg = CLI.IsVarArg; 2670 bool IsSibCall = false; 2671 bool IsThisReturn = false; 2672 MachineFunction &MF = DAG.getMachineFunction(); 2673 2674 if (Callee.isUndef() || isNullConstant(Callee)) { 2675 if (!CLI.IsTailCall) { 2676 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2677 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2678 } 2679 2680 return Chain; 2681 } 2682 2683 if (IsVarArg) { 2684 return lowerUnhandledCall(CLI, InVals, 2685 "unsupported call to variadic function "); 2686 } 2687 2688 if (!CLI.CS.getInstruction()) 2689 report_fatal_error("unsupported libcall legalization"); 2690 2691 if (!CLI.CS.getCalledFunction()) { 2692 return lowerUnhandledCall(CLI, InVals, 2693 "unsupported indirect call to function "); 2694 } 2695 2696 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2697 return lowerUnhandledCall(CLI, InVals, 2698 "unsupported required tail call to function "); 2699 } 2700 2701 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2702 // Note the issue is with the CC of the calling function, not of the call 2703 // itself. 2704 return lowerUnhandledCall(CLI, InVals, 2705 "unsupported call from graphics shader of function "); 2706 } 2707 2708 if (IsTailCall) { 2709 IsTailCall = isEligibleForTailCallOptimization( 2710 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2711 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2712 report_fatal_error("failed to perform tail call elimination on a call " 2713 "site marked musttail"); 2714 } 2715 2716 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2717 2718 // A sibling call is one where we're under the usual C ABI and not planning 2719 // to change that but can still do a tail call: 2720 if (!TailCallOpt && IsTailCall) 2721 IsSibCall = true; 2722 2723 if (IsTailCall) 2724 ++NumTailCalls; 2725 } 2726 2727 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2728 2729 // Analyze operands of the call, assigning locations to each operand. 2730 SmallVector<CCValAssign, 16> ArgLocs; 2731 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2732 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2733 2734 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2735 2736 // Get a count of how many bytes are to be pushed on the stack. 2737 unsigned NumBytes = CCInfo.getNextStackOffset(); 2738 2739 if (IsSibCall) { 2740 // Since we're not changing the ABI to make this a tail call, the memory 2741 // operands are already available in the caller's incoming argument space. 2742 NumBytes = 0; 2743 } 2744 2745 // FPDiff is the byte offset of the call's argument area from the callee's. 2746 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2747 // by this amount for a tail call. In a sibling call it must be 0 because the 2748 // caller will deallocate the entire stack and the callee still expects its 2749 // arguments to begin at SP+0. Completely unused for non-tail calls. 2750 int32_t FPDiff = 0; 2751 MachineFrameInfo &MFI = MF.getFrameInfo(); 2752 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2753 2754 // Adjust the stack pointer for the new arguments... 2755 // These operations are automatically eliminated by the prolog/epilog pass 2756 if (!IsSibCall) { 2757 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2758 2759 SmallVector<SDValue, 4> CopyFromChains; 2760 2761 // In the HSA case, this should be an identity copy. 2762 SDValue ScratchRSrcReg 2763 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2764 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2765 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2766 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2767 } 2768 2769 SmallVector<SDValue, 8> MemOpChains; 2770 MVT PtrVT = MVT::i32; 2771 2772 // Walk the register/memloc assignments, inserting copies/loads. 2773 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2774 CCValAssign &VA = ArgLocs[i]; 2775 SDValue Arg = OutVals[i]; 2776 2777 // Promote the value if needed. 2778 switch (VA.getLocInfo()) { 2779 case CCValAssign::Full: 2780 break; 2781 case CCValAssign::BCvt: 2782 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2783 break; 2784 case CCValAssign::ZExt: 2785 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2786 break; 2787 case CCValAssign::SExt: 2788 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2789 break; 2790 case CCValAssign::AExt: 2791 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2792 break; 2793 case CCValAssign::FPExt: 2794 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2795 break; 2796 default: 2797 llvm_unreachable("Unknown loc info!"); 2798 } 2799 2800 if (VA.isRegLoc()) { 2801 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2802 } else { 2803 assert(VA.isMemLoc()); 2804 2805 SDValue DstAddr; 2806 MachinePointerInfo DstInfo; 2807 2808 unsigned LocMemOffset = VA.getLocMemOffset(); 2809 int32_t Offset = LocMemOffset; 2810 2811 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2812 MaybeAlign Alignment; 2813 2814 if (IsTailCall) { 2815 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2816 unsigned OpSize = Flags.isByVal() ? 2817 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2818 2819 // FIXME: We can have better than the minimum byval required alignment. 2820 Alignment = 2821 Flags.isByVal() 2822 ? Flags.getNonZeroByValAlign() 2823 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2824 2825 Offset = Offset + FPDiff; 2826 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2827 2828 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2829 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2830 2831 // Make sure any stack arguments overlapping with where we're storing 2832 // are loaded before this eventual operation. Otherwise they'll be 2833 // clobbered. 2834 2835 // FIXME: Why is this really necessary? This seems to just result in a 2836 // lot of code to copy the stack and write them back to the same 2837 // locations, which are supposed to be immutable? 2838 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2839 } else { 2840 DstAddr = PtrOff; 2841 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2842 Alignment = 2843 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2844 } 2845 2846 if (Outs[i].Flags.isByVal()) { 2847 SDValue SizeNode = 2848 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2849 SDValue Cpy = 2850 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2851 Outs[i].Flags.getNonZeroByValAlign(), 2852 /*isVol = */ false, /*AlwaysInline = */ true, 2853 /*isTailCall = */ false, DstInfo, 2854 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2855 2856 MemOpChains.push_back(Cpy); 2857 } else { 2858 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2859 Alignment ? Alignment->value() : 0); 2860 MemOpChains.push_back(Store); 2861 } 2862 } 2863 } 2864 2865 // Copy special input registers after user input arguments. 2866 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2867 2868 if (!MemOpChains.empty()) 2869 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2870 2871 // Build a sequence of copy-to-reg nodes chained together with token chain 2872 // and flag operands which copy the outgoing args into the appropriate regs. 2873 SDValue InFlag; 2874 for (auto &RegToPass : RegsToPass) { 2875 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2876 RegToPass.second, InFlag); 2877 InFlag = Chain.getValue(1); 2878 } 2879 2880 2881 SDValue PhysReturnAddrReg; 2882 if (IsTailCall) { 2883 // Since the return is being combined with the call, we need to pass on the 2884 // return address. 2885 2886 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2887 SDValue ReturnAddrReg = CreateLiveInRegister( 2888 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2889 2890 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2891 MVT::i64); 2892 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2893 InFlag = Chain.getValue(1); 2894 } 2895 2896 // We don't usually want to end the call-sequence here because we would tidy 2897 // the frame up *after* the call, however in the ABI-changing tail-call case 2898 // we've carefully laid out the parameters so that when sp is reset they'll be 2899 // in the correct location. 2900 if (IsTailCall && !IsSibCall) { 2901 Chain = DAG.getCALLSEQ_END(Chain, 2902 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2903 DAG.getTargetConstant(0, DL, MVT::i32), 2904 InFlag, DL); 2905 InFlag = Chain.getValue(1); 2906 } 2907 2908 std::vector<SDValue> Ops; 2909 Ops.push_back(Chain); 2910 Ops.push_back(Callee); 2911 // Add a redundant copy of the callee global which will not be legalized, as 2912 // we need direct access to the callee later. 2913 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2914 const GlobalValue *GV = GSD->getGlobal(); 2915 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2916 2917 if (IsTailCall) { 2918 // Each tail call may have to adjust the stack by a different amount, so 2919 // this information must travel along with the operation for eventual 2920 // consumption by emitEpilogue. 2921 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2922 2923 Ops.push_back(PhysReturnAddrReg); 2924 } 2925 2926 // Add argument registers to the end of the list so that they are known live 2927 // into the call. 2928 for (auto &RegToPass : RegsToPass) { 2929 Ops.push_back(DAG.getRegister(RegToPass.first, 2930 RegToPass.second.getValueType())); 2931 } 2932 2933 // Add a register mask operand representing the call-preserved registers. 2934 2935 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2936 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2937 assert(Mask && "Missing call preserved mask for calling convention"); 2938 Ops.push_back(DAG.getRegisterMask(Mask)); 2939 2940 if (InFlag.getNode()) 2941 Ops.push_back(InFlag); 2942 2943 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2944 2945 // If we're doing a tall call, use a TC_RETURN here rather than an 2946 // actual call instruction. 2947 if (IsTailCall) { 2948 MFI.setHasTailCall(); 2949 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2950 } 2951 2952 // Returns a chain and a flag for retval copy to use. 2953 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2954 Chain = Call.getValue(0); 2955 InFlag = Call.getValue(1); 2956 2957 uint64_t CalleePopBytes = NumBytes; 2958 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2959 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2960 InFlag, DL); 2961 if (!Ins.empty()) 2962 InFlag = Chain.getValue(1); 2963 2964 // Handle result values, copying them out of physregs into vregs that we 2965 // return. 2966 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2967 InVals, IsThisReturn, 2968 IsThisReturn ? OutVals[0] : SDValue()); 2969 } 2970 2971 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 2972 const MachineFunction &MF) const { 2973 Register Reg = StringSwitch<Register>(RegName) 2974 .Case("m0", AMDGPU::M0) 2975 .Case("exec", AMDGPU::EXEC) 2976 .Case("exec_lo", AMDGPU::EXEC_LO) 2977 .Case("exec_hi", AMDGPU::EXEC_HI) 2978 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2979 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2980 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2981 .Default(Register()); 2982 2983 if (Reg == AMDGPU::NoRegister) { 2984 report_fatal_error(Twine("invalid register name \"" 2985 + StringRef(RegName) + "\".")); 2986 2987 } 2988 2989 if (!Subtarget->hasFlatScrRegister() && 2990 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 2991 report_fatal_error(Twine("invalid register \"" 2992 + StringRef(RegName) + "\" for subtarget.")); 2993 } 2994 2995 switch (Reg) { 2996 case AMDGPU::M0: 2997 case AMDGPU::EXEC_LO: 2998 case AMDGPU::EXEC_HI: 2999 case AMDGPU::FLAT_SCR_LO: 3000 case AMDGPU::FLAT_SCR_HI: 3001 if (VT.getSizeInBits() == 32) 3002 return Reg; 3003 break; 3004 case AMDGPU::EXEC: 3005 case AMDGPU::FLAT_SCR: 3006 if (VT.getSizeInBits() == 64) 3007 return Reg; 3008 break; 3009 default: 3010 llvm_unreachable("missing register type checking"); 3011 } 3012 3013 report_fatal_error(Twine("invalid type for register \"" 3014 + StringRef(RegName) + "\".")); 3015 } 3016 3017 // If kill is not the last instruction, split the block so kill is always a 3018 // proper terminator. 3019 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3020 MachineBasicBlock *BB) const { 3021 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3022 3023 MachineBasicBlock::iterator SplitPoint(&MI); 3024 ++SplitPoint; 3025 3026 if (SplitPoint == BB->end()) { 3027 // Don't bother with a new block. 3028 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3029 return BB; 3030 } 3031 3032 MachineFunction *MF = BB->getParent(); 3033 MachineBasicBlock *SplitBB 3034 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3035 3036 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3037 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3038 3039 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3040 BB->addSuccessor(SplitBB); 3041 3042 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3043 return SplitBB; 3044 } 3045 3046 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3047 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3048 // be the first instruction in the remainder block. 3049 // 3050 /// \returns { LoopBody, Remainder } 3051 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3052 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3053 MachineFunction *MF = MBB.getParent(); 3054 MachineBasicBlock::iterator I(&MI); 3055 3056 // To insert the loop we need to split the block. Move everything after this 3057 // point to a new block, and insert a new empty block between the two. 3058 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3059 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3060 MachineFunction::iterator MBBI(MBB); 3061 ++MBBI; 3062 3063 MF->insert(MBBI, LoopBB); 3064 MF->insert(MBBI, RemainderBB); 3065 3066 LoopBB->addSuccessor(LoopBB); 3067 LoopBB->addSuccessor(RemainderBB); 3068 3069 // Move the rest of the block into a new block. 3070 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3071 3072 if (InstInLoop) { 3073 auto Next = std::next(I); 3074 3075 // Move instruction to loop body. 3076 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3077 3078 // Move the rest of the block. 3079 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3080 } else { 3081 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3082 } 3083 3084 MBB.addSuccessor(LoopBB); 3085 3086 return std::make_pair(LoopBB, RemainderBB); 3087 } 3088 3089 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3090 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3091 MachineBasicBlock *MBB = MI.getParent(); 3092 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3093 auto I = MI.getIterator(); 3094 auto E = std::next(I); 3095 3096 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3097 .addImm(0); 3098 3099 MIBundleBuilder Bundler(*MBB, I, E); 3100 finalizeBundle(*MBB, Bundler.begin()); 3101 } 3102 3103 MachineBasicBlock * 3104 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3105 MachineBasicBlock *BB) const { 3106 const DebugLoc &DL = MI.getDebugLoc(); 3107 3108 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3109 3110 MachineBasicBlock *LoopBB; 3111 MachineBasicBlock *RemainderBB; 3112 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3113 3114 // Apparently kill flags are only valid if the def is in the same block? 3115 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3116 Src->setIsKill(false); 3117 3118 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3119 3120 MachineBasicBlock::iterator I = LoopBB->end(); 3121 3122 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3123 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3124 3125 // Clear TRAP_STS.MEM_VIOL 3126 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3127 .addImm(0) 3128 .addImm(EncodedReg); 3129 3130 bundleInstWithWaitcnt(MI); 3131 3132 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3133 3134 // Load and check TRAP_STS.MEM_VIOL 3135 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3136 .addImm(EncodedReg); 3137 3138 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3139 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3140 .addReg(Reg, RegState::Kill) 3141 .addImm(0); 3142 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3143 .addMBB(LoopBB); 3144 3145 return RemainderBB; 3146 } 3147 3148 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3149 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3150 // will only do one iteration. In the worst case, this will loop 64 times. 3151 // 3152 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3153 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3154 const SIInstrInfo *TII, 3155 MachineRegisterInfo &MRI, 3156 MachineBasicBlock &OrigBB, 3157 MachineBasicBlock &LoopBB, 3158 const DebugLoc &DL, 3159 const MachineOperand &IdxReg, 3160 unsigned InitReg, 3161 unsigned ResultReg, 3162 unsigned PhiReg, 3163 unsigned InitSaveExecReg, 3164 int Offset, 3165 bool UseGPRIdxMode, 3166 bool IsIndirectSrc) { 3167 MachineFunction *MF = OrigBB.getParent(); 3168 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3169 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3170 MachineBasicBlock::iterator I = LoopBB.begin(); 3171 3172 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3173 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3174 Register NewExec = MRI.createVirtualRegister(BoolRC); 3175 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3176 Register CondReg = MRI.createVirtualRegister(BoolRC); 3177 3178 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3179 .addReg(InitReg) 3180 .addMBB(&OrigBB) 3181 .addReg(ResultReg) 3182 .addMBB(&LoopBB); 3183 3184 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3185 .addReg(InitSaveExecReg) 3186 .addMBB(&OrigBB) 3187 .addReg(NewExec) 3188 .addMBB(&LoopBB); 3189 3190 // Read the next variant <- also loop target. 3191 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3192 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3193 3194 // Compare the just read M0 value to all possible Idx values. 3195 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3196 .addReg(CurrentIdxReg) 3197 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3198 3199 // Update EXEC, save the original EXEC value to VCC. 3200 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3201 : AMDGPU::S_AND_SAVEEXEC_B64), 3202 NewExec) 3203 .addReg(CondReg, RegState::Kill); 3204 3205 MRI.setSimpleHint(NewExec, CondReg); 3206 3207 if (UseGPRIdxMode) { 3208 unsigned IdxReg; 3209 if (Offset == 0) { 3210 IdxReg = CurrentIdxReg; 3211 } else { 3212 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3213 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3214 .addReg(CurrentIdxReg, RegState::Kill) 3215 .addImm(Offset); 3216 } 3217 unsigned IdxMode = IsIndirectSrc ? 3218 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3219 MachineInstr *SetOn = 3220 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3221 .addReg(IdxReg, RegState::Kill) 3222 .addImm(IdxMode); 3223 SetOn->getOperand(3).setIsUndef(); 3224 } else { 3225 // Move index from VCC into M0 3226 if (Offset == 0) { 3227 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3228 .addReg(CurrentIdxReg, RegState::Kill); 3229 } else { 3230 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3231 .addReg(CurrentIdxReg, RegState::Kill) 3232 .addImm(Offset); 3233 } 3234 } 3235 3236 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3237 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3238 MachineInstr *InsertPt = 3239 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3240 : AMDGPU::S_XOR_B64_term), Exec) 3241 .addReg(Exec) 3242 .addReg(NewExec); 3243 3244 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3245 // s_cbranch_scc0? 3246 3247 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3248 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3249 .addMBB(&LoopBB); 3250 3251 return InsertPt->getIterator(); 3252 } 3253 3254 // This has slightly sub-optimal regalloc when the source vector is killed by 3255 // the read. The register allocator does not understand that the kill is 3256 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3257 // subregister from it, using 1 more VGPR than necessary. This was saved when 3258 // this was expanded after register allocation. 3259 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3260 MachineBasicBlock &MBB, 3261 MachineInstr &MI, 3262 unsigned InitResultReg, 3263 unsigned PhiReg, 3264 int Offset, 3265 bool UseGPRIdxMode, 3266 bool IsIndirectSrc) { 3267 MachineFunction *MF = MBB.getParent(); 3268 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3269 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3270 MachineRegisterInfo &MRI = MF->getRegInfo(); 3271 const DebugLoc &DL = MI.getDebugLoc(); 3272 MachineBasicBlock::iterator I(&MI); 3273 3274 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3275 Register DstReg = MI.getOperand(0).getReg(); 3276 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3277 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3278 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3279 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3280 3281 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3282 3283 // Save the EXEC mask 3284 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3285 .addReg(Exec); 3286 3287 MachineBasicBlock *LoopBB; 3288 MachineBasicBlock *RemainderBB; 3289 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3290 3291 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3292 3293 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3294 InitResultReg, DstReg, PhiReg, TmpExec, 3295 Offset, UseGPRIdxMode, IsIndirectSrc); 3296 3297 MachineBasicBlock::iterator First = RemainderBB->begin(); 3298 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3299 .addReg(SaveExec); 3300 3301 return InsPt; 3302 } 3303 3304 // Returns subreg index, offset 3305 static std::pair<unsigned, int> 3306 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3307 const TargetRegisterClass *SuperRC, 3308 unsigned VecReg, 3309 int Offset) { 3310 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3311 3312 // Skip out of bounds offsets, or else we would end up using an undefined 3313 // register. 3314 if (Offset >= NumElts || Offset < 0) 3315 return std::make_pair(AMDGPU::sub0, Offset); 3316 3317 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3318 } 3319 3320 // Return true if the index is an SGPR and was set. 3321 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3322 MachineRegisterInfo &MRI, 3323 MachineInstr &MI, 3324 int Offset, 3325 bool UseGPRIdxMode, 3326 bool IsIndirectSrc) { 3327 MachineBasicBlock *MBB = MI.getParent(); 3328 const DebugLoc &DL = MI.getDebugLoc(); 3329 MachineBasicBlock::iterator I(&MI); 3330 3331 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3332 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3333 3334 assert(Idx->getReg() != AMDGPU::NoRegister); 3335 3336 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3337 return false; 3338 3339 if (UseGPRIdxMode) { 3340 unsigned IdxMode = IsIndirectSrc ? 3341 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3342 if (Offset == 0) { 3343 MachineInstr *SetOn = 3344 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3345 .add(*Idx) 3346 .addImm(IdxMode); 3347 3348 SetOn->getOperand(3).setIsUndef(); 3349 } else { 3350 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3351 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3352 .add(*Idx) 3353 .addImm(Offset); 3354 MachineInstr *SetOn = 3355 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3356 .addReg(Tmp, RegState::Kill) 3357 .addImm(IdxMode); 3358 3359 SetOn->getOperand(3).setIsUndef(); 3360 } 3361 3362 return true; 3363 } 3364 3365 if (Offset == 0) { 3366 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3367 .add(*Idx); 3368 } else { 3369 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3370 .add(*Idx) 3371 .addImm(Offset); 3372 } 3373 3374 return true; 3375 } 3376 3377 // Control flow needs to be inserted if indexing with a VGPR. 3378 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3379 MachineBasicBlock &MBB, 3380 const GCNSubtarget &ST) { 3381 const SIInstrInfo *TII = ST.getInstrInfo(); 3382 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3383 MachineFunction *MF = MBB.getParent(); 3384 MachineRegisterInfo &MRI = MF->getRegInfo(); 3385 3386 Register Dst = MI.getOperand(0).getReg(); 3387 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3388 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3389 3390 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3391 3392 unsigned SubReg; 3393 std::tie(SubReg, Offset) 3394 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3395 3396 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3397 3398 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3399 MachineBasicBlock::iterator I(&MI); 3400 const DebugLoc &DL = MI.getDebugLoc(); 3401 3402 if (UseGPRIdxMode) { 3403 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3404 // to avoid interfering with other uses, so probably requires a new 3405 // optimization pass. 3406 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3407 .addReg(SrcReg, RegState::Undef, SubReg) 3408 .addReg(SrcReg, RegState::Implicit) 3409 .addReg(AMDGPU::M0, RegState::Implicit); 3410 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3411 } else { 3412 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3413 .addReg(SrcReg, RegState::Undef, SubReg) 3414 .addReg(SrcReg, RegState::Implicit); 3415 } 3416 3417 MI.eraseFromParent(); 3418 3419 return &MBB; 3420 } 3421 3422 const DebugLoc &DL = MI.getDebugLoc(); 3423 MachineBasicBlock::iterator I(&MI); 3424 3425 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3426 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3427 3428 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3429 3430 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3431 Offset, UseGPRIdxMode, true); 3432 MachineBasicBlock *LoopBB = InsPt->getParent(); 3433 3434 if (UseGPRIdxMode) { 3435 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3436 .addReg(SrcReg, RegState::Undef, SubReg) 3437 .addReg(SrcReg, RegState::Implicit) 3438 .addReg(AMDGPU::M0, RegState::Implicit); 3439 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3440 } else { 3441 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3442 .addReg(SrcReg, RegState::Undef, SubReg) 3443 .addReg(SrcReg, RegState::Implicit); 3444 } 3445 3446 MI.eraseFromParent(); 3447 3448 return LoopBB; 3449 } 3450 3451 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3452 MachineBasicBlock &MBB, 3453 const GCNSubtarget &ST) { 3454 const SIInstrInfo *TII = ST.getInstrInfo(); 3455 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3456 MachineFunction *MF = MBB.getParent(); 3457 MachineRegisterInfo &MRI = MF->getRegInfo(); 3458 3459 Register Dst = MI.getOperand(0).getReg(); 3460 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3461 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3462 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3463 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3464 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3465 3466 // This can be an immediate, but will be folded later. 3467 assert(Val->getReg()); 3468 3469 unsigned SubReg; 3470 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3471 SrcVec->getReg(), 3472 Offset); 3473 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3474 3475 if (Idx->getReg() == AMDGPU::NoRegister) { 3476 MachineBasicBlock::iterator I(&MI); 3477 const DebugLoc &DL = MI.getDebugLoc(); 3478 3479 assert(Offset == 0); 3480 3481 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3482 .add(*SrcVec) 3483 .add(*Val) 3484 .addImm(SubReg); 3485 3486 MI.eraseFromParent(); 3487 return &MBB; 3488 } 3489 3490 const MCInstrDesc &MovRelDesc 3491 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3492 3493 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3494 MachineBasicBlock::iterator I(&MI); 3495 const DebugLoc &DL = MI.getDebugLoc(); 3496 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3497 .addReg(SrcVec->getReg()) 3498 .add(*Val) 3499 .addImm(SubReg); 3500 if (UseGPRIdxMode) 3501 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3502 3503 MI.eraseFromParent(); 3504 return &MBB; 3505 } 3506 3507 if (Val->isReg()) 3508 MRI.clearKillFlags(Val->getReg()); 3509 3510 const DebugLoc &DL = MI.getDebugLoc(); 3511 3512 Register PhiReg = MRI.createVirtualRegister(VecRC); 3513 3514 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3515 Offset, UseGPRIdxMode, false); 3516 MachineBasicBlock *LoopBB = InsPt->getParent(); 3517 3518 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3519 .addReg(PhiReg) 3520 .add(*Val) 3521 .addImm(AMDGPU::sub0); 3522 if (UseGPRIdxMode) 3523 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3524 3525 MI.eraseFromParent(); 3526 return LoopBB; 3527 } 3528 3529 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3530 MachineInstr &MI, MachineBasicBlock *BB) const { 3531 3532 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3533 MachineFunction *MF = BB->getParent(); 3534 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3535 3536 if (TII->isMIMG(MI)) { 3537 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3538 report_fatal_error("missing mem operand from MIMG instruction"); 3539 } 3540 // Add a memoperand for mimg instructions so that they aren't assumed to 3541 // be ordered memory instuctions. 3542 3543 return BB; 3544 } 3545 3546 switch (MI.getOpcode()) { 3547 case AMDGPU::S_ADD_U64_PSEUDO: 3548 case AMDGPU::S_SUB_U64_PSEUDO: { 3549 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3550 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3551 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3552 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3553 const DebugLoc &DL = MI.getDebugLoc(); 3554 3555 MachineOperand &Dest = MI.getOperand(0); 3556 MachineOperand &Src0 = MI.getOperand(1); 3557 MachineOperand &Src1 = MI.getOperand(2); 3558 3559 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3560 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3561 3562 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3563 Src0, BoolRC, AMDGPU::sub0, 3564 &AMDGPU::SReg_32RegClass); 3565 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3566 Src0, BoolRC, AMDGPU::sub1, 3567 &AMDGPU::SReg_32RegClass); 3568 3569 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3570 Src1, BoolRC, AMDGPU::sub0, 3571 &AMDGPU::SReg_32RegClass); 3572 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3573 Src1, BoolRC, AMDGPU::sub1, 3574 &AMDGPU::SReg_32RegClass); 3575 3576 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3577 3578 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3579 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3580 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3581 .add(Src0Sub0) 3582 .add(Src1Sub0); 3583 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3584 .add(Src0Sub1) 3585 .add(Src1Sub1); 3586 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3587 .addReg(DestSub0) 3588 .addImm(AMDGPU::sub0) 3589 .addReg(DestSub1) 3590 .addImm(AMDGPU::sub1); 3591 MI.eraseFromParent(); 3592 return BB; 3593 } 3594 case AMDGPU::SI_INIT_M0: { 3595 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3596 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3597 .add(MI.getOperand(0)); 3598 MI.eraseFromParent(); 3599 return BB; 3600 } 3601 case AMDGPU::SI_INIT_EXEC: 3602 // This should be before all vector instructions. 3603 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3604 AMDGPU::EXEC) 3605 .addImm(MI.getOperand(0).getImm()); 3606 MI.eraseFromParent(); 3607 return BB; 3608 3609 case AMDGPU::SI_INIT_EXEC_LO: 3610 // This should be before all vector instructions. 3611 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3612 AMDGPU::EXEC_LO) 3613 .addImm(MI.getOperand(0).getImm()); 3614 MI.eraseFromParent(); 3615 return BB; 3616 3617 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3618 // Extract the thread count from an SGPR input and set EXEC accordingly. 3619 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3620 // 3621 // S_BFE_U32 count, input, {shift, 7} 3622 // S_BFM_B64 exec, count, 0 3623 // S_CMP_EQ_U32 count, 64 3624 // S_CMOV_B64 exec, -1 3625 MachineInstr *FirstMI = &*BB->begin(); 3626 MachineRegisterInfo &MRI = MF->getRegInfo(); 3627 Register InputReg = MI.getOperand(0).getReg(); 3628 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3629 bool Found = false; 3630 3631 // Move the COPY of the input reg to the beginning, so that we can use it. 3632 for (auto I = BB->begin(); I != &MI; I++) { 3633 if (I->getOpcode() != TargetOpcode::COPY || 3634 I->getOperand(0).getReg() != InputReg) 3635 continue; 3636 3637 if (I == FirstMI) { 3638 FirstMI = &*++BB->begin(); 3639 } else { 3640 I->removeFromParent(); 3641 BB->insert(FirstMI, &*I); 3642 } 3643 Found = true; 3644 break; 3645 } 3646 assert(Found); 3647 (void)Found; 3648 3649 // This should be before all vector instructions. 3650 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3651 bool isWave32 = getSubtarget()->isWave32(); 3652 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3653 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3654 .addReg(InputReg) 3655 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3656 BuildMI(*BB, FirstMI, DebugLoc(), 3657 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3658 Exec) 3659 .addReg(CountReg) 3660 .addImm(0); 3661 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3662 .addReg(CountReg, RegState::Kill) 3663 .addImm(getSubtarget()->getWavefrontSize()); 3664 BuildMI(*BB, FirstMI, DebugLoc(), 3665 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3666 Exec) 3667 .addImm(-1); 3668 MI.eraseFromParent(); 3669 return BB; 3670 } 3671 3672 case AMDGPU::GET_GROUPSTATICSIZE: { 3673 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3674 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3675 DebugLoc DL = MI.getDebugLoc(); 3676 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3677 .add(MI.getOperand(0)) 3678 .addImm(MFI->getLDSSize()); 3679 MI.eraseFromParent(); 3680 return BB; 3681 } 3682 case AMDGPU::SI_INDIRECT_SRC_V1: 3683 case AMDGPU::SI_INDIRECT_SRC_V2: 3684 case AMDGPU::SI_INDIRECT_SRC_V4: 3685 case AMDGPU::SI_INDIRECT_SRC_V8: 3686 case AMDGPU::SI_INDIRECT_SRC_V16: 3687 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3688 case AMDGPU::SI_INDIRECT_DST_V1: 3689 case AMDGPU::SI_INDIRECT_DST_V2: 3690 case AMDGPU::SI_INDIRECT_DST_V4: 3691 case AMDGPU::SI_INDIRECT_DST_V8: 3692 case AMDGPU::SI_INDIRECT_DST_V16: 3693 return emitIndirectDst(MI, *BB, *getSubtarget()); 3694 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3695 case AMDGPU::SI_KILL_I1_PSEUDO: 3696 return splitKillBlock(MI, BB); 3697 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3698 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3699 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3700 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3701 3702 Register Dst = MI.getOperand(0).getReg(); 3703 Register Src0 = MI.getOperand(1).getReg(); 3704 Register Src1 = MI.getOperand(2).getReg(); 3705 const DebugLoc &DL = MI.getDebugLoc(); 3706 Register SrcCond = MI.getOperand(3).getReg(); 3707 3708 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3709 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3710 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3711 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3712 3713 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3714 .addReg(SrcCond); 3715 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3716 .addImm(0) 3717 .addReg(Src0, 0, AMDGPU::sub0) 3718 .addImm(0) 3719 .addReg(Src1, 0, AMDGPU::sub0) 3720 .addReg(SrcCondCopy); 3721 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3722 .addImm(0) 3723 .addReg(Src0, 0, AMDGPU::sub1) 3724 .addImm(0) 3725 .addReg(Src1, 0, AMDGPU::sub1) 3726 .addReg(SrcCondCopy); 3727 3728 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3729 .addReg(DstLo) 3730 .addImm(AMDGPU::sub0) 3731 .addReg(DstHi) 3732 .addImm(AMDGPU::sub1); 3733 MI.eraseFromParent(); 3734 return BB; 3735 } 3736 case AMDGPU::SI_BR_UNDEF: { 3737 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3738 const DebugLoc &DL = MI.getDebugLoc(); 3739 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3740 .add(MI.getOperand(0)); 3741 Br->getOperand(1).setIsUndef(true); // read undef SCC 3742 MI.eraseFromParent(); 3743 return BB; 3744 } 3745 case AMDGPU::ADJCALLSTACKUP: 3746 case AMDGPU::ADJCALLSTACKDOWN: { 3747 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3748 MachineInstrBuilder MIB(*MF, &MI); 3749 3750 // Add an implicit use of the frame offset reg to prevent the restore copy 3751 // inserted after the call from being reorderd after stack operations in the 3752 // the caller's frame. 3753 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3754 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3755 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3756 return BB; 3757 } 3758 case AMDGPU::SI_CALL_ISEL: { 3759 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3760 const DebugLoc &DL = MI.getDebugLoc(); 3761 3762 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3763 3764 MachineInstrBuilder MIB; 3765 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3766 3767 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3768 MIB.add(MI.getOperand(I)); 3769 3770 MIB.cloneMemRefs(MI); 3771 MI.eraseFromParent(); 3772 return BB; 3773 } 3774 case AMDGPU::V_ADD_I32_e32: 3775 case AMDGPU::V_SUB_I32_e32: 3776 case AMDGPU::V_SUBREV_I32_e32: { 3777 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3778 const DebugLoc &DL = MI.getDebugLoc(); 3779 unsigned Opc = MI.getOpcode(); 3780 3781 bool NeedClampOperand = false; 3782 if (TII->pseudoToMCOpcode(Opc) == -1) { 3783 Opc = AMDGPU::getVOPe64(Opc); 3784 NeedClampOperand = true; 3785 } 3786 3787 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3788 if (TII->isVOP3(*I)) { 3789 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3790 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3791 I.addReg(TRI->getVCC(), RegState::Define); 3792 } 3793 I.add(MI.getOperand(1)) 3794 .add(MI.getOperand(2)); 3795 if (NeedClampOperand) 3796 I.addImm(0); // clamp bit for e64 encoding 3797 3798 TII->legalizeOperands(*I); 3799 3800 MI.eraseFromParent(); 3801 return BB; 3802 } 3803 case AMDGPU::DS_GWS_INIT: 3804 case AMDGPU::DS_GWS_SEMA_V: 3805 case AMDGPU::DS_GWS_SEMA_BR: 3806 case AMDGPU::DS_GWS_SEMA_P: 3807 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3808 case AMDGPU::DS_GWS_BARRIER: 3809 // A s_waitcnt 0 is required to be the instruction immediately following. 3810 if (getSubtarget()->hasGWSAutoReplay()) { 3811 bundleInstWithWaitcnt(MI); 3812 return BB; 3813 } 3814 3815 return emitGWSMemViolTestLoop(MI, BB); 3816 default: 3817 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3818 } 3819 } 3820 3821 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3822 return isTypeLegal(VT.getScalarType()); 3823 } 3824 3825 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3826 // This currently forces unfolding various combinations of fsub into fma with 3827 // free fneg'd operands. As long as we have fast FMA (controlled by 3828 // isFMAFasterThanFMulAndFAdd), we should perform these. 3829 3830 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3831 // most of these combines appear to be cycle neutral but save on instruction 3832 // count / code size. 3833 return true; 3834 } 3835 3836 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3837 EVT VT) const { 3838 if (!VT.isVector()) { 3839 return MVT::i1; 3840 } 3841 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3842 } 3843 3844 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3845 // TODO: Should i16 be used always if legal? For now it would force VALU 3846 // shifts. 3847 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3848 } 3849 3850 // Answering this is somewhat tricky and depends on the specific device which 3851 // have different rates for fma or all f64 operations. 3852 // 3853 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3854 // regardless of which device (although the number of cycles differs between 3855 // devices), so it is always profitable for f64. 3856 // 3857 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3858 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3859 // which we can always do even without fused FP ops since it returns the same 3860 // result as the separate operations and since it is always full 3861 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3862 // however does not support denormals, so we do report fma as faster if we have 3863 // a fast fma device and require denormals. 3864 // 3865 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3866 EVT VT) const { 3867 VT = VT.getScalarType(); 3868 3869 switch (VT.getSimpleVT().SimpleTy) { 3870 case MVT::f32: { 3871 // This is as fast on some subtargets. However, we always have full rate f32 3872 // mad available which returns the same result as the separate operations 3873 // which we should prefer over fma. We can't use this if we want to support 3874 // denormals, so only report this in these cases. 3875 if (hasFP32Denormals(MF)) 3876 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3877 3878 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3879 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3880 } 3881 case MVT::f64: 3882 return true; 3883 case MVT::f16: 3884 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3885 default: 3886 break; 3887 } 3888 3889 return false; 3890 } 3891 3892 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3893 const SDNode *N) const { 3894 // TODO: Check future ftz flag 3895 // v_mad_f32/v_mac_f32 do not support denormals. 3896 EVT VT = N->getValueType(0); 3897 if (VT == MVT::f32) 3898 return !hasFP32Denormals(DAG.getMachineFunction()); 3899 if (VT == MVT::f16) { 3900 return Subtarget->hasMadF16() && 3901 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3902 } 3903 3904 return false; 3905 } 3906 3907 //===----------------------------------------------------------------------===// 3908 // Custom DAG Lowering Operations 3909 //===----------------------------------------------------------------------===// 3910 3911 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3912 // wider vector type is legal. 3913 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3914 SelectionDAG &DAG) const { 3915 unsigned Opc = Op.getOpcode(); 3916 EVT VT = Op.getValueType(); 3917 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 3918 3919 SDValue Lo, Hi; 3920 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3921 3922 SDLoc SL(Op); 3923 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3924 Op->getFlags()); 3925 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3926 Op->getFlags()); 3927 3928 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3929 } 3930 3931 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3932 // wider vector type is legal. 3933 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3934 SelectionDAG &DAG) const { 3935 unsigned Opc = Op.getOpcode(); 3936 EVT VT = Op.getValueType(); 3937 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3938 3939 SDValue Lo0, Hi0; 3940 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3941 SDValue Lo1, Hi1; 3942 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3943 3944 SDLoc SL(Op); 3945 3946 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3947 Op->getFlags()); 3948 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3949 Op->getFlags()); 3950 3951 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3952 } 3953 3954 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 3955 SelectionDAG &DAG) const { 3956 unsigned Opc = Op.getOpcode(); 3957 EVT VT = Op.getValueType(); 3958 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3959 3960 SDValue Lo0, Hi0; 3961 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3962 SDValue Lo1, Hi1; 3963 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3964 SDValue Lo2, Hi2; 3965 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 3966 3967 SDLoc SL(Op); 3968 3969 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 3970 Op->getFlags()); 3971 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 3972 Op->getFlags()); 3973 3974 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3975 } 3976 3977 3978 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3979 switch (Op.getOpcode()) { 3980 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3981 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3982 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 3983 case ISD::LOAD: { 3984 SDValue Result = LowerLOAD(Op, DAG); 3985 assert((!Result.getNode() || 3986 Result.getNode()->getNumValues() == 2) && 3987 "Load should return a value and a chain"); 3988 return Result; 3989 } 3990 3991 case ISD::FSIN: 3992 case ISD::FCOS: 3993 return LowerTrig(Op, DAG); 3994 case ISD::SELECT: return LowerSELECT(Op, DAG); 3995 case ISD::FDIV: return LowerFDIV(Op, DAG); 3996 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 3997 case ISD::STORE: return LowerSTORE(Op, DAG); 3998 case ISD::GlobalAddress: { 3999 MachineFunction &MF = DAG.getMachineFunction(); 4000 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4001 return LowerGlobalAddress(MFI, Op, DAG); 4002 } 4003 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4004 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4005 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4006 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4007 case ISD::INSERT_SUBVECTOR: 4008 return lowerINSERT_SUBVECTOR(Op, DAG); 4009 case ISD::INSERT_VECTOR_ELT: 4010 return lowerINSERT_VECTOR_ELT(Op, DAG); 4011 case ISD::EXTRACT_VECTOR_ELT: 4012 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4013 case ISD::VECTOR_SHUFFLE: 4014 return lowerVECTOR_SHUFFLE(Op, DAG); 4015 case ISD::BUILD_VECTOR: 4016 return lowerBUILD_VECTOR(Op, DAG); 4017 case ISD::FP_ROUND: 4018 return lowerFP_ROUND(Op, DAG); 4019 case ISD::TRAP: 4020 return lowerTRAP(Op, DAG); 4021 case ISD::DEBUGTRAP: 4022 return lowerDEBUGTRAP(Op, DAG); 4023 case ISD::FABS: 4024 case ISD::FNEG: 4025 case ISD::FCANONICALIZE: 4026 case ISD::BSWAP: 4027 return splitUnaryVectorOp(Op, DAG); 4028 case ISD::FMINNUM: 4029 case ISD::FMAXNUM: 4030 return lowerFMINNUM_FMAXNUM(Op, DAG); 4031 case ISD::FMA: 4032 return splitTernaryVectorOp(Op, DAG); 4033 case ISD::SHL: 4034 case ISD::SRA: 4035 case ISD::SRL: 4036 case ISD::ADD: 4037 case ISD::SUB: 4038 case ISD::MUL: 4039 case ISD::SMIN: 4040 case ISD::SMAX: 4041 case ISD::UMIN: 4042 case ISD::UMAX: 4043 case ISD::FADD: 4044 case ISD::FMUL: 4045 case ISD::FMINNUM_IEEE: 4046 case ISD::FMAXNUM_IEEE: 4047 return splitBinaryVectorOp(Op, DAG); 4048 } 4049 return SDValue(); 4050 } 4051 4052 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4053 const SDLoc &DL, 4054 SelectionDAG &DAG, bool Unpacked) { 4055 if (!LoadVT.isVector()) 4056 return Result; 4057 4058 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4059 // Truncate to v2i16/v4i16. 4060 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4061 4062 // Workaround legalizer not scalarizing truncate after vector op 4063 // legalization byt not creating intermediate vector trunc. 4064 SmallVector<SDValue, 4> Elts; 4065 DAG.ExtractVectorElements(Result, Elts); 4066 for (SDValue &Elt : Elts) 4067 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4068 4069 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4070 4071 // Bitcast to original type (v2f16/v4f16). 4072 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4073 } 4074 4075 // Cast back to the original packed type. 4076 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4077 } 4078 4079 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4080 MemSDNode *M, 4081 SelectionDAG &DAG, 4082 ArrayRef<SDValue> Ops, 4083 bool IsIntrinsic) const { 4084 SDLoc DL(M); 4085 4086 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4087 EVT LoadVT = M->getValueType(0); 4088 4089 EVT EquivLoadVT = LoadVT; 4090 if (Unpacked && LoadVT.isVector()) { 4091 EquivLoadVT = LoadVT.isVector() ? 4092 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4093 LoadVT.getVectorNumElements()) : LoadVT; 4094 } 4095 4096 // Change from v4f16/v2f16 to EquivLoadVT. 4097 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4098 4099 SDValue Load 4100 = DAG.getMemIntrinsicNode( 4101 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4102 VTList, Ops, M->getMemoryVT(), 4103 M->getMemOperand()); 4104 if (!Unpacked) // Just adjusted the opcode. 4105 return Load; 4106 4107 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4108 4109 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4110 } 4111 4112 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4113 SelectionDAG &DAG, 4114 ArrayRef<SDValue> Ops) const { 4115 SDLoc DL(M); 4116 EVT LoadVT = M->getValueType(0); 4117 EVT EltType = LoadVT.getScalarType(); 4118 EVT IntVT = LoadVT.changeTypeToInteger(); 4119 4120 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4121 4122 unsigned Opc = 4123 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4124 4125 if (IsD16) { 4126 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4127 } 4128 4129 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4130 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4131 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4132 4133 if (isTypeLegal(LoadVT)) { 4134 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4135 M->getMemOperand(), DAG); 4136 } 4137 4138 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4139 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4140 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4141 M->getMemOperand(), DAG); 4142 return DAG.getMergeValues( 4143 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4144 DL); 4145 } 4146 4147 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4148 SDNode *N, SelectionDAG &DAG) { 4149 EVT VT = N->getValueType(0); 4150 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4151 int CondCode = CD->getSExtValue(); 4152 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4153 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4154 return DAG.getUNDEF(VT); 4155 4156 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4157 4158 SDValue LHS = N->getOperand(1); 4159 SDValue RHS = N->getOperand(2); 4160 4161 SDLoc DL(N); 4162 4163 EVT CmpVT = LHS.getValueType(); 4164 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4165 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4166 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4167 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4168 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4169 } 4170 4171 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4172 4173 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4174 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4175 4176 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4177 DAG.getCondCode(CCOpcode)); 4178 if (VT.bitsEq(CCVT)) 4179 return SetCC; 4180 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4181 } 4182 4183 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4184 SDNode *N, SelectionDAG &DAG) { 4185 EVT VT = N->getValueType(0); 4186 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4187 4188 int CondCode = CD->getSExtValue(); 4189 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4190 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4191 return DAG.getUNDEF(VT); 4192 } 4193 4194 SDValue Src0 = N->getOperand(1); 4195 SDValue Src1 = N->getOperand(2); 4196 EVT CmpVT = Src0.getValueType(); 4197 SDLoc SL(N); 4198 4199 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4200 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4201 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4202 } 4203 4204 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4205 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4206 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4207 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4208 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4209 Src1, DAG.getCondCode(CCOpcode)); 4210 if (VT.bitsEq(CCVT)) 4211 return SetCC; 4212 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4213 } 4214 4215 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4216 SmallVectorImpl<SDValue> &Results, 4217 SelectionDAG &DAG) const { 4218 switch (N->getOpcode()) { 4219 case ISD::INSERT_VECTOR_ELT: { 4220 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4221 Results.push_back(Res); 4222 return; 4223 } 4224 case ISD::EXTRACT_VECTOR_ELT: { 4225 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4226 Results.push_back(Res); 4227 return; 4228 } 4229 case ISD::INTRINSIC_WO_CHAIN: { 4230 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4231 switch (IID) { 4232 case Intrinsic::amdgcn_cvt_pkrtz: { 4233 SDValue Src0 = N->getOperand(1); 4234 SDValue Src1 = N->getOperand(2); 4235 SDLoc SL(N); 4236 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4237 Src0, Src1); 4238 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4239 return; 4240 } 4241 case Intrinsic::amdgcn_cvt_pknorm_i16: 4242 case Intrinsic::amdgcn_cvt_pknorm_u16: 4243 case Intrinsic::amdgcn_cvt_pk_i16: 4244 case Intrinsic::amdgcn_cvt_pk_u16: { 4245 SDValue Src0 = N->getOperand(1); 4246 SDValue Src1 = N->getOperand(2); 4247 SDLoc SL(N); 4248 unsigned Opcode; 4249 4250 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4251 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4252 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4253 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4254 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4255 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4256 else 4257 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4258 4259 EVT VT = N->getValueType(0); 4260 if (isTypeLegal(VT)) 4261 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4262 else { 4263 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4264 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4265 } 4266 return; 4267 } 4268 } 4269 break; 4270 } 4271 case ISD::INTRINSIC_W_CHAIN: { 4272 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4273 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4274 // FIXME: Hacky 4275 Results.push_back(Res.getOperand(0)); 4276 Results.push_back(Res.getOperand(1)); 4277 } else { 4278 Results.push_back(Res); 4279 Results.push_back(Res.getValue(1)); 4280 } 4281 return; 4282 } 4283 4284 break; 4285 } 4286 case ISD::SELECT: { 4287 SDLoc SL(N); 4288 EVT VT = N->getValueType(0); 4289 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4290 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4291 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4292 4293 EVT SelectVT = NewVT; 4294 if (NewVT.bitsLT(MVT::i32)) { 4295 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4296 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4297 SelectVT = MVT::i32; 4298 } 4299 4300 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4301 N->getOperand(0), LHS, RHS); 4302 4303 if (NewVT != SelectVT) 4304 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4305 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4306 return; 4307 } 4308 case ISD::FNEG: { 4309 if (N->getValueType(0) != MVT::v2f16) 4310 break; 4311 4312 SDLoc SL(N); 4313 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4314 4315 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4316 BC, 4317 DAG.getConstant(0x80008000, SL, MVT::i32)); 4318 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4319 return; 4320 } 4321 case ISD::FABS: { 4322 if (N->getValueType(0) != MVT::v2f16) 4323 break; 4324 4325 SDLoc SL(N); 4326 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4327 4328 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4329 BC, 4330 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4331 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4332 return; 4333 } 4334 default: 4335 break; 4336 } 4337 } 4338 4339 /// Helper function for LowerBRCOND 4340 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4341 4342 SDNode *Parent = Value.getNode(); 4343 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4344 I != E; ++I) { 4345 4346 if (I.getUse().get() != Value) 4347 continue; 4348 4349 if (I->getOpcode() == Opcode) 4350 return *I; 4351 } 4352 return nullptr; 4353 } 4354 4355 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4356 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4357 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4358 case Intrinsic::amdgcn_if: 4359 return AMDGPUISD::IF; 4360 case Intrinsic::amdgcn_else: 4361 return AMDGPUISD::ELSE; 4362 case Intrinsic::amdgcn_loop: 4363 return AMDGPUISD::LOOP; 4364 case Intrinsic::amdgcn_end_cf: 4365 llvm_unreachable("should not occur"); 4366 default: 4367 return 0; 4368 } 4369 } 4370 4371 // break, if_break, else_break are all only used as inputs to loop, not 4372 // directly as branch conditions. 4373 return 0; 4374 } 4375 4376 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4377 const Triple &TT = getTargetMachine().getTargetTriple(); 4378 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4379 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4380 AMDGPU::shouldEmitConstantsToTextSection(TT); 4381 } 4382 4383 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4384 // FIXME: Either avoid relying on address space here or change the default 4385 // address space for functions to avoid the explicit check. 4386 return (GV->getValueType()->isFunctionTy() || 4387 GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4388 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4389 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4390 !shouldEmitFixup(GV) && 4391 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4392 } 4393 4394 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4395 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4396 } 4397 4398 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4399 if (!GV->hasExternalLinkage()) 4400 return true; 4401 4402 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4403 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4404 } 4405 4406 /// This transforms the control flow intrinsics to get the branch destination as 4407 /// last parameter, also switches branch target with BR if the need arise 4408 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4409 SelectionDAG &DAG) const { 4410 SDLoc DL(BRCOND); 4411 4412 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4413 SDValue Target = BRCOND.getOperand(2); 4414 SDNode *BR = nullptr; 4415 SDNode *SetCC = nullptr; 4416 4417 if (Intr->getOpcode() == ISD::SETCC) { 4418 // As long as we negate the condition everything is fine 4419 SetCC = Intr; 4420 Intr = SetCC->getOperand(0).getNode(); 4421 4422 } else { 4423 // Get the target from BR if we don't negate the condition 4424 BR = findUser(BRCOND, ISD::BR); 4425 Target = BR->getOperand(1); 4426 } 4427 4428 // FIXME: This changes the types of the intrinsics instead of introducing new 4429 // nodes with the correct types. 4430 // e.g. llvm.amdgcn.loop 4431 4432 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4433 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4434 4435 unsigned CFNode = isCFIntrinsic(Intr); 4436 if (CFNode == 0) { 4437 // This is a uniform branch so we don't need to legalize. 4438 return BRCOND; 4439 } 4440 4441 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4442 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4443 4444 assert(!SetCC || 4445 (SetCC->getConstantOperandVal(1) == 1 && 4446 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4447 ISD::SETNE)); 4448 4449 // operands of the new intrinsic call 4450 SmallVector<SDValue, 4> Ops; 4451 if (HaveChain) 4452 Ops.push_back(BRCOND.getOperand(0)); 4453 4454 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4455 Ops.push_back(Target); 4456 4457 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4458 4459 // build the new intrinsic call 4460 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4461 4462 if (!HaveChain) { 4463 SDValue Ops[] = { 4464 SDValue(Result, 0), 4465 BRCOND.getOperand(0) 4466 }; 4467 4468 Result = DAG.getMergeValues(Ops, DL).getNode(); 4469 } 4470 4471 if (BR) { 4472 // Give the branch instruction our target 4473 SDValue Ops[] = { 4474 BR->getOperand(0), 4475 BRCOND.getOperand(2) 4476 }; 4477 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4478 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4479 BR = NewBR.getNode(); 4480 } 4481 4482 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4483 4484 // Copy the intrinsic results to registers 4485 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4486 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4487 if (!CopyToReg) 4488 continue; 4489 4490 Chain = DAG.getCopyToReg( 4491 Chain, DL, 4492 CopyToReg->getOperand(1), 4493 SDValue(Result, i - 1), 4494 SDValue()); 4495 4496 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4497 } 4498 4499 // Remove the old intrinsic from the chain 4500 DAG.ReplaceAllUsesOfValueWith( 4501 SDValue(Intr, Intr->getNumValues() - 1), 4502 Intr->getOperand(0)); 4503 4504 return Chain; 4505 } 4506 4507 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4508 SelectionDAG &DAG) const { 4509 MVT VT = Op.getSimpleValueType(); 4510 SDLoc DL(Op); 4511 // Checking the depth 4512 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4513 return DAG.getConstant(0, DL, VT); 4514 4515 MachineFunction &MF = DAG.getMachineFunction(); 4516 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4517 // Check for kernel and shader functions 4518 if (Info->isEntryFunction()) 4519 return DAG.getConstant(0, DL, VT); 4520 4521 MachineFrameInfo &MFI = MF.getFrameInfo(); 4522 // There is a call to @llvm.returnaddress in this function 4523 MFI.setReturnAddressIsTaken(true); 4524 4525 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4526 // Get the return address reg and mark it as an implicit live-in 4527 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4528 4529 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4530 } 4531 4532 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4533 SDValue Op, 4534 const SDLoc &DL, 4535 EVT VT) const { 4536 return Op.getValueType().bitsLE(VT) ? 4537 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4538 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4539 } 4540 4541 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4542 assert(Op.getValueType() == MVT::f16 && 4543 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4544 4545 SDValue Src = Op.getOperand(0); 4546 EVT SrcVT = Src.getValueType(); 4547 if (SrcVT != MVT::f64) 4548 return Op; 4549 4550 SDLoc DL(Op); 4551 4552 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4553 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4554 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4555 } 4556 4557 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4558 SelectionDAG &DAG) const { 4559 EVT VT = Op.getValueType(); 4560 const MachineFunction &MF = DAG.getMachineFunction(); 4561 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4562 bool IsIEEEMode = Info->getMode().IEEE; 4563 4564 // FIXME: Assert during eslection that this is only selected for 4565 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4566 // mode functions, but this happens to be OK since it's only done in cases 4567 // where there is known no sNaN. 4568 if (IsIEEEMode) 4569 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4570 4571 if (VT == MVT::v4f16) 4572 return splitBinaryVectorOp(Op, DAG); 4573 return Op; 4574 } 4575 4576 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4577 SDLoc SL(Op); 4578 SDValue Chain = Op.getOperand(0); 4579 4580 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4581 !Subtarget->isTrapHandlerEnabled()) 4582 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4583 4584 MachineFunction &MF = DAG.getMachineFunction(); 4585 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4586 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4587 assert(UserSGPR != AMDGPU::NoRegister); 4588 SDValue QueuePtr = CreateLiveInRegister( 4589 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4590 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4591 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4592 QueuePtr, SDValue()); 4593 SDValue Ops[] = { 4594 ToReg, 4595 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4596 SGPR01, 4597 ToReg.getValue(1) 4598 }; 4599 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4600 } 4601 4602 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4603 SDLoc SL(Op); 4604 SDValue Chain = Op.getOperand(0); 4605 MachineFunction &MF = DAG.getMachineFunction(); 4606 4607 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4608 !Subtarget->isTrapHandlerEnabled()) { 4609 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4610 "debugtrap handler not supported", 4611 Op.getDebugLoc(), 4612 DS_Warning); 4613 LLVMContext &Ctx = MF.getFunction().getContext(); 4614 Ctx.diagnose(NoTrap); 4615 return Chain; 4616 } 4617 4618 SDValue Ops[] = { 4619 Chain, 4620 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4621 }; 4622 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4623 } 4624 4625 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4626 SelectionDAG &DAG) const { 4627 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4628 if (Subtarget->hasApertureRegs()) { 4629 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4630 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4631 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4632 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4633 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4634 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4635 unsigned Encoding = 4636 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4637 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4638 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4639 4640 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4641 SDValue ApertureReg = SDValue( 4642 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4643 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4644 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4645 } 4646 4647 MachineFunction &MF = DAG.getMachineFunction(); 4648 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4649 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4650 assert(UserSGPR != AMDGPU::NoRegister); 4651 4652 SDValue QueuePtr = CreateLiveInRegister( 4653 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4654 4655 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4656 // private_segment_aperture_base_hi. 4657 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4658 4659 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4660 4661 // TODO: Use custom target PseudoSourceValue. 4662 // TODO: We should use the value from the IR intrinsic call, but it might not 4663 // be available and how do we get it? 4664 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4665 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4666 MinAlign(64, StructOffset), 4667 MachineMemOperand::MODereferenceable | 4668 MachineMemOperand::MOInvariant); 4669 } 4670 4671 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4672 SelectionDAG &DAG) const { 4673 SDLoc SL(Op); 4674 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4675 4676 SDValue Src = ASC->getOperand(0); 4677 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4678 4679 const AMDGPUTargetMachine &TM = 4680 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4681 4682 // flat -> local/private 4683 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4684 unsigned DestAS = ASC->getDestAddressSpace(); 4685 4686 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4687 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4688 unsigned NullVal = TM.getNullPointerValue(DestAS); 4689 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4690 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4691 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4692 4693 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4694 NonNull, Ptr, SegmentNullPtr); 4695 } 4696 } 4697 4698 // local/private -> flat 4699 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4700 unsigned SrcAS = ASC->getSrcAddressSpace(); 4701 4702 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4703 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4704 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4705 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4706 4707 SDValue NonNull 4708 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4709 4710 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4711 SDValue CvtPtr 4712 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4713 4714 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4715 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4716 FlatNullPtr); 4717 } 4718 } 4719 4720 // global <-> flat are no-ops and never emitted. 4721 4722 const MachineFunction &MF = DAG.getMachineFunction(); 4723 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4724 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4725 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4726 4727 return DAG.getUNDEF(ASC->getValueType(0)); 4728 } 4729 4730 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4731 // the small vector and inserting them into the big vector. That is better than 4732 // the default expansion of doing it via a stack slot. Even though the use of 4733 // the stack slot would be optimized away afterwards, the stack slot itself 4734 // remains. 4735 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4736 SelectionDAG &DAG) const { 4737 SDValue Vec = Op.getOperand(0); 4738 SDValue Ins = Op.getOperand(1); 4739 SDValue Idx = Op.getOperand(2); 4740 EVT VecVT = Vec.getValueType(); 4741 EVT InsVT = Ins.getValueType(); 4742 EVT EltVT = VecVT.getVectorElementType(); 4743 unsigned InsNumElts = InsVT.getVectorNumElements(); 4744 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4745 SDLoc SL(Op); 4746 4747 for (unsigned I = 0; I != InsNumElts; ++I) { 4748 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4749 DAG.getConstant(I, SL, MVT::i32)); 4750 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4751 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4752 } 4753 return Vec; 4754 } 4755 4756 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4757 SelectionDAG &DAG) const { 4758 SDValue Vec = Op.getOperand(0); 4759 SDValue InsVal = Op.getOperand(1); 4760 SDValue Idx = Op.getOperand(2); 4761 EVT VecVT = Vec.getValueType(); 4762 EVT EltVT = VecVT.getVectorElementType(); 4763 unsigned VecSize = VecVT.getSizeInBits(); 4764 unsigned EltSize = EltVT.getSizeInBits(); 4765 4766 4767 assert(VecSize <= 64); 4768 4769 unsigned NumElts = VecVT.getVectorNumElements(); 4770 SDLoc SL(Op); 4771 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4772 4773 if (NumElts == 4 && EltSize == 16 && KIdx) { 4774 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4775 4776 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4777 DAG.getConstant(0, SL, MVT::i32)); 4778 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4779 DAG.getConstant(1, SL, MVT::i32)); 4780 4781 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4782 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4783 4784 unsigned Idx = KIdx->getZExtValue(); 4785 bool InsertLo = Idx < 2; 4786 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4787 InsertLo ? LoVec : HiVec, 4788 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4789 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4790 4791 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4792 4793 SDValue Concat = InsertLo ? 4794 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4795 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4796 4797 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4798 } 4799 4800 if (isa<ConstantSDNode>(Idx)) 4801 return SDValue(); 4802 4803 MVT IntVT = MVT::getIntegerVT(VecSize); 4804 4805 // Avoid stack access for dynamic indexing. 4806 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4807 4808 // Create a congruent vector with the target value in each element so that 4809 // the required element can be masked and ORed into the target vector. 4810 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4811 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4812 4813 assert(isPowerOf2_32(EltSize)); 4814 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4815 4816 // Convert vector index to bit-index. 4817 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4818 4819 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4820 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4821 DAG.getConstant(0xffff, SL, IntVT), 4822 ScaledIdx); 4823 4824 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4825 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4826 DAG.getNOT(SL, BFM, IntVT), BCVec); 4827 4828 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4829 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4830 } 4831 4832 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4833 SelectionDAG &DAG) const { 4834 SDLoc SL(Op); 4835 4836 EVT ResultVT = Op.getValueType(); 4837 SDValue Vec = Op.getOperand(0); 4838 SDValue Idx = Op.getOperand(1); 4839 EVT VecVT = Vec.getValueType(); 4840 unsigned VecSize = VecVT.getSizeInBits(); 4841 EVT EltVT = VecVT.getVectorElementType(); 4842 assert(VecSize <= 64); 4843 4844 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4845 4846 // Make sure we do any optimizations that will make it easier to fold 4847 // source modifiers before obscuring it with bit operations. 4848 4849 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4850 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4851 return Combined; 4852 4853 unsigned EltSize = EltVT.getSizeInBits(); 4854 assert(isPowerOf2_32(EltSize)); 4855 4856 MVT IntVT = MVT::getIntegerVT(VecSize); 4857 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4858 4859 // Convert vector index to bit-index (* EltSize) 4860 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4861 4862 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4863 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4864 4865 if (ResultVT == MVT::f16) { 4866 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4867 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4868 } 4869 4870 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4871 } 4872 4873 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4874 assert(Elt % 2 == 0); 4875 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4876 } 4877 4878 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4879 SelectionDAG &DAG) const { 4880 SDLoc SL(Op); 4881 EVT ResultVT = Op.getValueType(); 4882 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4883 4884 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4885 EVT EltVT = PackVT.getVectorElementType(); 4886 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4887 4888 // vector_shuffle <0,1,6,7> lhs, rhs 4889 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4890 // 4891 // vector_shuffle <6,7,2,3> lhs, rhs 4892 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4893 // 4894 // vector_shuffle <6,7,0,1> lhs, rhs 4895 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4896 4897 // Avoid scalarizing when both halves are reading from consecutive elements. 4898 SmallVector<SDValue, 4> Pieces; 4899 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4900 if (elementPairIsContiguous(SVN->getMask(), I)) { 4901 const int Idx = SVN->getMaskElt(I); 4902 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4903 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4904 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4905 PackVT, SVN->getOperand(VecIdx), 4906 DAG.getConstant(EltIdx, SL, MVT::i32)); 4907 Pieces.push_back(SubVec); 4908 } else { 4909 const int Idx0 = SVN->getMaskElt(I); 4910 const int Idx1 = SVN->getMaskElt(I + 1); 4911 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4912 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4913 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4914 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4915 4916 SDValue Vec0 = SVN->getOperand(VecIdx0); 4917 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4918 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4919 4920 SDValue Vec1 = SVN->getOperand(VecIdx1); 4921 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4922 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4923 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4924 } 4925 } 4926 4927 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4928 } 4929 4930 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4931 SelectionDAG &DAG) const { 4932 SDLoc SL(Op); 4933 EVT VT = Op.getValueType(); 4934 4935 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4936 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4937 4938 // Turn into pair of packed build_vectors. 4939 // TODO: Special case for constants that can be materialized with s_mov_b64. 4940 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4941 { Op.getOperand(0), Op.getOperand(1) }); 4942 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4943 { Op.getOperand(2), Op.getOperand(3) }); 4944 4945 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4946 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4947 4948 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4949 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4950 } 4951 4952 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4953 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4954 4955 SDValue Lo = Op.getOperand(0); 4956 SDValue Hi = Op.getOperand(1); 4957 4958 // Avoid adding defined bits with the zero_extend. 4959 if (Hi.isUndef()) { 4960 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4961 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4962 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4963 } 4964 4965 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4966 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4967 4968 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4969 DAG.getConstant(16, SL, MVT::i32)); 4970 if (Lo.isUndef()) 4971 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4972 4973 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4974 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4975 4976 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4977 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4978 } 4979 4980 bool 4981 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4982 // We can fold offsets for anything that doesn't require a GOT relocation. 4983 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4984 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4985 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4986 !shouldEmitGOTReloc(GA->getGlobal()); 4987 } 4988 4989 static SDValue 4990 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 4991 const SDLoc &DL, unsigned Offset, EVT PtrVT, 4992 unsigned GAFlags = SIInstrInfo::MO_NONE) { 4993 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 4994 // lowered to the following code sequence: 4995 // 4996 // For constant address space: 4997 // s_getpc_b64 s[0:1] 4998 // s_add_u32 s0, s0, $symbol 4999 // s_addc_u32 s1, s1, 0 5000 // 5001 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5002 // a fixup or relocation is emitted to replace $symbol with a literal 5003 // constant, which is a pc-relative offset from the encoding of the $symbol 5004 // operand to the global variable. 5005 // 5006 // For global address space: 5007 // s_getpc_b64 s[0:1] 5008 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5009 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5010 // 5011 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5012 // fixups or relocations are emitted to replace $symbol@*@lo and 5013 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5014 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5015 // operand to the global variable. 5016 // 5017 // What we want here is an offset from the value returned by s_getpc 5018 // (which is the address of the s_add_u32 instruction) to the global 5019 // variable, but since the encoding of $symbol starts 4 bytes after the start 5020 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5021 // small. This requires us to add 4 to the global variable offset in order to 5022 // compute the correct address. 5023 SDValue PtrLo = 5024 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5025 SDValue PtrHi; 5026 if (GAFlags == SIInstrInfo::MO_NONE) { 5027 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5028 } else { 5029 PtrHi = 5030 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5031 } 5032 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5033 } 5034 5035 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5036 SDValue Op, 5037 SelectionDAG &DAG) const { 5038 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5039 const GlobalValue *GV = GSD->getGlobal(); 5040 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5041 shouldUseLDSConstAddress(GV)) || 5042 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5043 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5044 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5045 5046 SDLoc DL(GSD); 5047 EVT PtrVT = Op.getValueType(); 5048 5049 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5050 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5051 SIInstrInfo::MO_ABS32_LO); 5052 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5053 } 5054 5055 if (shouldEmitFixup(GV)) 5056 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5057 else if (shouldEmitPCReloc(GV)) 5058 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5059 SIInstrInfo::MO_REL32); 5060 5061 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5062 SIInstrInfo::MO_GOTPCREL32); 5063 5064 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5065 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5066 const DataLayout &DataLayout = DAG.getDataLayout(); 5067 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5068 MachinePointerInfo PtrInfo 5069 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5070 5071 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5072 MachineMemOperand::MODereferenceable | 5073 MachineMemOperand::MOInvariant); 5074 } 5075 5076 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5077 const SDLoc &DL, SDValue V) const { 5078 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5079 // the destination register. 5080 // 5081 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5082 // so we will end up with redundant moves to m0. 5083 // 5084 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5085 5086 // A Null SDValue creates a glue result. 5087 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5088 V, Chain); 5089 return SDValue(M0, 0); 5090 } 5091 5092 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5093 SDValue Op, 5094 MVT VT, 5095 unsigned Offset) const { 5096 SDLoc SL(Op); 5097 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5098 DAG.getEntryNode(), Offset, 4, false); 5099 // The local size values will have the hi 16-bits as zero. 5100 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5101 DAG.getValueType(VT)); 5102 } 5103 5104 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5105 EVT VT) { 5106 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5107 "non-hsa intrinsic with hsa target", 5108 DL.getDebugLoc()); 5109 DAG.getContext()->diagnose(BadIntrin); 5110 return DAG.getUNDEF(VT); 5111 } 5112 5113 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5114 EVT VT) { 5115 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5116 "intrinsic not supported on subtarget", 5117 DL.getDebugLoc()); 5118 DAG.getContext()->diagnose(BadIntrin); 5119 return DAG.getUNDEF(VT); 5120 } 5121 5122 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5123 ArrayRef<SDValue> Elts) { 5124 assert(!Elts.empty()); 5125 MVT Type; 5126 unsigned NumElts; 5127 5128 if (Elts.size() == 1) { 5129 Type = MVT::f32; 5130 NumElts = 1; 5131 } else if (Elts.size() == 2) { 5132 Type = MVT::v2f32; 5133 NumElts = 2; 5134 } else if (Elts.size() == 3) { 5135 Type = MVT::v3f32; 5136 NumElts = 3; 5137 } else if (Elts.size() <= 4) { 5138 Type = MVT::v4f32; 5139 NumElts = 4; 5140 } else if (Elts.size() <= 8) { 5141 Type = MVT::v8f32; 5142 NumElts = 8; 5143 } else { 5144 assert(Elts.size() <= 16); 5145 Type = MVT::v16f32; 5146 NumElts = 16; 5147 } 5148 5149 SmallVector<SDValue, 16> VecElts(NumElts); 5150 for (unsigned i = 0; i < Elts.size(); ++i) { 5151 SDValue Elt = Elts[i]; 5152 if (Elt.getValueType() != MVT::f32) 5153 Elt = DAG.getBitcast(MVT::f32, Elt); 5154 VecElts[i] = Elt; 5155 } 5156 for (unsigned i = Elts.size(); i < NumElts; ++i) 5157 VecElts[i] = DAG.getUNDEF(MVT::f32); 5158 5159 if (NumElts == 1) 5160 return VecElts[0]; 5161 return DAG.getBuildVector(Type, DL, VecElts); 5162 } 5163 5164 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5165 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5166 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5167 5168 uint64_t Value = CachePolicyConst->getZExtValue(); 5169 SDLoc DL(CachePolicy); 5170 if (GLC) { 5171 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5172 Value &= ~(uint64_t)0x1; 5173 } 5174 if (SLC) { 5175 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5176 Value &= ~(uint64_t)0x2; 5177 } 5178 if (DLC) { 5179 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5180 Value &= ~(uint64_t)0x4; 5181 } 5182 5183 return Value == 0; 5184 } 5185 5186 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5187 SDValue Src, int ExtraElts) { 5188 EVT SrcVT = Src.getValueType(); 5189 5190 SmallVector<SDValue, 8> Elts; 5191 5192 if (SrcVT.isVector()) 5193 DAG.ExtractVectorElements(Src, Elts); 5194 else 5195 Elts.push_back(Src); 5196 5197 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5198 while (ExtraElts--) 5199 Elts.push_back(Undef); 5200 5201 return DAG.getBuildVector(CastVT, DL, Elts); 5202 } 5203 5204 // Re-construct the required return value for a image load intrinsic. 5205 // This is more complicated due to the optional use TexFailCtrl which means the required 5206 // return type is an aggregate 5207 static SDValue constructRetValue(SelectionDAG &DAG, 5208 MachineSDNode *Result, 5209 ArrayRef<EVT> ResultTypes, 5210 bool IsTexFail, bool Unpacked, bool IsD16, 5211 int DMaskPop, int NumVDataDwords, 5212 const SDLoc &DL, LLVMContext &Context) { 5213 // Determine the required return type. This is the same regardless of IsTexFail flag 5214 EVT ReqRetVT = ResultTypes[0]; 5215 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5216 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5217 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5218 5219 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5220 DMaskPop : (DMaskPop + 1) / 2; 5221 5222 MVT DataDwordVT = NumDataDwords == 1 ? 5223 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5224 5225 MVT MaskPopVT = MaskPopDwords == 1 ? 5226 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5227 5228 SDValue Data(Result, 0); 5229 SDValue TexFail; 5230 5231 if (IsTexFail) { 5232 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5233 if (MaskPopVT.isVector()) { 5234 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5235 SDValue(Result, 0), ZeroIdx); 5236 } else { 5237 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5238 SDValue(Result, 0), ZeroIdx); 5239 } 5240 5241 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5242 SDValue(Result, 0), 5243 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5244 } 5245 5246 if (DataDwordVT.isVector()) 5247 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5248 NumDataDwords - MaskPopDwords); 5249 5250 if (IsD16) 5251 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5252 5253 if (!ReqRetVT.isVector()) 5254 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5255 5256 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5257 5258 if (TexFail) 5259 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5260 5261 if (Result->getNumValues() == 1) 5262 return Data; 5263 5264 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5265 } 5266 5267 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5268 SDValue *LWE, bool &IsTexFail) { 5269 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5270 5271 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5272 if (Value) { 5273 IsTexFail = true; 5274 } 5275 5276 SDLoc DL(TexFailCtrlConst); 5277 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5278 Value &= ~(uint64_t)0x1; 5279 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5280 Value &= ~(uint64_t)0x2; 5281 5282 return Value == 0; 5283 } 5284 5285 SDValue SITargetLowering::lowerImage(SDValue Op, 5286 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5287 SelectionDAG &DAG) const { 5288 SDLoc DL(Op); 5289 MachineFunction &MF = DAG.getMachineFunction(); 5290 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5291 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5292 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5293 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5294 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5295 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5296 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5297 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5298 unsigned IntrOpcode = Intr->BaseOpcode; 5299 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5300 5301 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5302 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5303 bool IsD16 = false; 5304 bool IsA16 = false; 5305 SDValue VData; 5306 int NumVDataDwords; 5307 bool AdjustRetType = false; 5308 5309 unsigned AddrIdx; // Index of first address argument 5310 unsigned DMask; 5311 unsigned DMaskLanes = 0; 5312 5313 if (BaseOpcode->Atomic) { 5314 VData = Op.getOperand(2); 5315 5316 bool Is64Bit = VData.getValueType() == MVT::i64; 5317 if (BaseOpcode->AtomicX2) { 5318 SDValue VData2 = Op.getOperand(3); 5319 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5320 {VData, VData2}); 5321 if (Is64Bit) 5322 VData = DAG.getBitcast(MVT::v4i32, VData); 5323 5324 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5325 DMask = Is64Bit ? 0xf : 0x3; 5326 NumVDataDwords = Is64Bit ? 4 : 2; 5327 AddrIdx = 4; 5328 } else { 5329 DMask = Is64Bit ? 0x3 : 0x1; 5330 NumVDataDwords = Is64Bit ? 2 : 1; 5331 AddrIdx = 3; 5332 } 5333 } else { 5334 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5335 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5336 DMask = DMaskConst->getZExtValue(); 5337 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5338 5339 if (BaseOpcode->Store) { 5340 VData = Op.getOperand(2); 5341 5342 MVT StoreVT = VData.getSimpleValueType(); 5343 if (StoreVT.getScalarType() == MVT::f16) { 5344 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5345 return Op; // D16 is unsupported for this instruction 5346 5347 IsD16 = true; 5348 VData = handleD16VData(VData, DAG); 5349 } 5350 5351 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5352 } else { 5353 // Work out the num dwords based on the dmask popcount and underlying type 5354 // and whether packing is supported. 5355 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5356 if (LoadVT.getScalarType() == MVT::f16) { 5357 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5358 return Op; // D16 is unsupported for this instruction 5359 5360 IsD16 = true; 5361 } 5362 5363 // Confirm that the return type is large enough for the dmask specified 5364 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5365 (!LoadVT.isVector() && DMaskLanes > 1)) 5366 return Op; 5367 5368 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5369 NumVDataDwords = (DMaskLanes + 1) / 2; 5370 else 5371 NumVDataDwords = DMaskLanes; 5372 5373 AdjustRetType = true; 5374 } 5375 5376 AddrIdx = DMaskIdx + 1; 5377 } 5378 5379 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5380 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5381 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5382 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5383 NumCoords + NumLCM; 5384 unsigned NumMIVAddrs = NumVAddrs; 5385 5386 SmallVector<SDValue, 4> VAddrs; 5387 5388 // Optimize _L to _LZ when _L is zero 5389 if (LZMappingInfo) { 5390 if (auto ConstantLod = 5391 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5392 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5393 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5394 NumMIVAddrs--; // remove 'lod' 5395 } 5396 } 5397 } 5398 5399 // Optimize _mip away, when 'lod' is zero 5400 if (MIPMappingInfo) { 5401 if (auto ConstantLod = 5402 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5403 if (ConstantLod->isNullValue()) { 5404 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5405 NumMIVAddrs--; // remove 'lod' 5406 } 5407 } 5408 } 5409 5410 // Check for 16 bit addresses and pack if true. 5411 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5412 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5413 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5414 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5415 // Illegal to use a16 images 5416 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5417 return Op; 5418 5419 IsA16 = true; 5420 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5421 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5422 SDValue AddrLo; 5423 // Push back extra arguments. 5424 if (i < DimIdx) { 5425 AddrLo = Op.getOperand(i); 5426 } else { 5427 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5428 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5429 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5430 ((NumGradients / 2) % 2 == 1 && 5431 (i == DimIdx + (NumGradients / 2) - 1 || 5432 i == DimIdx + NumGradients - 1))) { 5433 AddrLo = Op.getOperand(i); 5434 if (AddrLo.getValueType() != MVT::i16) 5435 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5436 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5437 } else { 5438 AddrLo = DAG.getBuildVector(VectorVT, DL, 5439 {Op.getOperand(i), Op.getOperand(i + 1)}); 5440 i++; 5441 } 5442 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5443 } 5444 VAddrs.push_back(AddrLo); 5445 } 5446 } else { 5447 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5448 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5449 } 5450 5451 // If the register allocator cannot place the address registers contiguously 5452 // without introducing moves, then using the non-sequential address encoding 5453 // is always preferable, since it saves VALU instructions and is usually a 5454 // wash in terms of code size or even better. 5455 // 5456 // However, we currently have no way of hinting to the register allocator that 5457 // MIMG addresses should be placed contiguously when it is possible to do so, 5458 // so force non-NSA for the common 2-address case as a heuristic. 5459 // 5460 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5461 // allocation when possible. 5462 bool UseNSA = 5463 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5464 SDValue VAddr; 5465 if (!UseNSA) 5466 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5467 5468 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5469 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5470 unsigned CtrlIdx; // Index of texfailctrl argument 5471 SDValue Unorm; 5472 if (!BaseOpcode->Sampler) { 5473 Unorm = True; 5474 CtrlIdx = AddrIdx + NumVAddrs + 1; 5475 } else { 5476 auto UnormConst = 5477 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5478 5479 Unorm = UnormConst->getZExtValue() ? True : False; 5480 CtrlIdx = AddrIdx + NumVAddrs + 3; 5481 } 5482 5483 SDValue TFE; 5484 SDValue LWE; 5485 SDValue TexFail = Op.getOperand(CtrlIdx); 5486 bool IsTexFail = false; 5487 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5488 return Op; 5489 5490 if (IsTexFail) { 5491 if (!DMaskLanes) { 5492 // Expecting to get an error flag since TFC is on - and dmask is 0 5493 // Force dmask to be at least 1 otherwise the instruction will fail 5494 DMask = 0x1; 5495 DMaskLanes = 1; 5496 NumVDataDwords = 1; 5497 } 5498 NumVDataDwords += 1; 5499 AdjustRetType = true; 5500 } 5501 5502 // Has something earlier tagged that the return type needs adjusting 5503 // This happens if the instruction is a load or has set TexFailCtrl flags 5504 if (AdjustRetType) { 5505 // NumVDataDwords reflects the true number of dwords required in the return type 5506 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5507 // This is a no-op load. This can be eliminated 5508 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5509 if (isa<MemSDNode>(Op)) 5510 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5511 return Undef; 5512 } 5513 5514 EVT NewVT = NumVDataDwords > 1 ? 5515 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5516 : MVT::i32; 5517 5518 ResultTypes[0] = NewVT; 5519 if (ResultTypes.size() == 3) { 5520 // Original result was aggregate type used for TexFailCtrl results 5521 // The actual instruction returns as a vector type which has now been 5522 // created. Remove the aggregate result. 5523 ResultTypes.erase(&ResultTypes[1]); 5524 } 5525 } 5526 5527 SDValue GLC; 5528 SDValue SLC; 5529 SDValue DLC; 5530 if (BaseOpcode->Atomic) { 5531 GLC = True; // TODO no-return optimization 5532 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5533 IsGFX10 ? &DLC : nullptr)) 5534 return Op; 5535 } else { 5536 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5537 IsGFX10 ? &DLC : nullptr)) 5538 return Op; 5539 } 5540 5541 SmallVector<SDValue, 26> Ops; 5542 if (BaseOpcode->Store || BaseOpcode->Atomic) 5543 Ops.push_back(VData); // vdata 5544 if (UseNSA) { 5545 for (const SDValue &Addr : VAddrs) 5546 Ops.push_back(Addr); 5547 } else { 5548 Ops.push_back(VAddr); 5549 } 5550 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5551 if (BaseOpcode->Sampler) 5552 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5553 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5554 if (IsGFX10) 5555 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5556 Ops.push_back(Unorm); 5557 if (IsGFX10) 5558 Ops.push_back(DLC); 5559 Ops.push_back(GLC); 5560 Ops.push_back(SLC); 5561 Ops.push_back(IsA16 && // r128, a16 for gfx9 5562 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5563 if (IsGFX10) 5564 Ops.push_back(IsA16 ? True : False); 5565 Ops.push_back(TFE); 5566 Ops.push_back(LWE); 5567 if (!IsGFX10) 5568 Ops.push_back(DimInfo->DA ? True : False); 5569 if (BaseOpcode->HasD16) 5570 Ops.push_back(IsD16 ? True : False); 5571 if (isa<MemSDNode>(Op)) 5572 Ops.push_back(Op.getOperand(0)); // chain 5573 5574 int NumVAddrDwords = 5575 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5576 int Opcode = -1; 5577 5578 if (IsGFX10) { 5579 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5580 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5581 : AMDGPU::MIMGEncGfx10Default, 5582 NumVDataDwords, NumVAddrDwords); 5583 } else { 5584 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5585 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5586 NumVDataDwords, NumVAddrDwords); 5587 if (Opcode == -1) 5588 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5589 NumVDataDwords, NumVAddrDwords); 5590 } 5591 assert(Opcode != -1); 5592 5593 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5594 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5595 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5596 DAG.setNodeMemRefs(NewNode, {MemRef}); 5597 } 5598 5599 if (BaseOpcode->AtomicX2) { 5600 SmallVector<SDValue, 1> Elt; 5601 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5602 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5603 } else if (!BaseOpcode->Store) { 5604 return constructRetValue(DAG, NewNode, 5605 OrigResultTypes, IsTexFail, 5606 Subtarget->hasUnpackedD16VMem(), IsD16, 5607 DMaskLanes, NumVDataDwords, DL, 5608 *DAG.getContext()); 5609 } 5610 5611 return SDValue(NewNode, 0); 5612 } 5613 5614 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5615 SDValue Offset, SDValue CachePolicy, 5616 SelectionDAG &DAG) const { 5617 MachineFunction &MF = DAG.getMachineFunction(); 5618 5619 const DataLayout &DataLayout = DAG.getDataLayout(); 5620 unsigned Align = 5621 DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5622 5623 MachineMemOperand *MMO = MF.getMachineMemOperand( 5624 MachinePointerInfo(), 5625 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5626 MachineMemOperand::MOInvariant, 5627 VT.getStoreSize(), Align); 5628 5629 if (!Offset->isDivergent()) { 5630 SDValue Ops[] = { 5631 Rsrc, 5632 Offset, // Offset 5633 CachePolicy 5634 }; 5635 5636 // Widen vec3 load to vec4. 5637 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5638 EVT WidenedVT = 5639 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5640 auto WidenedOp = DAG.getMemIntrinsicNode( 5641 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5642 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5643 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5644 DAG.getVectorIdxConstant(0, DL)); 5645 return Subvector; 5646 } 5647 5648 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5649 DAG.getVTList(VT), Ops, VT, MMO); 5650 } 5651 5652 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5653 // assume that the buffer is unswizzled. 5654 SmallVector<SDValue, 4> Loads; 5655 unsigned NumLoads = 1; 5656 MVT LoadVT = VT.getSimpleVT(); 5657 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5658 assert((LoadVT.getScalarType() == MVT::i32 || 5659 LoadVT.getScalarType() == MVT::f32)); 5660 5661 if (NumElts == 8 || NumElts == 16) { 5662 NumLoads = NumElts / 4; 5663 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5664 } 5665 5666 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5667 SDValue Ops[] = { 5668 DAG.getEntryNode(), // Chain 5669 Rsrc, // rsrc 5670 DAG.getConstant(0, DL, MVT::i32), // vindex 5671 {}, // voffset 5672 {}, // soffset 5673 {}, // offset 5674 CachePolicy, // cachepolicy 5675 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5676 }; 5677 5678 // Use the alignment to ensure that the required offsets will fit into the 5679 // immediate offsets. 5680 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5681 5682 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5683 for (unsigned i = 0; i < NumLoads; ++i) { 5684 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5685 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5686 LoadVT, MMO, DAG)); 5687 } 5688 5689 if (NumElts == 8 || NumElts == 16) 5690 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5691 5692 return Loads[0]; 5693 } 5694 5695 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5696 SelectionDAG &DAG) const { 5697 MachineFunction &MF = DAG.getMachineFunction(); 5698 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5699 5700 EVT VT = Op.getValueType(); 5701 SDLoc DL(Op); 5702 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5703 5704 // TODO: Should this propagate fast-math-flags? 5705 5706 switch (IntrinsicID) { 5707 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5708 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5709 return emitNonHSAIntrinsicError(DAG, DL, VT); 5710 return getPreloadedValue(DAG, *MFI, VT, 5711 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5712 } 5713 case Intrinsic::amdgcn_dispatch_ptr: 5714 case Intrinsic::amdgcn_queue_ptr: { 5715 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5716 DiagnosticInfoUnsupported BadIntrin( 5717 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5718 DL.getDebugLoc()); 5719 DAG.getContext()->diagnose(BadIntrin); 5720 return DAG.getUNDEF(VT); 5721 } 5722 5723 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5724 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5725 return getPreloadedValue(DAG, *MFI, VT, RegID); 5726 } 5727 case Intrinsic::amdgcn_implicitarg_ptr: { 5728 if (MFI->isEntryFunction()) 5729 return getImplicitArgPtr(DAG, DL); 5730 return getPreloadedValue(DAG, *MFI, VT, 5731 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5732 } 5733 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5734 return getPreloadedValue(DAG, *MFI, VT, 5735 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5736 } 5737 case Intrinsic::amdgcn_dispatch_id: { 5738 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5739 } 5740 case Intrinsic::amdgcn_rcp: 5741 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5742 case Intrinsic::amdgcn_rsq: 5743 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5744 case Intrinsic::amdgcn_rsq_legacy: 5745 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5746 return emitRemovedIntrinsicError(DAG, DL, VT); 5747 5748 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5749 case Intrinsic::amdgcn_rcp_legacy: 5750 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5751 return emitRemovedIntrinsicError(DAG, DL, VT); 5752 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5753 case Intrinsic::amdgcn_rsq_clamp: { 5754 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5755 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5756 5757 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5758 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5759 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5760 5761 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5762 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5763 DAG.getConstantFP(Max, DL, VT)); 5764 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5765 DAG.getConstantFP(Min, DL, VT)); 5766 } 5767 case Intrinsic::r600_read_ngroups_x: 5768 if (Subtarget->isAmdHsaOS()) 5769 return emitNonHSAIntrinsicError(DAG, DL, VT); 5770 5771 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5772 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5773 case Intrinsic::r600_read_ngroups_y: 5774 if (Subtarget->isAmdHsaOS()) 5775 return emitNonHSAIntrinsicError(DAG, DL, VT); 5776 5777 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5778 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5779 case Intrinsic::r600_read_ngroups_z: 5780 if (Subtarget->isAmdHsaOS()) 5781 return emitNonHSAIntrinsicError(DAG, DL, VT); 5782 5783 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5784 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5785 case Intrinsic::r600_read_global_size_x: 5786 if (Subtarget->isAmdHsaOS()) 5787 return emitNonHSAIntrinsicError(DAG, DL, VT); 5788 5789 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5790 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5791 case Intrinsic::r600_read_global_size_y: 5792 if (Subtarget->isAmdHsaOS()) 5793 return emitNonHSAIntrinsicError(DAG, DL, VT); 5794 5795 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5796 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5797 case Intrinsic::r600_read_global_size_z: 5798 if (Subtarget->isAmdHsaOS()) 5799 return emitNonHSAIntrinsicError(DAG, DL, VT); 5800 5801 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5802 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5803 case Intrinsic::r600_read_local_size_x: 5804 if (Subtarget->isAmdHsaOS()) 5805 return emitNonHSAIntrinsicError(DAG, DL, VT); 5806 5807 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5808 SI::KernelInputOffsets::LOCAL_SIZE_X); 5809 case Intrinsic::r600_read_local_size_y: 5810 if (Subtarget->isAmdHsaOS()) 5811 return emitNonHSAIntrinsicError(DAG, DL, VT); 5812 5813 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5814 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5815 case Intrinsic::r600_read_local_size_z: 5816 if (Subtarget->isAmdHsaOS()) 5817 return emitNonHSAIntrinsicError(DAG, DL, VT); 5818 5819 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5820 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5821 case Intrinsic::amdgcn_workgroup_id_x: 5822 return getPreloadedValue(DAG, *MFI, VT, 5823 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5824 case Intrinsic::amdgcn_workgroup_id_y: 5825 return getPreloadedValue(DAG, *MFI, VT, 5826 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5827 case Intrinsic::amdgcn_workgroup_id_z: 5828 return getPreloadedValue(DAG, *MFI, VT, 5829 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5830 case Intrinsic::amdgcn_workitem_id_x: 5831 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5832 SDLoc(DAG.getEntryNode()), 5833 MFI->getArgInfo().WorkItemIDX); 5834 case Intrinsic::amdgcn_workitem_id_y: 5835 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5836 SDLoc(DAG.getEntryNode()), 5837 MFI->getArgInfo().WorkItemIDY); 5838 case Intrinsic::amdgcn_workitem_id_z: 5839 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5840 SDLoc(DAG.getEntryNode()), 5841 MFI->getArgInfo().WorkItemIDZ); 5842 case Intrinsic::amdgcn_wavefrontsize: 5843 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5844 SDLoc(Op), MVT::i32); 5845 case Intrinsic::amdgcn_s_buffer_load: { 5846 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5847 SDValue GLC; 5848 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5849 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5850 IsGFX10 ? &DLC : nullptr)) 5851 return Op; 5852 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5853 DAG); 5854 } 5855 case Intrinsic::amdgcn_fdiv_fast: 5856 return lowerFDIV_FAST(Op, DAG); 5857 case Intrinsic::amdgcn_sin: 5858 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5859 5860 case Intrinsic::amdgcn_cos: 5861 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5862 5863 case Intrinsic::amdgcn_mul_u24: 5864 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5865 case Intrinsic::amdgcn_mul_i24: 5866 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5867 5868 case Intrinsic::amdgcn_log_clamp: { 5869 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5870 return SDValue(); 5871 5872 DiagnosticInfoUnsupported BadIntrin( 5873 MF.getFunction(), "intrinsic not supported on subtarget", 5874 DL.getDebugLoc()); 5875 DAG.getContext()->diagnose(BadIntrin); 5876 return DAG.getUNDEF(VT); 5877 } 5878 case Intrinsic::amdgcn_ldexp: 5879 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5880 Op.getOperand(1), Op.getOperand(2)); 5881 5882 case Intrinsic::amdgcn_fract: 5883 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5884 5885 case Intrinsic::amdgcn_class: 5886 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5887 Op.getOperand(1), Op.getOperand(2)); 5888 case Intrinsic::amdgcn_div_fmas: 5889 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5890 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5891 Op.getOperand(4)); 5892 5893 case Intrinsic::amdgcn_div_fixup: 5894 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5895 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5896 5897 case Intrinsic::amdgcn_trig_preop: 5898 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5899 Op.getOperand(1), Op.getOperand(2)); 5900 case Intrinsic::amdgcn_div_scale: { 5901 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5902 5903 // Translate to the operands expected by the machine instruction. The 5904 // first parameter must be the same as the first instruction. 5905 SDValue Numerator = Op.getOperand(1); 5906 SDValue Denominator = Op.getOperand(2); 5907 5908 // Note this order is opposite of the machine instruction's operations, 5909 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5910 // intrinsic has the numerator as the first operand to match a normal 5911 // division operation. 5912 5913 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5914 5915 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5916 Denominator, Numerator); 5917 } 5918 case Intrinsic::amdgcn_icmp: { 5919 // There is a Pat that handles this variant, so return it as-is. 5920 if (Op.getOperand(1).getValueType() == MVT::i1 && 5921 Op.getConstantOperandVal(2) == 0 && 5922 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5923 return Op; 5924 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5925 } 5926 case Intrinsic::amdgcn_fcmp: { 5927 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5928 } 5929 case Intrinsic::amdgcn_fmed3: 5930 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5931 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5932 case Intrinsic::amdgcn_fdot2: 5933 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5934 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5935 Op.getOperand(4)); 5936 case Intrinsic::amdgcn_fmul_legacy: 5937 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5938 Op.getOperand(1), Op.getOperand(2)); 5939 case Intrinsic::amdgcn_sffbh: 5940 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5941 case Intrinsic::amdgcn_sbfe: 5942 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5943 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5944 case Intrinsic::amdgcn_ubfe: 5945 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5946 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5947 case Intrinsic::amdgcn_cvt_pkrtz: 5948 case Intrinsic::amdgcn_cvt_pknorm_i16: 5949 case Intrinsic::amdgcn_cvt_pknorm_u16: 5950 case Intrinsic::amdgcn_cvt_pk_i16: 5951 case Intrinsic::amdgcn_cvt_pk_u16: { 5952 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5953 EVT VT = Op.getValueType(); 5954 unsigned Opcode; 5955 5956 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5957 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5958 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5959 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5960 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5961 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5962 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5963 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5964 else 5965 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5966 5967 if (isTypeLegal(VT)) 5968 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5969 5970 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5971 Op.getOperand(1), Op.getOperand(2)); 5972 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5973 } 5974 case Intrinsic::amdgcn_fmad_ftz: 5975 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5976 Op.getOperand(2), Op.getOperand(3)); 5977 5978 case Intrinsic::amdgcn_if_break: 5979 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5980 Op->getOperand(1), Op->getOperand(2)), 0); 5981 5982 case Intrinsic::amdgcn_groupstaticsize: { 5983 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 5984 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 5985 return Op; 5986 5987 const Module *M = MF.getFunction().getParent(); 5988 const GlobalValue *GV = 5989 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 5990 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 5991 SIInstrInfo::MO_ABS32_LO); 5992 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 5993 } 5994 case Intrinsic::amdgcn_is_shared: 5995 case Intrinsic::amdgcn_is_private: { 5996 SDLoc SL(Op); 5997 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 5998 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 5999 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6000 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6001 Op.getOperand(1)); 6002 6003 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6004 DAG.getConstant(1, SL, MVT::i32)); 6005 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6006 } 6007 default: 6008 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6009 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6010 return lowerImage(Op, ImageDimIntr, DAG); 6011 6012 return Op; 6013 } 6014 } 6015 6016 // This function computes an appropriate offset to pass to 6017 // MachineMemOperand::setOffset() based on the offset inputs to 6018 // an intrinsic. If any of the offsets are non-contstant or 6019 // if VIndex is non-zero then this function returns 0. Otherwise, 6020 // it returns the sum of VOffset, SOffset, and Offset. 6021 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6022 SDValue SOffset, 6023 SDValue Offset, 6024 SDValue VIndex = SDValue()) { 6025 6026 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6027 !isa<ConstantSDNode>(Offset)) 6028 return 0; 6029 6030 if (VIndex) { 6031 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6032 return 0; 6033 } 6034 6035 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6036 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6037 cast<ConstantSDNode>(Offset)->getSExtValue(); 6038 } 6039 6040 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6041 switch (MF.getFunction().getCallingConv()) { 6042 case CallingConv::AMDGPU_PS: 6043 return 1; 6044 case CallingConv::AMDGPU_VS: 6045 return 2; 6046 case CallingConv::AMDGPU_GS: 6047 return 3; 6048 case CallingConv::AMDGPU_HS: 6049 case CallingConv::AMDGPU_LS: 6050 case CallingConv::AMDGPU_ES: 6051 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6052 case CallingConv::AMDGPU_CS: 6053 case CallingConv::AMDGPU_KERNEL: 6054 case CallingConv::C: 6055 case CallingConv::Fast: 6056 default: 6057 // Assume other calling conventions are various compute callable functions 6058 return 0; 6059 } 6060 } 6061 6062 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6063 SelectionDAG &DAG) const { 6064 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6065 SDLoc DL(Op); 6066 6067 switch (IntrID) { 6068 case Intrinsic::amdgcn_ds_ordered_add: 6069 case Intrinsic::amdgcn_ds_ordered_swap: { 6070 MemSDNode *M = cast<MemSDNode>(Op); 6071 SDValue Chain = M->getOperand(0); 6072 SDValue M0 = M->getOperand(2); 6073 SDValue Value = M->getOperand(3); 6074 unsigned IndexOperand = M->getConstantOperandVal(7); 6075 unsigned WaveRelease = M->getConstantOperandVal(8); 6076 unsigned WaveDone = M->getConstantOperandVal(9); 6077 6078 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6079 IndexOperand &= ~0x3f; 6080 unsigned CountDw = 0; 6081 6082 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6083 CountDw = (IndexOperand >> 24) & 0xf; 6084 IndexOperand &= ~(0xf << 24); 6085 6086 if (CountDw < 1 || CountDw > 4) { 6087 report_fatal_error( 6088 "ds_ordered_count: dword count must be between 1 and 4"); 6089 } 6090 } 6091 6092 if (IndexOperand) 6093 report_fatal_error("ds_ordered_count: bad index operand"); 6094 6095 if (WaveDone && !WaveRelease) 6096 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6097 6098 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6099 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6100 unsigned Offset0 = OrderedCountIndex << 2; 6101 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6102 (Instruction << 4); 6103 6104 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6105 Offset1 |= (CountDw - 1) << 6; 6106 6107 unsigned Offset = Offset0 | (Offset1 << 8); 6108 6109 SDValue Ops[] = { 6110 Chain, 6111 Value, 6112 DAG.getTargetConstant(Offset, DL, MVT::i16), 6113 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6114 }; 6115 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6116 M->getVTList(), Ops, M->getMemoryVT(), 6117 M->getMemOperand()); 6118 } 6119 case Intrinsic::amdgcn_ds_fadd: { 6120 MemSDNode *M = cast<MemSDNode>(Op); 6121 unsigned Opc; 6122 switch (IntrID) { 6123 case Intrinsic::amdgcn_ds_fadd: 6124 Opc = ISD::ATOMIC_LOAD_FADD; 6125 break; 6126 } 6127 6128 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6129 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6130 M->getMemOperand()); 6131 } 6132 case Intrinsic::amdgcn_atomic_inc: 6133 case Intrinsic::amdgcn_atomic_dec: 6134 case Intrinsic::amdgcn_ds_fmin: 6135 case Intrinsic::amdgcn_ds_fmax: { 6136 MemSDNode *M = cast<MemSDNode>(Op); 6137 unsigned Opc; 6138 switch (IntrID) { 6139 case Intrinsic::amdgcn_atomic_inc: 6140 Opc = AMDGPUISD::ATOMIC_INC; 6141 break; 6142 case Intrinsic::amdgcn_atomic_dec: 6143 Opc = AMDGPUISD::ATOMIC_DEC; 6144 break; 6145 case Intrinsic::amdgcn_ds_fmin: 6146 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6147 break; 6148 case Intrinsic::amdgcn_ds_fmax: 6149 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6150 break; 6151 default: 6152 llvm_unreachable("Unknown intrinsic!"); 6153 } 6154 SDValue Ops[] = { 6155 M->getOperand(0), // Chain 6156 M->getOperand(2), // Ptr 6157 M->getOperand(3) // Value 6158 }; 6159 6160 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6161 M->getMemoryVT(), M->getMemOperand()); 6162 } 6163 case Intrinsic::amdgcn_buffer_load: 6164 case Intrinsic::amdgcn_buffer_load_format: { 6165 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6166 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6167 unsigned IdxEn = 1; 6168 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6169 IdxEn = Idx->getZExtValue() != 0; 6170 SDValue Ops[] = { 6171 Op.getOperand(0), // Chain 6172 Op.getOperand(2), // rsrc 6173 Op.getOperand(3), // vindex 6174 SDValue(), // voffset -- will be set by setBufferOffsets 6175 SDValue(), // soffset -- will be set by setBufferOffsets 6176 SDValue(), // offset -- will be set by setBufferOffsets 6177 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6178 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6179 }; 6180 6181 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6182 // We don't know the offset if vindex is non-zero, so clear it. 6183 if (IdxEn) 6184 Offset = 0; 6185 6186 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6187 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6188 6189 EVT VT = Op.getValueType(); 6190 EVT IntVT = VT.changeTypeToInteger(); 6191 auto *M = cast<MemSDNode>(Op); 6192 M->getMemOperand()->setOffset(Offset); 6193 EVT LoadVT = Op.getValueType(); 6194 6195 if (LoadVT.getScalarType() == MVT::f16) 6196 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6197 M, DAG, Ops); 6198 6199 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6200 if (LoadVT.getScalarType() == MVT::i8 || 6201 LoadVT.getScalarType() == MVT::i16) 6202 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6203 6204 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6205 M->getMemOperand(), DAG); 6206 } 6207 case Intrinsic::amdgcn_raw_buffer_load: 6208 case Intrinsic::amdgcn_raw_buffer_load_format: { 6209 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6210 6211 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6212 SDValue Ops[] = { 6213 Op.getOperand(0), // Chain 6214 Op.getOperand(2), // rsrc 6215 DAG.getConstant(0, DL, MVT::i32), // vindex 6216 Offsets.first, // voffset 6217 Op.getOperand(4), // soffset 6218 Offsets.second, // offset 6219 Op.getOperand(5), // cachepolicy, swizzled buffer 6220 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6221 }; 6222 6223 auto *M = cast<MemSDNode>(Op); 6224 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6225 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6226 } 6227 case Intrinsic::amdgcn_struct_buffer_load: 6228 case Intrinsic::amdgcn_struct_buffer_load_format: { 6229 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6230 6231 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6232 SDValue Ops[] = { 6233 Op.getOperand(0), // Chain 6234 Op.getOperand(2), // rsrc 6235 Op.getOperand(3), // vindex 6236 Offsets.first, // voffset 6237 Op.getOperand(5), // soffset 6238 Offsets.second, // offset 6239 Op.getOperand(6), // cachepolicy, swizzled buffer 6240 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6241 }; 6242 6243 auto *M = cast<MemSDNode>(Op); 6244 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6245 Ops[2])); 6246 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6247 } 6248 case Intrinsic::amdgcn_tbuffer_load: { 6249 MemSDNode *M = cast<MemSDNode>(Op); 6250 EVT LoadVT = Op.getValueType(); 6251 6252 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6253 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6254 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6255 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6256 unsigned IdxEn = 1; 6257 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6258 IdxEn = Idx->getZExtValue() != 0; 6259 SDValue Ops[] = { 6260 Op.getOperand(0), // Chain 6261 Op.getOperand(2), // rsrc 6262 Op.getOperand(3), // vindex 6263 Op.getOperand(4), // voffset 6264 Op.getOperand(5), // soffset 6265 Op.getOperand(6), // offset 6266 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6267 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6268 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6269 }; 6270 6271 if (LoadVT.getScalarType() == MVT::f16) 6272 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6273 M, DAG, Ops); 6274 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6275 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6276 DAG); 6277 } 6278 case Intrinsic::amdgcn_raw_tbuffer_load: { 6279 MemSDNode *M = cast<MemSDNode>(Op); 6280 EVT LoadVT = Op.getValueType(); 6281 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6282 6283 SDValue Ops[] = { 6284 Op.getOperand(0), // Chain 6285 Op.getOperand(2), // rsrc 6286 DAG.getConstant(0, DL, MVT::i32), // vindex 6287 Offsets.first, // voffset 6288 Op.getOperand(4), // soffset 6289 Offsets.second, // offset 6290 Op.getOperand(5), // format 6291 Op.getOperand(6), // cachepolicy, swizzled buffer 6292 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6293 }; 6294 6295 if (LoadVT.getScalarType() == MVT::f16) 6296 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6297 M, DAG, Ops); 6298 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6299 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6300 DAG); 6301 } 6302 case Intrinsic::amdgcn_struct_tbuffer_load: { 6303 MemSDNode *M = cast<MemSDNode>(Op); 6304 EVT LoadVT = Op.getValueType(); 6305 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6306 6307 SDValue Ops[] = { 6308 Op.getOperand(0), // Chain 6309 Op.getOperand(2), // rsrc 6310 Op.getOperand(3), // vindex 6311 Offsets.first, // voffset 6312 Op.getOperand(5), // soffset 6313 Offsets.second, // offset 6314 Op.getOperand(6), // format 6315 Op.getOperand(7), // cachepolicy, swizzled buffer 6316 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6317 }; 6318 6319 if (LoadVT.getScalarType() == MVT::f16) 6320 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6321 M, DAG, Ops); 6322 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6323 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6324 DAG); 6325 } 6326 case Intrinsic::amdgcn_buffer_atomic_swap: 6327 case Intrinsic::amdgcn_buffer_atomic_add: 6328 case Intrinsic::amdgcn_buffer_atomic_sub: 6329 case Intrinsic::amdgcn_buffer_atomic_smin: 6330 case Intrinsic::amdgcn_buffer_atomic_umin: 6331 case Intrinsic::amdgcn_buffer_atomic_smax: 6332 case Intrinsic::amdgcn_buffer_atomic_umax: 6333 case Intrinsic::amdgcn_buffer_atomic_and: 6334 case Intrinsic::amdgcn_buffer_atomic_or: 6335 case Intrinsic::amdgcn_buffer_atomic_xor: { 6336 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6337 unsigned IdxEn = 1; 6338 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6339 IdxEn = Idx->getZExtValue() != 0; 6340 SDValue Ops[] = { 6341 Op.getOperand(0), // Chain 6342 Op.getOperand(2), // vdata 6343 Op.getOperand(3), // rsrc 6344 Op.getOperand(4), // vindex 6345 SDValue(), // voffset -- will be set by setBufferOffsets 6346 SDValue(), // soffset -- will be set by setBufferOffsets 6347 SDValue(), // offset -- will be set by setBufferOffsets 6348 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6349 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6350 }; 6351 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6352 // We don't know the offset if vindex is non-zero, so clear it. 6353 if (IdxEn) 6354 Offset = 0; 6355 EVT VT = Op.getValueType(); 6356 6357 auto *M = cast<MemSDNode>(Op); 6358 M->getMemOperand()->setOffset(Offset); 6359 unsigned Opcode = 0; 6360 6361 switch (IntrID) { 6362 case Intrinsic::amdgcn_buffer_atomic_swap: 6363 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6364 break; 6365 case Intrinsic::amdgcn_buffer_atomic_add: 6366 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6367 break; 6368 case Intrinsic::amdgcn_buffer_atomic_sub: 6369 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6370 break; 6371 case Intrinsic::amdgcn_buffer_atomic_smin: 6372 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6373 break; 6374 case Intrinsic::amdgcn_buffer_atomic_umin: 6375 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6376 break; 6377 case Intrinsic::amdgcn_buffer_atomic_smax: 6378 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6379 break; 6380 case Intrinsic::amdgcn_buffer_atomic_umax: 6381 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6382 break; 6383 case Intrinsic::amdgcn_buffer_atomic_and: 6384 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6385 break; 6386 case Intrinsic::amdgcn_buffer_atomic_or: 6387 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6388 break; 6389 case Intrinsic::amdgcn_buffer_atomic_xor: 6390 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6391 break; 6392 default: 6393 llvm_unreachable("unhandled atomic opcode"); 6394 } 6395 6396 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6397 M->getMemOperand()); 6398 } 6399 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6400 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6401 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6402 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6403 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6404 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6405 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6406 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6407 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6408 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6409 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6410 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6411 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6412 SDValue Ops[] = { 6413 Op.getOperand(0), // Chain 6414 Op.getOperand(2), // vdata 6415 Op.getOperand(3), // rsrc 6416 DAG.getConstant(0, DL, MVT::i32), // vindex 6417 Offsets.first, // voffset 6418 Op.getOperand(5), // soffset 6419 Offsets.second, // offset 6420 Op.getOperand(6), // cachepolicy 6421 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6422 }; 6423 EVT VT = Op.getValueType(); 6424 6425 auto *M = cast<MemSDNode>(Op); 6426 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6427 unsigned Opcode = 0; 6428 6429 switch (IntrID) { 6430 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6431 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6432 break; 6433 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6434 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6435 break; 6436 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6437 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6438 break; 6439 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6440 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6441 break; 6442 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6443 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6444 break; 6445 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6446 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6447 break; 6448 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6449 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6450 break; 6451 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6452 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6453 break; 6454 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6455 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6456 break; 6457 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6458 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6459 break; 6460 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6461 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6462 break; 6463 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6464 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6465 break; 6466 default: 6467 llvm_unreachable("unhandled atomic opcode"); 6468 } 6469 6470 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6471 M->getMemOperand()); 6472 } 6473 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6474 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6475 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6476 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6477 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6478 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6479 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6480 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6481 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6482 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6483 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6484 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6485 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6486 SDValue Ops[] = { 6487 Op.getOperand(0), // Chain 6488 Op.getOperand(2), // vdata 6489 Op.getOperand(3), // rsrc 6490 Op.getOperand(4), // vindex 6491 Offsets.first, // voffset 6492 Op.getOperand(6), // soffset 6493 Offsets.second, // offset 6494 Op.getOperand(7), // cachepolicy 6495 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6496 }; 6497 EVT VT = Op.getValueType(); 6498 6499 auto *M = cast<MemSDNode>(Op); 6500 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6501 Ops[3])); 6502 unsigned Opcode = 0; 6503 6504 switch (IntrID) { 6505 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6506 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6507 break; 6508 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6509 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6510 break; 6511 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6512 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6513 break; 6514 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6515 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6516 break; 6517 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6518 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6519 break; 6520 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6521 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6522 break; 6523 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6524 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6525 break; 6526 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6527 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6528 break; 6529 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6530 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6531 break; 6532 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6533 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6534 break; 6535 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6536 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6537 break; 6538 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6539 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6540 break; 6541 default: 6542 llvm_unreachable("unhandled atomic opcode"); 6543 } 6544 6545 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6546 M->getMemOperand()); 6547 } 6548 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6549 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6550 unsigned IdxEn = 1; 6551 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6552 IdxEn = Idx->getZExtValue() != 0; 6553 SDValue Ops[] = { 6554 Op.getOperand(0), // Chain 6555 Op.getOperand(2), // src 6556 Op.getOperand(3), // cmp 6557 Op.getOperand(4), // rsrc 6558 Op.getOperand(5), // vindex 6559 SDValue(), // voffset -- will be set by setBufferOffsets 6560 SDValue(), // soffset -- will be set by setBufferOffsets 6561 SDValue(), // offset -- will be set by setBufferOffsets 6562 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6563 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6564 }; 6565 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6566 // We don't know the offset if vindex is non-zero, so clear it. 6567 if (IdxEn) 6568 Offset = 0; 6569 EVT VT = Op.getValueType(); 6570 auto *M = cast<MemSDNode>(Op); 6571 M->getMemOperand()->setOffset(Offset); 6572 6573 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6574 Op->getVTList(), Ops, VT, M->getMemOperand()); 6575 } 6576 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6577 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6578 SDValue Ops[] = { 6579 Op.getOperand(0), // Chain 6580 Op.getOperand(2), // src 6581 Op.getOperand(3), // cmp 6582 Op.getOperand(4), // rsrc 6583 DAG.getConstant(0, DL, MVT::i32), // vindex 6584 Offsets.first, // voffset 6585 Op.getOperand(6), // soffset 6586 Offsets.second, // offset 6587 Op.getOperand(7), // cachepolicy 6588 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6589 }; 6590 EVT VT = Op.getValueType(); 6591 auto *M = cast<MemSDNode>(Op); 6592 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6593 6594 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6595 Op->getVTList(), Ops, VT, M->getMemOperand()); 6596 } 6597 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6598 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6599 SDValue Ops[] = { 6600 Op.getOperand(0), // Chain 6601 Op.getOperand(2), // src 6602 Op.getOperand(3), // cmp 6603 Op.getOperand(4), // rsrc 6604 Op.getOperand(5), // vindex 6605 Offsets.first, // voffset 6606 Op.getOperand(7), // soffset 6607 Offsets.second, // offset 6608 Op.getOperand(8), // cachepolicy 6609 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6610 }; 6611 EVT VT = Op.getValueType(); 6612 auto *M = cast<MemSDNode>(Op); 6613 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6614 Ops[4])); 6615 6616 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6617 Op->getVTList(), Ops, VT, M->getMemOperand()); 6618 } 6619 6620 default: 6621 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6622 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6623 return lowerImage(Op, ImageDimIntr, DAG); 6624 6625 return SDValue(); 6626 } 6627 } 6628 6629 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6630 // dwordx4 if on SI. 6631 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6632 SDVTList VTList, 6633 ArrayRef<SDValue> Ops, EVT MemVT, 6634 MachineMemOperand *MMO, 6635 SelectionDAG &DAG) const { 6636 EVT VT = VTList.VTs[0]; 6637 EVT WidenedVT = VT; 6638 EVT WidenedMemVT = MemVT; 6639 if (!Subtarget->hasDwordx3LoadStores() && 6640 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6641 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6642 WidenedVT.getVectorElementType(), 4); 6643 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6644 WidenedMemVT.getVectorElementType(), 4); 6645 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6646 } 6647 6648 assert(VTList.NumVTs == 2); 6649 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6650 6651 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6652 WidenedMemVT, MMO); 6653 if (WidenedVT != VT) { 6654 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6655 DAG.getVectorIdxConstant(0, DL)); 6656 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6657 } 6658 return NewOp; 6659 } 6660 6661 SDValue SITargetLowering::handleD16VData(SDValue VData, 6662 SelectionDAG &DAG) const { 6663 EVT StoreVT = VData.getValueType(); 6664 6665 // No change for f16 and legal vector D16 types. 6666 if (!StoreVT.isVector()) 6667 return VData; 6668 6669 SDLoc DL(VData); 6670 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6671 6672 if (Subtarget->hasUnpackedD16VMem()) { 6673 // We need to unpack the packed data to store. 6674 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6675 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6676 6677 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6678 StoreVT.getVectorNumElements()); 6679 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6680 return DAG.UnrollVectorOp(ZExt.getNode()); 6681 } 6682 6683 assert(isTypeLegal(StoreVT)); 6684 return VData; 6685 } 6686 6687 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6688 SelectionDAG &DAG) const { 6689 SDLoc DL(Op); 6690 SDValue Chain = Op.getOperand(0); 6691 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6692 MachineFunction &MF = DAG.getMachineFunction(); 6693 6694 switch (IntrinsicID) { 6695 case Intrinsic::amdgcn_exp_compr: { 6696 SDValue Src0 = Op.getOperand(4); 6697 SDValue Src1 = Op.getOperand(5); 6698 // Hack around illegal type on SI by directly selecting it. 6699 if (isTypeLegal(Src0.getValueType())) 6700 return SDValue(); 6701 6702 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6703 SDValue Undef = DAG.getUNDEF(MVT::f32); 6704 const SDValue Ops[] = { 6705 Op.getOperand(2), // tgt 6706 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6707 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6708 Undef, // src2 6709 Undef, // src3 6710 Op.getOperand(7), // vm 6711 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6712 Op.getOperand(3), // en 6713 Op.getOperand(0) // Chain 6714 }; 6715 6716 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6717 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6718 } 6719 case Intrinsic::amdgcn_s_barrier: { 6720 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6721 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6722 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6723 if (WGSize <= ST.getWavefrontSize()) 6724 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6725 Op.getOperand(0)), 0); 6726 } 6727 return SDValue(); 6728 }; 6729 case Intrinsic::amdgcn_tbuffer_store: { 6730 SDValue VData = Op.getOperand(2); 6731 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6732 if (IsD16) 6733 VData = handleD16VData(VData, DAG); 6734 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6735 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6736 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6737 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6738 unsigned IdxEn = 1; 6739 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6740 IdxEn = Idx->getZExtValue() != 0; 6741 SDValue Ops[] = { 6742 Chain, 6743 VData, // vdata 6744 Op.getOperand(3), // rsrc 6745 Op.getOperand(4), // vindex 6746 Op.getOperand(5), // voffset 6747 Op.getOperand(6), // soffset 6748 Op.getOperand(7), // offset 6749 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6750 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6751 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6752 }; 6753 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6754 AMDGPUISD::TBUFFER_STORE_FORMAT; 6755 MemSDNode *M = cast<MemSDNode>(Op); 6756 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6757 M->getMemoryVT(), M->getMemOperand()); 6758 } 6759 6760 case Intrinsic::amdgcn_struct_tbuffer_store: { 6761 SDValue VData = Op.getOperand(2); 6762 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6763 if (IsD16) 6764 VData = handleD16VData(VData, DAG); 6765 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6766 SDValue Ops[] = { 6767 Chain, 6768 VData, // vdata 6769 Op.getOperand(3), // rsrc 6770 Op.getOperand(4), // vindex 6771 Offsets.first, // voffset 6772 Op.getOperand(6), // soffset 6773 Offsets.second, // offset 6774 Op.getOperand(7), // format 6775 Op.getOperand(8), // cachepolicy, swizzled buffer 6776 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6777 }; 6778 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6779 AMDGPUISD::TBUFFER_STORE_FORMAT; 6780 MemSDNode *M = cast<MemSDNode>(Op); 6781 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6782 M->getMemoryVT(), M->getMemOperand()); 6783 } 6784 6785 case Intrinsic::amdgcn_raw_tbuffer_store: { 6786 SDValue VData = Op.getOperand(2); 6787 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6788 if (IsD16) 6789 VData = handleD16VData(VData, DAG); 6790 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6791 SDValue Ops[] = { 6792 Chain, 6793 VData, // vdata 6794 Op.getOperand(3), // rsrc 6795 DAG.getConstant(0, DL, MVT::i32), // vindex 6796 Offsets.first, // voffset 6797 Op.getOperand(5), // soffset 6798 Offsets.second, // offset 6799 Op.getOperand(6), // format 6800 Op.getOperand(7), // cachepolicy, swizzled buffer 6801 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6802 }; 6803 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6804 AMDGPUISD::TBUFFER_STORE_FORMAT; 6805 MemSDNode *M = cast<MemSDNode>(Op); 6806 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6807 M->getMemoryVT(), M->getMemOperand()); 6808 } 6809 6810 case Intrinsic::amdgcn_buffer_store: 6811 case Intrinsic::amdgcn_buffer_store_format: { 6812 SDValue VData = Op.getOperand(2); 6813 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6814 if (IsD16) 6815 VData = handleD16VData(VData, DAG); 6816 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6817 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6818 unsigned IdxEn = 1; 6819 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6820 IdxEn = Idx->getZExtValue() != 0; 6821 SDValue Ops[] = { 6822 Chain, 6823 VData, 6824 Op.getOperand(3), // rsrc 6825 Op.getOperand(4), // vindex 6826 SDValue(), // voffset -- will be set by setBufferOffsets 6827 SDValue(), // soffset -- will be set by setBufferOffsets 6828 SDValue(), // offset -- will be set by setBufferOffsets 6829 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6830 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6831 }; 6832 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6833 // We don't know the offset if vindex is non-zero, so clear it. 6834 if (IdxEn) 6835 Offset = 0; 6836 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6837 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6838 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6839 MemSDNode *M = cast<MemSDNode>(Op); 6840 M->getMemOperand()->setOffset(Offset); 6841 6842 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6843 EVT VDataType = VData.getValueType().getScalarType(); 6844 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6845 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6846 6847 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6848 M->getMemoryVT(), M->getMemOperand()); 6849 } 6850 6851 case Intrinsic::amdgcn_raw_buffer_store: 6852 case Intrinsic::amdgcn_raw_buffer_store_format: { 6853 const bool IsFormat = 6854 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6855 6856 SDValue VData = Op.getOperand(2); 6857 EVT VDataVT = VData.getValueType(); 6858 EVT EltType = VDataVT.getScalarType(); 6859 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6860 if (IsD16) 6861 VData = handleD16VData(VData, DAG); 6862 6863 if (!isTypeLegal(VDataVT)) { 6864 VData = 6865 DAG.getNode(ISD::BITCAST, DL, 6866 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6867 } 6868 6869 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6870 SDValue Ops[] = { 6871 Chain, 6872 VData, 6873 Op.getOperand(3), // rsrc 6874 DAG.getConstant(0, DL, MVT::i32), // vindex 6875 Offsets.first, // voffset 6876 Op.getOperand(5), // soffset 6877 Offsets.second, // offset 6878 Op.getOperand(6), // cachepolicy, swizzled buffer 6879 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6880 }; 6881 unsigned Opc = 6882 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6883 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6884 MemSDNode *M = cast<MemSDNode>(Op); 6885 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6886 6887 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6888 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6889 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 6890 6891 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6892 M->getMemoryVT(), M->getMemOperand()); 6893 } 6894 6895 case Intrinsic::amdgcn_struct_buffer_store: 6896 case Intrinsic::amdgcn_struct_buffer_store_format: { 6897 const bool IsFormat = 6898 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 6899 6900 SDValue VData = Op.getOperand(2); 6901 EVT VDataVT = VData.getValueType(); 6902 EVT EltType = VDataVT.getScalarType(); 6903 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6904 6905 if (IsD16) 6906 VData = handleD16VData(VData, DAG); 6907 6908 if (!isTypeLegal(VDataVT)) { 6909 VData = 6910 DAG.getNode(ISD::BITCAST, DL, 6911 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6912 } 6913 6914 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6915 SDValue Ops[] = { 6916 Chain, 6917 VData, 6918 Op.getOperand(3), // rsrc 6919 Op.getOperand(4), // vindex 6920 Offsets.first, // voffset 6921 Op.getOperand(6), // soffset 6922 Offsets.second, // offset 6923 Op.getOperand(7), // cachepolicy, swizzled buffer 6924 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6925 }; 6926 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6927 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6928 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6929 MemSDNode *M = cast<MemSDNode>(Op); 6930 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6931 Ops[3])); 6932 6933 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6934 EVT VDataType = VData.getValueType().getScalarType(); 6935 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6936 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6937 6938 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6939 M->getMemoryVT(), M->getMemOperand()); 6940 } 6941 6942 case Intrinsic::amdgcn_buffer_atomic_fadd: { 6943 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6944 unsigned IdxEn = 1; 6945 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6946 IdxEn = Idx->getZExtValue() != 0; 6947 SDValue Ops[] = { 6948 Chain, 6949 Op.getOperand(2), // vdata 6950 Op.getOperand(3), // rsrc 6951 Op.getOperand(4), // vindex 6952 SDValue(), // voffset -- will be set by setBufferOffsets 6953 SDValue(), // soffset -- will be set by setBufferOffsets 6954 SDValue(), // offset -- will be set by setBufferOffsets 6955 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6956 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6957 }; 6958 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6959 // We don't know the offset if vindex is non-zero, so clear it. 6960 if (IdxEn) 6961 Offset = 0; 6962 EVT VT = Op.getOperand(2).getValueType(); 6963 6964 auto *M = cast<MemSDNode>(Op); 6965 M->getMemOperand()->setOffset(Offset); 6966 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 6967 : AMDGPUISD::BUFFER_ATOMIC_FADD; 6968 6969 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6970 M->getMemOperand()); 6971 } 6972 6973 case Intrinsic::amdgcn_global_atomic_fadd: { 6974 SDValue Ops[] = { 6975 Chain, 6976 Op.getOperand(2), // ptr 6977 Op.getOperand(3) // vdata 6978 }; 6979 EVT VT = Op.getOperand(3).getValueType(); 6980 6981 auto *M = cast<MemSDNode>(Op); 6982 if (VT.isVector()) { 6983 return DAG.getMemIntrinsicNode( 6984 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 6985 M->getMemOperand()); 6986 } 6987 6988 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 6989 DAG.getVTList(VT, MVT::Other), Ops, 6990 M->getMemOperand()).getValue(1); 6991 } 6992 case Intrinsic::amdgcn_end_cf: 6993 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 6994 Op->getOperand(2), Chain), 0); 6995 6996 default: { 6997 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6998 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6999 return lowerImage(Op, ImageDimIntr, DAG); 7000 7001 return Op; 7002 } 7003 } 7004 } 7005 7006 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7007 // offset (the offset that is included in bounds checking and swizzling, to be 7008 // split between the instruction's voffset and immoffset fields) and soffset 7009 // (the offset that is excluded from bounds checking and swizzling, to go in 7010 // the instruction's soffset field). This function takes the first kind of 7011 // offset and figures out how to split it between voffset and immoffset. 7012 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7013 SDValue Offset, SelectionDAG &DAG) const { 7014 SDLoc DL(Offset); 7015 const unsigned MaxImm = 4095; 7016 SDValue N0 = Offset; 7017 ConstantSDNode *C1 = nullptr; 7018 7019 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7020 N0 = SDValue(); 7021 else if (DAG.isBaseWithConstantOffset(N0)) { 7022 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7023 N0 = N0.getOperand(0); 7024 } 7025 7026 if (C1) { 7027 unsigned ImmOffset = C1->getZExtValue(); 7028 // If the immediate value is too big for the immoffset field, put the value 7029 // and -4096 into the immoffset field so that the value that is copied/added 7030 // for the voffset field is a multiple of 4096, and it stands more chance 7031 // of being CSEd with the copy/add for another similar load/store. 7032 // However, do not do that rounding down to a multiple of 4096 if that is a 7033 // negative number, as it appears to be illegal to have a negative offset 7034 // in the vgpr, even if adding the immediate offset makes it positive. 7035 unsigned Overflow = ImmOffset & ~MaxImm; 7036 ImmOffset -= Overflow; 7037 if ((int32_t)Overflow < 0) { 7038 Overflow += ImmOffset; 7039 ImmOffset = 0; 7040 } 7041 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7042 if (Overflow) { 7043 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7044 if (!N0) 7045 N0 = OverflowVal; 7046 else { 7047 SDValue Ops[] = { N0, OverflowVal }; 7048 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7049 } 7050 } 7051 } 7052 if (!N0) 7053 N0 = DAG.getConstant(0, DL, MVT::i32); 7054 if (!C1) 7055 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7056 return {N0, SDValue(C1, 0)}; 7057 } 7058 7059 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7060 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7061 // pointed to by Offsets. 7062 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7063 SelectionDAG &DAG, SDValue *Offsets, 7064 unsigned Align) const { 7065 SDLoc DL(CombinedOffset); 7066 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7067 uint32_t Imm = C->getZExtValue(); 7068 uint32_t SOffset, ImmOffset; 7069 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7070 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7071 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7072 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7073 return SOffset + ImmOffset; 7074 } 7075 } 7076 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7077 SDValue N0 = CombinedOffset.getOperand(0); 7078 SDValue N1 = CombinedOffset.getOperand(1); 7079 uint32_t SOffset, ImmOffset; 7080 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7081 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7082 Subtarget, Align)) { 7083 Offsets[0] = N0; 7084 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7085 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7086 return 0; 7087 } 7088 } 7089 Offsets[0] = CombinedOffset; 7090 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7091 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7092 return 0; 7093 } 7094 7095 // Handle 8 bit and 16 bit buffer loads 7096 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7097 EVT LoadVT, SDLoc DL, 7098 ArrayRef<SDValue> Ops, 7099 MemSDNode *M) const { 7100 EVT IntVT = LoadVT.changeTypeToInteger(); 7101 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7102 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7103 7104 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7105 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7106 Ops, IntVT, 7107 M->getMemOperand()); 7108 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7109 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7110 7111 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7112 } 7113 7114 // Handle 8 bit and 16 bit buffer stores 7115 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7116 EVT VDataType, SDLoc DL, 7117 SDValue Ops[], 7118 MemSDNode *M) const { 7119 if (VDataType == MVT::f16) 7120 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7121 7122 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7123 Ops[1] = BufferStoreExt; 7124 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7125 AMDGPUISD::BUFFER_STORE_SHORT; 7126 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7127 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7128 M->getMemOperand()); 7129 } 7130 7131 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7132 ISD::LoadExtType ExtType, SDValue Op, 7133 const SDLoc &SL, EVT VT) { 7134 if (VT.bitsLT(Op.getValueType())) 7135 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7136 7137 switch (ExtType) { 7138 case ISD::SEXTLOAD: 7139 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7140 case ISD::ZEXTLOAD: 7141 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7142 case ISD::EXTLOAD: 7143 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7144 case ISD::NON_EXTLOAD: 7145 return Op; 7146 } 7147 7148 llvm_unreachable("invalid ext type"); 7149 } 7150 7151 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7152 SelectionDAG &DAG = DCI.DAG; 7153 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7154 return SDValue(); 7155 7156 // FIXME: Constant loads should all be marked invariant. 7157 unsigned AS = Ld->getAddressSpace(); 7158 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7159 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7160 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7161 return SDValue(); 7162 7163 // Don't do this early, since it may interfere with adjacent load merging for 7164 // illegal types. We can avoid losing alignment information for exotic types 7165 // pre-legalize. 7166 EVT MemVT = Ld->getMemoryVT(); 7167 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7168 MemVT.getSizeInBits() >= 32) 7169 return SDValue(); 7170 7171 SDLoc SL(Ld); 7172 7173 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7174 "unexpected vector extload"); 7175 7176 // TODO: Drop only high part of range. 7177 SDValue Ptr = Ld->getBasePtr(); 7178 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7179 MVT::i32, SL, Ld->getChain(), Ptr, 7180 Ld->getOffset(), 7181 Ld->getPointerInfo(), MVT::i32, 7182 Ld->getAlignment(), 7183 Ld->getMemOperand()->getFlags(), 7184 Ld->getAAInfo(), 7185 nullptr); // Drop ranges 7186 7187 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7188 if (MemVT.isFloatingPoint()) { 7189 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7190 "unexpected fp extload"); 7191 TruncVT = MemVT.changeTypeToInteger(); 7192 } 7193 7194 SDValue Cvt = NewLoad; 7195 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7196 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7197 DAG.getValueType(TruncVT)); 7198 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7199 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7200 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7201 } else { 7202 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7203 } 7204 7205 EVT VT = Ld->getValueType(0); 7206 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7207 7208 DCI.AddToWorklist(Cvt.getNode()); 7209 7210 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7211 // the appropriate extension from the 32-bit load. 7212 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7213 DCI.AddToWorklist(Cvt.getNode()); 7214 7215 // Handle conversion back to floating point if necessary. 7216 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7217 7218 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7219 } 7220 7221 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7222 SDLoc DL(Op); 7223 LoadSDNode *Load = cast<LoadSDNode>(Op); 7224 ISD::LoadExtType ExtType = Load->getExtensionType(); 7225 EVT MemVT = Load->getMemoryVT(); 7226 7227 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7228 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7229 return SDValue(); 7230 7231 // FIXME: Copied from PPC 7232 // First, load into 32 bits, then truncate to 1 bit. 7233 7234 SDValue Chain = Load->getChain(); 7235 SDValue BasePtr = Load->getBasePtr(); 7236 MachineMemOperand *MMO = Load->getMemOperand(); 7237 7238 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7239 7240 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7241 BasePtr, RealMemVT, MMO); 7242 7243 if (!MemVT.isVector()) { 7244 SDValue Ops[] = { 7245 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7246 NewLD.getValue(1) 7247 }; 7248 7249 return DAG.getMergeValues(Ops, DL); 7250 } 7251 7252 SmallVector<SDValue, 3> Elts; 7253 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7254 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7255 DAG.getConstant(I, DL, MVT::i32)); 7256 7257 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7258 } 7259 7260 SDValue Ops[] = { 7261 DAG.getBuildVector(MemVT, DL, Elts), 7262 NewLD.getValue(1) 7263 }; 7264 7265 return DAG.getMergeValues(Ops, DL); 7266 } 7267 7268 if (!MemVT.isVector()) 7269 return SDValue(); 7270 7271 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7272 "Custom lowering for non-i32 vectors hasn't been implemented."); 7273 7274 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7275 MemVT, *Load->getMemOperand())) { 7276 SDValue Ops[2]; 7277 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7278 return DAG.getMergeValues(Ops, DL); 7279 } 7280 7281 unsigned Alignment = Load->getAlignment(); 7282 unsigned AS = Load->getAddressSpace(); 7283 if (Subtarget->hasLDSMisalignedBug() && 7284 AS == AMDGPUAS::FLAT_ADDRESS && 7285 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7286 return SplitVectorLoad(Op, DAG); 7287 } 7288 7289 MachineFunction &MF = DAG.getMachineFunction(); 7290 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7291 // If there is a possibilty that flat instruction access scratch memory 7292 // then we need to use the same legalization rules we use for private. 7293 if (AS == AMDGPUAS::FLAT_ADDRESS && 7294 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7295 AS = MFI->hasFlatScratchInit() ? 7296 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7297 7298 unsigned NumElements = MemVT.getVectorNumElements(); 7299 7300 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7301 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7302 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7303 if (MemVT.isPow2VectorType()) 7304 return SDValue(); 7305 if (NumElements == 3) 7306 return WidenVectorLoad(Op, DAG); 7307 return SplitVectorLoad(Op, DAG); 7308 } 7309 // Non-uniform loads will be selected to MUBUF instructions, so they 7310 // have the same legalization requirements as global and private 7311 // loads. 7312 // 7313 } 7314 7315 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7316 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7317 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7318 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7319 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7320 Alignment >= 4 && NumElements < 32) { 7321 if (MemVT.isPow2VectorType()) 7322 return SDValue(); 7323 if (NumElements == 3) 7324 return WidenVectorLoad(Op, DAG); 7325 return SplitVectorLoad(Op, DAG); 7326 } 7327 // Non-uniform loads will be selected to MUBUF instructions, so they 7328 // have the same legalization requirements as global and private 7329 // loads. 7330 // 7331 } 7332 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7333 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7334 AS == AMDGPUAS::GLOBAL_ADDRESS || 7335 AS == AMDGPUAS::FLAT_ADDRESS) { 7336 if (NumElements > 4) 7337 return SplitVectorLoad(Op, DAG); 7338 // v3 loads not supported on SI. 7339 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7340 return WidenVectorLoad(Op, DAG); 7341 // v3 and v4 loads are supported for private and global memory. 7342 return SDValue(); 7343 } 7344 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7345 // Depending on the setting of the private_element_size field in the 7346 // resource descriptor, we can only make private accesses up to a certain 7347 // size. 7348 switch (Subtarget->getMaxPrivateElementSize()) { 7349 case 4: { 7350 SDValue Ops[2]; 7351 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7352 return DAG.getMergeValues(Ops, DL); 7353 } 7354 case 8: 7355 if (NumElements > 2) 7356 return SplitVectorLoad(Op, DAG); 7357 return SDValue(); 7358 case 16: 7359 // Same as global/flat 7360 if (NumElements > 4) 7361 return SplitVectorLoad(Op, DAG); 7362 // v3 loads not supported on SI. 7363 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7364 return WidenVectorLoad(Op, DAG); 7365 return SDValue(); 7366 default: 7367 llvm_unreachable("unsupported private_element_size"); 7368 } 7369 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7370 // Use ds_read_b128 if possible. 7371 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7372 MemVT.getStoreSize() == 16) 7373 return SDValue(); 7374 7375 if (NumElements > 2) 7376 return SplitVectorLoad(Op, DAG); 7377 7378 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7379 // address is negative, then the instruction is incorrectly treated as 7380 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7381 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7382 // load later in the SILoadStoreOptimizer. 7383 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7384 NumElements == 2 && MemVT.getStoreSize() == 8 && 7385 Load->getAlignment() < 8) { 7386 return SplitVectorLoad(Op, DAG); 7387 } 7388 } 7389 return SDValue(); 7390 } 7391 7392 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7393 EVT VT = Op.getValueType(); 7394 assert(VT.getSizeInBits() == 64); 7395 7396 SDLoc DL(Op); 7397 SDValue Cond = Op.getOperand(0); 7398 7399 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7400 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7401 7402 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7403 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7404 7405 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7406 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7407 7408 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7409 7410 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7411 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7412 7413 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7414 7415 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7416 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7417 } 7418 7419 // Catch division cases where we can use shortcuts with rcp and rsq 7420 // instructions. 7421 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7422 SelectionDAG &DAG) const { 7423 SDLoc SL(Op); 7424 SDValue LHS = Op.getOperand(0); 7425 SDValue RHS = Op.getOperand(1); 7426 EVT VT = Op.getValueType(); 7427 const SDNodeFlags Flags = Op->getFlags(); 7428 7429 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7430 Flags.hasApproximateFuncs(); 7431 7432 // Without !fpmath accuracy information, we can't do more because we don't 7433 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7434 if (!AllowInaccurateRcp) 7435 return SDValue(); 7436 7437 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7438 if (CLHS->isExactlyValue(1.0)) { 7439 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7440 // the CI documentation has a worst case error of 1 ulp. 7441 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7442 // use it as long as we aren't trying to use denormals. 7443 // 7444 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7445 7446 // 1.0 / sqrt(x) -> rsq(x) 7447 7448 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7449 // error seems really high at 2^29 ULP. 7450 if (RHS.getOpcode() == ISD::FSQRT) 7451 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7452 7453 // 1.0 / x -> rcp(x) 7454 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7455 } 7456 7457 // Same as for 1.0, but expand the sign out of the constant. 7458 if (CLHS->isExactlyValue(-1.0)) { 7459 // -1.0 / x -> rcp (fneg x) 7460 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7461 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7462 } 7463 } 7464 7465 // Turn into multiply by the reciprocal. 7466 // x / y -> x * (1.0 / y) 7467 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7468 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7469 } 7470 7471 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7472 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7473 if (GlueChain->getNumValues() <= 1) { 7474 return DAG.getNode(Opcode, SL, VT, A, B); 7475 } 7476 7477 assert(GlueChain->getNumValues() == 3); 7478 7479 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7480 switch (Opcode) { 7481 default: llvm_unreachable("no chain equivalent for opcode"); 7482 case ISD::FMUL: 7483 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7484 break; 7485 } 7486 7487 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7488 GlueChain.getValue(2)); 7489 } 7490 7491 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7492 EVT VT, SDValue A, SDValue B, SDValue C, 7493 SDValue GlueChain) { 7494 if (GlueChain->getNumValues() <= 1) { 7495 return DAG.getNode(Opcode, SL, VT, A, B, C); 7496 } 7497 7498 assert(GlueChain->getNumValues() == 3); 7499 7500 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7501 switch (Opcode) { 7502 default: llvm_unreachable("no chain equivalent for opcode"); 7503 case ISD::FMA: 7504 Opcode = AMDGPUISD::FMA_W_CHAIN; 7505 break; 7506 } 7507 7508 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7509 GlueChain.getValue(2)); 7510 } 7511 7512 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7513 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7514 return FastLowered; 7515 7516 SDLoc SL(Op); 7517 SDValue Src0 = Op.getOperand(0); 7518 SDValue Src1 = Op.getOperand(1); 7519 7520 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7521 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7522 7523 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7524 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7525 7526 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7527 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7528 7529 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7530 } 7531 7532 // Faster 2.5 ULP division that does not support denormals. 7533 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7534 SDLoc SL(Op); 7535 SDValue LHS = Op.getOperand(1); 7536 SDValue RHS = Op.getOperand(2); 7537 7538 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7539 7540 const APFloat K0Val(BitsToFloat(0x6f800000)); 7541 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7542 7543 const APFloat K1Val(BitsToFloat(0x2f800000)); 7544 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7545 7546 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7547 7548 EVT SetCCVT = 7549 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7550 7551 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7552 7553 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7554 7555 // TODO: Should this propagate fast-math-flags? 7556 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7557 7558 // rcp does not support denormals. 7559 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7560 7561 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7562 7563 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7564 } 7565 7566 // Returns immediate value for setting the F32 denorm mode when using the 7567 // S_DENORM_MODE instruction. 7568 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7569 const SDLoc &SL, const GCNSubtarget *ST) { 7570 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7571 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7572 ? FP_DENORM_FLUSH_NONE 7573 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7574 7575 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7576 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7577 } 7578 7579 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7580 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7581 return FastLowered; 7582 7583 SDLoc SL(Op); 7584 SDValue LHS = Op.getOperand(0); 7585 SDValue RHS = Op.getOperand(1); 7586 7587 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7588 7589 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7590 7591 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7592 RHS, RHS, LHS); 7593 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7594 LHS, RHS, LHS); 7595 7596 // Denominator is scaled to not be denormal, so using rcp is ok. 7597 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7598 DenominatorScaled); 7599 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7600 DenominatorScaled); 7601 7602 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7603 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7604 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7605 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7606 7607 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7608 7609 if (!HasFP32Denormals) { 7610 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7611 7612 SDValue EnableDenorm; 7613 if (Subtarget->hasDenormModeInst()) { 7614 const SDValue EnableDenormValue = 7615 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7616 7617 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7618 DAG.getEntryNode(), EnableDenormValue); 7619 } else { 7620 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7621 SL, MVT::i32); 7622 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7623 DAG.getEntryNode(), EnableDenormValue, 7624 BitField); 7625 } 7626 7627 SDValue Ops[3] = { 7628 NegDivScale0, 7629 EnableDenorm.getValue(0), 7630 EnableDenorm.getValue(1) 7631 }; 7632 7633 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7634 } 7635 7636 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7637 ApproxRcp, One, NegDivScale0); 7638 7639 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7640 ApproxRcp, Fma0); 7641 7642 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7643 Fma1, Fma1); 7644 7645 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7646 NumeratorScaled, Mul); 7647 7648 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7649 7650 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7651 NumeratorScaled, Fma3); 7652 7653 if (!HasFP32Denormals) { 7654 SDValue DisableDenorm; 7655 if (Subtarget->hasDenormModeInst()) { 7656 const SDValue DisableDenormValue = 7657 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7658 7659 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7660 Fma4.getValue(1), DisableDenormValue, 7661 Fma4.getValue(2)); 7662 } else { 7663 const SDValue DisableDenormValue = 7664 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7665 7666 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7667 Fma4.getValue(1), DisableDenormValue, 7668 BitField, Fma4.getValue(2)); 7669 } 7670 7671 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7672 DisableDenorm, DAG.getRoot()); 7673 DAG.setRoot(OutputChain); 7674 } 7675 7676 SDValue Scale = NumeratorScaled.getValue(1); 7677 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7678 Fma4, Fma1, Fma3, Scale); 7679 7680 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7681 } 7682 7683 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7684 if (DAG.getTarget().Options.UnsafeFPMath) 7685 return lowerFastUnsafeFDIV(Op, DAG); 7686 7687 SDLoc SL(Op); 7688 SDValue X = Op.getOperand(0); 7689 SDValue Y = Op.getOperand(1); 7690 7691 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7692 7693 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7694 7695 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7696 7697 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7698 7699 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7700 7701 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7702 7703 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7704 7705 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7706 7707 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7708 7709 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7710 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7711 7712 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7713 NegDivScale0, Mul, DivScale1); 7714 7715 SDValue Scale; 7716 7717 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7718 // Workaround a hardware bug on SI where the condition output from div_scale 7719 // is not usable. 7720 7721 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7722 7723 // Figure out if the scale to use for div_fmas. 7724 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7725 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7726 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7727 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7728 7729 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7730 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7731 7732 SDValue Scale0Hi 7733 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7734 SDValue Scale1Hi 7735 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7736 7737 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7738 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7739 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7740 } else { 7741 Scale = DivScale1.getValue(1); 7742 } 7743 7744 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7745 Fma4, Fma3, Mul, Scale); 7746 7747 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7748 } 7749 7750 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7751 EVT VT = Op.getValueType(); 7752 7753 if (VT == MVT::f32) 7754 return LowerFDIV32(Op, DAG); 7755 7756 if (VT == MVT::f64) 7757 return LowerFDIV64(Op, DAG); 7758 7759 if (VT == MVT::f16) 7760 return LowerFDIV16(Op, DAG); 7761 7762 llvm_unreachable("Unexpected type for fdiv"); 7763 } 7764 7765 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7766 SDLoc DL(Op); 7767 StoreSDNode *Store = cast<StoreSDNode>(Op); 7768 EVT VT = Store->getMemoryVT(); 7769 7770 if (VT == MVT::i1) { 7771 return DAG.getTruncStore(Store->getChain(), DL, 7772 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7773 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7774 } 7775 7776 assert(VT.isVector() && 7777 Store->getValue().getValueType().getScalarType() == MVT::i32); 7778 7779 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7780 VT, *Store->getMemOperand())) { 7781 return expandUnalignedStore(Store, DAG); 7782 } 7783 7784 unsigned AS = Store->getAddressSpace(); 7785 if (Subtarget->hasLDSMisalignedBug() && 7786 AS == AMDGPUAS::FLAT_ADDRESS && 7787 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7788 return SplitVectorStore(Op, DAG); 7789 } 7790 7791 MachineFunction &MF = DAG.getMachineFunction(); 7792 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7793 // If there is a possibilty that flat instruction access scratch memory 7794 // then we need to use the same legalization rules we use for private. 7795 if (AS == AMDGPUAS::FLAT_ADDRESS && 7796 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7797 AS = MFI->hasFlatScratchInit() ? 7798 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7799 7800 unsigned NumElements = VT.getVectorNumElements(); 7801 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7802 AS == AMDGPUAS::FLAT_ADDRESS) { 7803 if (NumElements > 4) 7804 return SplitVectorStore(Op, DAG); 7805 // v3 stores not supported on SI. 7806 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7807 return SplitVectorStore(Op, DAG); 7808 return SDValue(); 7809 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7810 switch (Subtarget->getMaxPrivateElementSize()) { 7811 case 4: 7812 return scalarizeVectorStore(Store, DAG); 7813 case 8: 7814 if (NumElements > 2) 7815 return SplitVectorStore(Op, DAG); 7816 return SDValue(); 7817 case 16: 7818 if (NumElements > 4 || NumElements == 3) 7819 return SplitVectorStore(Op, DAG); 7820 return SDValue(); 7821 default: 7822 llvm_unreachable("unsupported private_element_size"); 7823 } 7824 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7825 // Use ds_write_b128 if possible. 7826 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7827 VT.getStoreSize() == 16 && NumElements != 3) 7828 return SDValue(); 7829 7830 if (NumElements > 2) 7831 return SplitVectorStore(Op, DAG); 7832 7833 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7834 // address is negative, then the instruction is incorrectly treated as 7835 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7836 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7837 // store later in the SILoadStoreOptimizer. 7838 if (!Subtarget->hasUsableDSOffset() && 7839 NumElements == 2 && VT.getStoreSize() == 8 && 7840 Store->getAlignment() < 8) { 7841 return SplitVectorStore(Op, DAG); 7842 } 7843 7844 return SDValue(); 7845 } else { 7846 llvm_unreachable("unhandled address space"); 7847 } 7848 } 7849 7850 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7851 SDLoc DL(Op); 7852 EVT VT = Op.getValueType(); 7853 SDValue Arg = Op.getOperand(0); 7854 SDValue TrigVal; 7855 7856 // TODO: Should this propagate fast-math-flags? 7857 7858 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7859 7860 if (Subtarget->hasTrigReducedRange()) { 7861 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7862 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7863 } else { 7864 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7865 } 7866 7867 switch (Op.getOpcode()) { 7868 case ISD::FCOS: 7869 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7870 case ISD::FSIN: 7871 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7872 default: 7873 llvm_unreachable("Wrong trig opcode"); 7874 } 7875 } 7876 7877 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7878 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7879 assert(AtomicNode->isCompareAndSwap()); 7880 unsigned AS = AtomicNode->getAddressSpace(); 7881 7882 // No custom lowering required for local address space 7883 if (!isFlatGlobalAddrSpace(AS)) 7884 return Op; 7885 7886 // Non-local address space requires custom lowering for atomic compare 7887 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7888 SDLoc DL(Op); 7889 SDValue ChainIn = Op.getOperand(0); 7890 SDValue Addr = Op.getOperand(1); 7891 SDValue Old = Op.getOperand(2); 7892 SDValue New = Op.getOperand(3); 7893 EVT VT = Op.getValueType(); 7894 MVT SimpleVT = VT.getSimpleVT(); 7895 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7896 7897 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7898 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7899 7900 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7901 Ops, VT, AtomicNode->getMemOperand()); 7902 } 7903 7904 //===----------------------------------------------------------------------===// 7905 // Custom DAG optimizations 7906 //===----------------------------------------------------------------------===// 7907 7908 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7909 DAGCombinerInfo &DCI) const { 7910 EVT VT = N->getValueType(0); 7911 EVT ScalarVT = VT.getScalarType(); 7912 if (ScalarVT != MVT::f32) 7913 return SDValue(); 7914 7915 SelectionDAG &DAG = DCI.DAG; 7916 SDLoc DL(N); 7917 7918 SDValue Src = N->getOperand(0); 7919 EVT SrcVT = Src.getValueType(); 7920 7921 // TODO: We could try to match extracting the higher bytes, which would be 7922 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7923 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7924 // about in practice. 7925 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7926 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7927 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7928 DCI.AddToWorklist(Cvt.getNode()); 7929 return Cvt; 7930 } 7931 } 7932 7933 return SDValue(); 7934 } 7935 7936 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7937 7938 // This is a variant of 7939 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7940 // 7941 // The normal DAG combiner will do this, but only if the add has one use since 7942 // that would increase the number of instructions. 7943 // 7944 // This prevents us from seeing a constant offset that can be folded into a 7945 // memory instruction's addressing mode. If we know the resulting add offset of 7946 // a pointer can be folded into an addressing offset, we can replace the pointer 7947 // operand with the add of new constant offset. This eliminates one of the uses, 7948 // and may allow the remaining use to also be simplified. 7949 // 7950 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7951 unsigned AddrSpace, 7952 EVT MemVT, 7953 DAGCombinerInfo &DCI) const { 7954 SDValue N0 = N->getOperand(0); 7955 SDValue N1 = N->getOperand(1); 7956 7957 // We only do this to handle cases where it's profitable when there are 7958 // multiple uses of the add, so defer to the standard combine. 7959 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7960 N0->hasOneUse()) 7961 return SDValue(); 7962 7963 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7964 if (!CN1) 7965 return SDValue(); 7966 7967 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7968 if (!CAdd) 7969 return SDValue(); 7970 7971 // If the resulting offset is too large, we can't fold it into the addressing 7972 // mode offset. 7973 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7974 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7975 7976 AddrMode AM; 7977 AM.HasBaseReg = true; 7978 AM.BaseOffs = Offset.getSExtValue(); 7979 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 7980 return SDValue(); 7981 7982 SelectionDAG &DAG = DCI.DAG; 7983 SDLoc SL(N); 7984 EVT VT = N->getValueType(0); 7985 7986 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 7987 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 7988 7989 SDNodeFlags Flags; 7990 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 7991 (N0.getOpcode() == ISD::OR || 7992 N0->getFlags().hasNoUnsignedWrap())); 7993 7994 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 7995 } 7996 7997 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 7998 DAGCombinerInfo &DCI) const { 7999 SDValue Ptr = N->getBasePtr(); 8000 SelectionDAG &DAG = DCI.DAG; 8001 SDLoc SL(N); 8002 8003 // TODO: We could also do this for multiplies. 8004 if (Ptr.getOpcode() == ISD::SHL) { 8005 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8006 N->getMemoryVT(), DCI); 8007 if (NewPtr) { 8008 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8009 8010 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8011 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8012 } 8013 } 8014 8015 return SDValue(); 8016 } 8017 8018 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8019 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8020 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8021 (Opc == ISD::XOR && Val == 0); 8022 } 8023 8024 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8025 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8026 // integer combine opportunities since most 64-bit operations are decomposed 8027 // this way. TODO: We won't want this for SALU especially if it is an inline 8028 // immediate. 8029 SDValue SITargetLowering::splitBinaryBitConstantOp( 8030 DAGCombinerInfo &DCI, 8031 const SDLoc &SL, 8032 unsigned Opc, SDValue LHS, 8033 const ConstantSDNode *CRHS) const { 8034 uint64_t Val = CRHS->getZExtValue(); 8035 uint32_t ValLo = Lo_32(Val); 8036 uint32_t ValHi = Hi_32(Val); 8037 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8038 8039 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8040 bitOpWithConstantIsReducible(Opc, ValHi)) || 8041 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8042 // If we need to materialize a 64-bit immediate, it will be split up later 8043 // anyway. Avoid creating the harder to understand 64-bit immediate 8044 // materialization. 8045 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8046 } 8047 8048 return SDValue(); 8049 } 8050 8051 // Returns true if argument is a boolean value which is not serialized into 8052 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8053 static bool isBoolSGPR(SDValue V) { 8054 if (V.getValueType() != MVT::i1) 8055 return false; 8056 switch (V.getOpcode()) { 8057 default: break; 8058 case ISD::SETCC: 8059 case ISD::AND: 8060 case ISD::OR: 8061 case ISD::XOR: 8062 case AMDGPUISD::FP_CLASS: 8063 return true; 8064 } 8065 return false; 8066 } 8067 8068 // If a constant has all zeroes or all ones within each byte return it. 8069 // Otherwise return 0. 8070 static uint32_t getConstantPermuteMask(uint32_t C) { 8071 // 0xff for any zero byte in the mask 8072 uint32_t ZeroByteMask = 0; 8073 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8074 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8075 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8076 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8077 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8078 if ((NonZeroByteMask & C) != NonZeroByteMask) 8079 return 0; // Partial bytes selected. 8080 return C; 8081 } 8082 8083 // Check if a node selects whole bytes from its operand 0 starting at a byte 8084 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8085 // or -1 if not succeeded. 8086 // Note byte select encoding: 8087 // value 0-3 selects corresponding source byte; 8088 // value 0xc selects zero; 8089 // value 0xff selects 0xff. 8090 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8091 assert(V.getValueSizeInBits() == 32); 8092 8093 if (V.getNumOperands() != 2) 8094 return ~0; 8095 8096 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8097 if (!N1) 8098 return ~0; 8099 8100 uint32_t C = N1->getZExtValue(); 8101 8102 switch (V.getOpcode()) { 8103 default: 8104 break; 8105 case ISD::AND: 8106 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8107 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8108 } 8109 break; 8110 8111 case ISD::OR: 8112 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8113 return (0x03020100 & ~ConstMask) | ConstMask; 8114 } 8115 break; 8116 8117 case ISD::SHL: 8118 if (C % 8) 8119 return ~0; 8120 8121 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8122 8123 case ISD::SRL: 8124 if (C % 8) 8125 return ~0; 8126 8127 return uint32_t(0x0c0c0c0c03020100ull >> C); 8128 } 8129 8130 return ~0; 8131 } 8132 8133 SDValue SITargetLowering::performAndCombine(SDNode *N, 8134 DAGCombinerInfo &DCI) const { 8135 if (DCI.isBeforeLegalize()) 8136 return SDValue(); 8137 8138 SelectionDAG &DAG = DCI.DAG; 8139 EVT VT = N->getValueType(0); 8140 SDValue LHS = N->getOperand(0); 8141 SDValue RHS = N->getOperand(1); 8142 8143 8144 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8145 if (VT == MVT::i64 && CRHS) { 8146 if (SDValue Split 8147 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8148 return Split; 8149 } 8150 8151 if (CRHS && VT == MVT::i32) { 8152 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8153 // nb = number of trailing zeroes in mask 8154 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8155 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8156 uint64_t Mask = CRHS->getZExtValue(); 8157 unsigned Bits = countPopulation(Mask); 8158 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8159 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8160 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8161 unsigned Shift = CShift->getZExtValue(); 8162 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8163 unsigned Offset = NB + Shift; 8164 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8165 SDLoc SL(N); 8166 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8167 LHS->getOperand(0), 8168 DAG.getConstant(Offset, SL, MVT::i32), 8169 DAG.getConstant(Bits, SL, MVT::i32)); 8170 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8171 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8172 DAG.getValueType(NarrowVT)); 8173 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8174 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8175 return Shl; 8176 } 8177 } 8178 } 8179 8180 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8181 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8182 isa<ConstantSDNode>(LHS.getOperand(2))) { 8183 uint32_t Sel = getConstantPermuteMask(Mask); 8184 if (!Sel) 8185 return SDValue(); 8186 8187 // Select 0xc for all zero bytes 8188 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8189 SDLoc DL(N); 8190 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8191 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8192 } 8193 } 8194 8195 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8196 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8197 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8198 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8199 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8200 8201 SDValue X = LHS.getOperand(0); 8202 SDValue Y = RHS.getOperand(0); 8203 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8204 return SDValue(); 8205 8206 if (LCC == ISD::SETO) { 8207 if (X != LHS.getOperand(1)) 8208 return SDValue(); 8209 8210 if (RCC == ISD::SETUNE) { 8211 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8212 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8213 return SDValue(); 8214 8215 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8216 SIInstrFlags::N_SUBNORMAL | 8217 SIInstrFlags::N_ZERO | 8218 SIInstrFlags::P_ZERO | 8219 SIInstrFlags::P_SUBNORMAL | 8220 SIInstrFlags::P_NORMAL; 8221 8222 static_assert(((~(SIInstrFlags::S_NAN | 8223 SIInstrFlags::Q_NAN | 8224 SIInstrFlags::N_INFINITY | 8225 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8226 "mask not equal"); 8227 8228 SDLoc DL(N); 8229 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8230 X, DAG.getConstant(Mask, DL, MVT::i32)); 8231 } 8232 } 8233 } 8234 8235 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8236 std::swap(LHS, RHS); 8237 8238 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8239 RHS.hasOneUse()) { 8240 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8241 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8242 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8243 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8244 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8245 (RHS.getOperand(0) == LHS.getOperand(0) && 8246 LHS.getOperand(0) == LHS.getOperand(1))) { 8247 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8248 unsigned NewMask = LCC == ISD::SETO ? 8249 Mask->getZExtValue() & ~OrdMask : 8250 Mask->getZExtValue() & OrdMask; 8251 8252 SDLoc DL(N); 8253 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8254 DAG.getConstant(NewMask, DL, MVT::i32)); 8255 } 8256 } 8257 8258 if (VT == MVT::i32 && 8259 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8260 // and x, (sext cc from i1) => select cc, x, 0 8261 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8262 std::swap(LHS, RHS); 8263 if (isBoolSGPR(RHS.getOperand(0))) 8264 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8265 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8266 } 8267 8268 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8269 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8270 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8271 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8272 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8273 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8274 if (LHSMask != ~0u && RHSMask != ~0u) { 8275 // Canonicalize the expression in an attempt to have fewer unique masks 8276 // and therefore fewer registers used to hold the masks. 8277 if (LHSMask > RHSMask) { 8278 std::swap(LHSMask, RHSMask); 8279 std::swap(LHS, RHS); 8280 } 8281 8282 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8283 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8284 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8285 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8286 8287 // Check of we need to combine values from two sources within a byte. 8288 if (!(LHSUsedLanes & RHSUsedLanes) && 8289 // If we select high and lower word keep it for SDWA. 8290 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8291 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8292 // Each byte in each mask is either selector mask 0-3, or has higher 8293 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8294 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8295 // mask which is not 0xff wins. By anding both masks we have a correct 8296 // result except that 0x0c shall be corrected to give 0x0c only. 8297 uint32_t Mask = LHSMask & RHSMask; 8298 for (unsigned I = 0; I < 32; I += 8) { 8299 uint32_t ByteSel = 0xff << I; 8300 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8301 Mask &= (0x0c << I) & 0xffffffff; 8302 } 8303 8304 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8305 // or 0x0c. 8306 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8307 SDLoc DL(N); 8308 8309 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8310 LHS.getOperand(0), RHS.getOperand(0), 8311 DAG.getConstant(Sel, DL, MVT::i32)); 8312 } 8313 } 8314 } 8315 8316 return SDValue(); 8317 } 8318 8319 SDValue SITargetLowering::performOrCombine(SDNode *N, 8320 DAGCombinerInfo &DCI) const { 8321 SelectionDAG &DAG = DCI.DAG; 8322 SDValue LHS = N->getOperand(0); 8323 SDValue RHS = N->getOperand(1); 8324 8325 EVT VT = N->getValueType(0); 8326 if (VT == MVT::i1) { 8327 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8328 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8329 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8330 SDValue Src = LHS.getOperand(0); 8331 if (Src != RHS.getOperand(0)) 8332 return SDValue(); 8333 8334 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8335 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8336 if (!CLHS || !CRHS) 8337 return SDValue(); 8338 8339 // Only 10 bits are used. 8340 static const uint32_t MaxMask = 0x3ff; 8341 8342 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8343 SDLoc DL(N); 8344 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8345 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8346 } 8347 8348 return SDValue(); 8349 } 8350 8351 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8352 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8353 LHS.getOpcode() == AMDGPUISD::PERM && 8354 isa<ConstantSDNode>(LHS.getOperand(2))) { 8355 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8356 if (!Sel) 8357 return SDValue(); 8358 8359 Sel |= LHS.getConstantOperandVal(2); 8360 SDLoc DL(N); 8361 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8362 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8363 } 8364 8365 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8366 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8367 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8368 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8369 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8370 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8371 if (LHSMask != ~0u && RHSMask != ~0u) { 8372 // Canonicalize the expression in an attempt to have fewer unique masks 8373 // and therefore fewer registers used to hold the masks. 8374 if (LHSMask > RHSMask) { 8375 std::swap(LHSMask, RHSMask); 8376 std::swap(LHS, RHS); 8377 } 8378 8379 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8380 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8381 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8382 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8383 8384 // Check of we need to combine values from two sources within a byte. 8385 if (!(LHSUsedLanes & RHSUsedLanes) && 8386 // If we select high and lower word keep it for SDWA. 8387 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8388 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8389 // Kill zero bytes selected by other mask. Zero value is 0xc. 8390 LHSMask &= ~RHSUsedLanes; 8391 RHSMask &= ~LHSUsedLanes; 8392 // Add 4 to each active LHS lane 8393 LHSMask |= LHSUsedLanes & 0x04040404; 8394 // Combine masks 8395 uint32_t Sel = LHSMask | RHSMask; 8396 SDLoc DL(N); 8397 8398 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8399 LHS.getOperand(0), RHS.getOperand(0), 8400 DAG.getConstant(Sel, DL, MVT::i32)); 8401 } 8402 } 8403 } 8404 8405 if (VT != MVT::i64) 8406 return SDValue(); 8407 8408 // TODO: This could be a generic combine with a predicate for extracting the 8409 // high half of an integer being free. 8410 8411 // (or i64:x, (zero_extend i32:y)) -> 8412 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8413 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8414 RHS.getOpcode() != ISD::ZERO_EXTEND) 8415 std::swap(LHS, RHS); 8416 8417 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8418 SDValue ExtSrc = RHS.getOperand(0); 8419 EVT SrcVT = ExtSrc.getValueType(); 8420 if (SrcVT == MVT::i32) { 8421 SDLoc SL(N); 8422 SDValue LowLHS, HiBits; 8423 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8424 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8425 8426 DCI.AddToWorklist(LowOr.getNode()); 8427 DCI.AddToWorklist(HiBits.getNode()); 8428 8429 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8430 LowOr, HiBits); 8431 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8432 } 8433 } 8434 8435 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8436 if (CRHS) { 8437 if (SDValue Split 8438 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8439 return Split; 8440 } 8441 8442 return SDValue(); 8443 } 8444 8445 SDValue SITargetLowering::performXorCombine(SDNode *N, 8446 DAGCombinerInfo &DCI) const { 8447 EVT VT = N->getValueType(0); 8448 if (VT != MVT::i64) 8449 return SDValue(); 8450 8451 SDValue LHS = N->getOperand(0); 8452 SDValue RHS = N->getOperand(1); 8453 8454 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8455 if (CRHS) { 8456 if (SDValue Split 8457 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8458 return Split; 8459 } 8460 8461 return SDValue(); 8462 } 8463 8464 // Instructions that will be lowered with a final instruction that zeros the 8465 // high result bits. 8466 // XXX - probably only need to list legal operations. 8467 static bool fp16SrcZerosHighBits(unsigned Opc) { 8468 switch (Opc) { 8469 case ISD::FADD: 8470 case ISD::FSUB: 8471 case ISD::FMUL: 8472 case ISD::FDIV: 8473 case ISD::FREM: 8474 case ISD::FMA: 8475 case ISD::FMAD: 8476 case ISD::FCANONICALIZE: 8477 case ISD::FP_ROUND: 8478 case ISD::UINT_TO_FP: 8479 case ISD::SINT_TO_FP: 8480 case ISD::FABS: 8481 // Fabs is lowered to a bit operation, but it's an and which will clear the 8482 // high bits anyway. 8483 case ISD::FSQRT: 8484 case ISD::FSIN: 8485 case ISD::FCOS: 8486 case ISD::FPOWI: 8487 case ISD::FPOW: 8488 case ISD::FLOG: 8489 case ISD::FLOG2: 8490 case ISD::FLOG10: 8491 case ISD::FEXP: 8492 case ISD::FEXP2: 8493 case ISD::FCEIL: 8494 case ISD::FTRUNC: 8495 case ISD::FRINT: 8496 case ISD::FNEARBYINT: 8497 case ISD::FROUND: 8498 case ISD::FFLOOR: 8499 case ISD::FMINNUM: 8500 case ISD::FMAXNUM: 8501 case AMDGPUISD::FRACT: 8502 case AMDGPUISD::CLAMP: 8503 case AMDGPUISD::COS_HW: 8504 case AMDGPUISD::SIN_HW: 8505 case AMDGPUISD::FMIN3: 8506 case AMDGPUISD::FMAX3: 8507 case AMDGPUISD::FMED3: 8508 case AMDGPUISD::FMAD_FTZ: 8509 case AMDGPUISD::RCP: 8510 case AMDGPUISD::RSQ: 8511 case AMDGPUISD::RCP_IFLAG: 8512 case AMDGPUISD::LDEXP: 8513 return true; 8514 default: 8515 // fcopysign, select and others may be lowered to 32-bit bit operations 8516 // which don't zero the high bits. 8517 return false; 8518 } 8519 } 8520 8521 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8522 DAGCombinerInfo &DCI) const { 8523 if (!Subtarget->has16BitInsts() || 8524 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8525 return SDValue(); 8526 8527 EVT VT = N->getValueType(0); 8528 if (VT != MVT::i32) 8529 return SDValue(); 8530 8531 SDValue Src = N->getOperand(0); 8532 if (Src.getValueType() != MVT::i16) 8533 return SDValue(); 8534 8535 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8536 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8537 if (Src.getOpcode() == ISD::BITCAST) { 8538 SDValue BCSrc = Src.getOperand(0); 8539 if (BCSrc.getValueType() == MVT::f16 && 8540 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8541 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8542 } 8543 8544 return SDValue(); 8545 } 8546 8547 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8548 DAGCombinerInfo &DCI) 8549 const { 8550 SDValue Src = N->getOperand(0); 8551 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8552 8553 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8554 VTSign->getVT() == MVT::i8) || 8555 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8556 VTSign->getVT() == MVT::i16)) && 8557 Src.hasOneUse()) { 8558 auto *M = cast<MemSDNode>(Src); 8559 SDValue Ops[] = { 8560 Src.getOperand(0), // Chain 8561 Src.getOperand(1), // rsrc 8562 Src.getOperand(2), // vindex 8563 Src.getOperand(3), // voffset 8564 Src.getOperand(4), // soffset 8565 Src.getOperand(5), // offset 8566 Src.getOperand(6), 8567 Src.getOperand(7) 8568 }; 8569 // replace with BUFFER_LOAD_BYTE/SHORT 8570 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8571 Src.getOperand(0).getValueType()); 8572 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8573 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8574 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8575 ResList, 8576 Ops, M->getMemoryVT(), 8577 M->getMemOperand()); 8578 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8579 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8580 } 8581 return SDValue(); 8582 } 8583 8584 SDValue SITargetLowering::performClassCombine(SDNode *N, 8585 DAGCombinerInfo &DCI) const { 8586 SelectionDAG &DAG = DCI.DAG; 8587 SDValue Mask = N->getOperand(1); 8588 8589 // fp_class x, 0 -> false 8590 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8591 if (CMask->isNullValue()) 8592 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8593 } 8594 8595 if (N->getOperand(0).isUndef()) 8596 return DAG.getUNDEF(MVT::i1); 8597 8598 return SDValue(); 8599 } 8600 8601 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8602 DAGCombinerInfo &DCI) const { 8603 EVT VT = N->getValueType(0); 8604 SDValue N0 = N->getOperand(0); 8605 8606 if (N0.isUndef()) 8607 return N0; 8608 8609 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8610 N0.getOpcode() == ISD::SINT_TO_FP)) { 8611 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8612 N->getFlags()); 8613 } 8614 8615 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8616 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8617 N0.getOperand(0), N->getFlags()); 8618 } 8619 8620 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8621 } 8622 8623 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8624 unsigned MaxDepth) const { 8625 unsigned Opcode = Op.getOpcode(); 8626 if (Opcode == ISD::FCANONICALIZE) 8627 return true; 8628 8629 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8630 auto F = CFP->getValueAPF(); 8631 if (F.isNaN() && F.isSignaling()) 8632 return false; 8633 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8634 } 8635 8636 // If source is a result of another standard FP operation it is already in 8637 // canonical form. 8638 if (MaxDepth == 0) 8639 return false; 8640 8641 switch (Opcode) { 8642 // These will flush denorms if required. 8643 case ISD::FADD: 8644 case ISD::FSUB: 8645 case ISD::FMUL: 8646 case ISD::FCEIL: 8647 case ISD::FFLOOR: 8648 case ISD::FMA: 8649 case ISD::FMAD: 8650 case ISD::FSQRT: 8651 case ISD::FDIV: 8652 case ISD::FREM: 8653 case ISD::FP_ROUND: 8654 case ISD::FP_EXTEND: 8655 case AMDGPUISD::FMUL_LEGACY: 8656 case AMDGPUISD::FMAD_FTZ: 8657 case AMDGPUISD::RCP: 8658 case AMDGPUISD::RSQ: 8659 case AMDGPUISD::RSQ_CLAMP: 8660 case AMDGPUISD::RCP_LEGACY: 8661 case AMDGPUISD::RSQ_LEGACY: 8662 case AMDGPUISD::RCP_IFLAG: 8663 case AMDGPUISD::TRIG_PREOP: 8664 case AMDGPUISD::DIV_SCALE: 8665 case AMDGPUISD::DIV_FMAS: 8666 case AMDGPUISD::DIV_FIXUP: 8667 case AMDGPUISD::FRACT: 8668 case AMDGPUISD::LDEXP: 8669 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8670 case AMDGPUISD::CVT_F32_UBYTE0: 8671 case AMDGPUISD::CVT_F32_UBYTE1: 8672 case AMDGPUISD::CVT_F32_UBYTE2: 8673 case AMDGPUISD::CVT_F32_UBYTE3: 8674 return true; 8675 8676 // It can/will be lowered or combined as a bit operation. 8677 // Need to check their input recursively to handle. 8678 case ISD::FNEG: 8679 case ISD::FABS: 8680 case ISD::FCOPYSIGN: 8681 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8682 8683 case ISD::FSIN: 8684 case ISD::FCOS: 8685 case ISD::FSINCOS: 8686 return Op.getValueType().getScalarType() != MVT::f16; 8687 8688 case ISD::FMINNUM: 8689 case ISD::FMAXNUM: 8690 case ISD::FMINNUM_IEEE: 8691 case ISD::FMAXNUM_IEEE: 8692 case AMDGPUISD::CLAMP: 8693 case AMDGPUISD::FMED3: 8694 case AMDGPUISD::FMAX3: 8695 case AMDGPUISD::FMIN3: { 8696 // FIXME: Shouldn't treat the generic operations different based these. 8697 // However, we aren't really required to flush the result from 8698 // minnum/maxnum.. 8699 8700 // snans will be quieted, so we only need to worry about denormals. 8701 if (Subtarget->supportsMinMaxDenormModes() || 8702 denormalsEnabledForType(DAG, Op.getValueType())) 8703 return true; 8704 8705 // Flushing may be required. 8706 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8707 // targets need to check their input recursively. 8708 8709 // FIXME: Does this apply with clamp? It's implemented with max. 8710 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8711 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8712 return false; 8713 } 8714 8715 return true; 8716 } 8717 case ISD::SELECT: { 8718 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8719 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8720 } 8721 case ISD::BUILD_VECTOR: { 8722 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8723 SDValue SrcOp = Op.getOperand(i); 8724 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8725 return false; 8726 } 8727 8728 return true; 8729 } 8730 case ISD::EXTRACT_VECTOR_ELT: 8731 case ISD::EXTRACT_SUBVECTOR: { 8732 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8733 } 8734 case ISD::INSERT_VECTOR_ELT: { 8735 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8736 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8737 } 8738 case ISD::UNDEF: 8739 // Could be anything. 8740 return false; 8741 8742 case ISD::BITCAST: { 8743 // Hack round the mess we make when legalizing extract_vector_elt 8744 SDValue Src = Op.getOperand(0); 8745 if (Src.getValueType() == MVT::i16 && 8746 Src.getOpcode() == ISD::TRUNCATE) { 8747 SDValue TruncSrc = Src.getOperand(0); 8748 if (TruncSrc.getValueType() == MVT::i32 && 8749 TruncSrc.getOpcode() == ISD::BITCAST && 8750 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8751 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8752 } 8753 } 8754 8755 return false; 8756 } 8757 case ISD::INTRINSIC_WO_CHAIN: { 8758 unsigned IntrinsicID 8759 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8760 // TODO: Handle more intrinsics 8761 switch (IntrinsicID) { 8762 case Intrinsic::amdgcn_cvt_pkrtz: 8763 case Intrinsic::amdgcn_cubeid: 8764 case Intrinsic::amdgcn_frexp_mant: 8765 case Intrinsic::amdgcn_fdot2: 8766 return true; 8767 default: 8768 break; 8769 } 8770 8771 LLVM_FALLTHROUGH; 8772 } 8773 default: 8774 return denormalsEnabledForType(DAG, Op.getValueType()) && 8775 DAG.isKnownNeverSNaN(Op); 8776 } 8777 8778 llvm_unreachable("invalid operation"); 8779 } 8780 8781 // Constant fold canonicalize. 8782 SDValue SITargetLowering::getCanonicalConstantFP( 8783 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8784 // Flush denormals to 0 if not enabled. 8785 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8786 return DAG.getConstantFP(0.0, SL, VT); 8787 8788 if (C.isNaN()) { 8789 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8790 if (C.isSignaling()) { 8791 // Quiet a signaling NaN. 8792 // FIXME: Is this supposed to preserve payload bits? 8793 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8794 } 8795 8796 // Make sure it is the canonical NaN bitpattern. 8797 // 8798 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8799 // immediate? 8800 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8801 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8802 } 8803 8804 // Already canonical. 8805 return DAG.getConstantFP(C, SL, VT); 8806 } 8807 8808 static bool vectorEltWillFoldAway(SDValue Op) { 8809 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8810 } 8811 8812 SDValue SITargetLowering::performFCanonicalizeCombine( 8813 SDNode *N, 8814 DAGCombinerInfo &DCI) const { 8815 SelectionDAG &DAG = DCI.DAG; 8816 SDValue N0 = N->getOperand(0); 8817 EVT VT = N->getValueType(0); 8818 8819 // fcanonicalize undef -> qnan 8820 if (N0.isUndef()) { 8821 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8822 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8823 } 8824 8825 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8826 EVT VT = N->getValueType(0); 8827 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8828 } 8829 8830 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8831 // (fcanonicalize k) 8832 // 8833 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8834 8835 // TODO: This could be better with wider vectors that will be split to v2f16, 8836 // and to consider uses since there aren't that many packed operations. 8837 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8838 isTypeLegal(MVT::v2f16)) { 8839 SDLoc SL(N); 8840 SDValue NewElts[2]; 8841 SDValue Lo = N0.getOperand(0); 8842 SDValue Hi = N0.getOperand(1); 8843 EVT EltVT = Lo.getValueType(); 8844 8845 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8846 for (unsigned I = 0; I != 2; ++I) { 8847 SDValue Op = N0.getOperand(I); 8848 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8849 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8850 CFP->getValueAPF()); 8851 } else if (Op.isUndef()) { 8852 // Handled below based on what the other operand is. 8853 NewElts[I] = Op; 8854 } else { 8855 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8856 } 8857 } 8858 8859 // If one half is undef, and one is constant, perfer a splat vector rather 8860 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8861 // cheaper to use and may be free with a packed operation. 8862 if (NewElts[0].isUndef()) { 8863 if (isa<ConstantFPSDNode>(NewElts[1])) 8864 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8865 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8866 } 8867 8868 if (NewElts[1].isUndef()) { 8869 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8870 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8871 } 8872 8873 return DAG.getBuildVector(VT, SL, NewElts); 8874 } 8875 } 8876 8877 unsigned SrcOpc = N0.getOpcode(); 8878 8879 // If it's free to do so, push canonicalizes further up the source, which may 8880 // find a canonical source. 8881 // 8882 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8883 // sNaNs. 8884 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8885 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8886 if (CRHS && N0.hasOneUse()) { 8887 SDLoc SL(N); 8888 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8889 N0.getOperand(0)); 8890 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8891 DCI.AddToWorklist(Canon0.getNode()); 8892 8893 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8894 } 8895 } 8896 8897 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8898 } 8899 8900 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8901 switch (Opc) { 8902 case ISD::FMAXNUM: 8903 case ISD::FMAXNUM_IEEE: 8904 return AMDGPUISD::FMAX3; 8905 case ISD::SMAX: 8906 return AMDGPUISD::SMAX3; 8907 case ISD::UMAX: 8908 return AMDGPUISD::UMAX3; 8909 case ISD::FMINNUM: 8910 case ISD::FMINNUM_IEEE: 8911 return AMDGPUISD::FMIN3; 8912 case ISD::SMIN: 8913 return AMDGPUISD::SMIN3; 8914 case ISD::UMIN: 8915 return AMDGPUISD::UMIN3; 8916 default: 8917 llvm_unreachable("Not a min/max opcode"); 8918 } 8919 } 8920 8921 SDValue SITargetLowering::performIntMed3ImmCombine( 8922 SelectionDAG &DAG, const SDLoc &SL, 8923 SDValue Op0, SDValue Op1, bool Signed) const { 8924 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8925 if (!K1) 8926 return SDValue(); 8927 8928 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8929 if (!K0) 8930 return SDValue(); 8931 8932 if (Signed) { 8933 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8934 return SDValue(); 8935 } else { 8936 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8937 return SDValue(); 8938 } 8939 8940 EVT VT = K0->getValueType(0); 8941 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8942 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8943 return DAG.getNode(Med3Opc, SL, VT, 8944 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8945 } 8946 8947 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8948 MVT NVT = MVT::i32; 8949 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8950 8951 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8952 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8953 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8954 8955 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8956 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8957 } 8958 8959 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8960 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8961 return C; 8962 8963 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8964 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8965 return C; 8966 } 8967 8968 return nullptr; 8969 } 8970 8971 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8972 const SDLoc &SL, 8973 SDValue Op0, 8974 SDValue Op1) const { 8975 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8976 if (!K1) 8977 return SDValue(); 8978 8979 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 8980 if (!K0) 8981 return SDValue(); 8982 8983 // Ordered >= (although NaN inputs should have folded away by now). 8984 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 8985 if (Cmp == APFloat::cmpGreaterThan) 8986 return SDValue(); 8987 8988 const MachineFunction &MF = DAG.getMachineFunction(); 8989 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 8990 8991 // TODO: Check IEEE bit enabled? 8992 EVT VT = Op0.getValueType(); 8993 if (Info->getMode().DX10Clamp) { 8994 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 8995 // hardware fmed3 behavior converting to a min. 8996 // FIXME: Should this be allowing -0.0? 8997 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 8998 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 8999 } 9000 9001 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9002 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9003 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9004 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9005 // then give the other result, which is different from med3 with a NaN 9006 // input. 9007 SDValue Var = Op0.getOperand(0); 9008 if (!DAG.isKnownNeverSNaN(Var)) 9009 return SDValue(); 9010 9011 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9012 9013 if ((!K0->hasOneUse() || 9014 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9015 (!K1->hasOneUse() || 9016 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9017 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9018 Var, SDValue(K0, 0), SDValue(K1, 0)); 9019 } 9020 } 9021 9022 return SDValue(); 9023 } 9024 9025 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9026 DAGCombinerInfo &DCI) const { 9027 SelectionDAG &DAG = DCI.DAG; 9028 9029 EVT VT = N->getValueType(0); 9030 unsigned Opc = N->getOpcode(); 9031 SDValue Op0 = N->getOperand(0); 9032 SDValue Op1 = N->getOperand(1); 9033 9034 // Only do this if the inner op has one use since this will just increases 9035 // register pressure for no benefit. 9036 9037 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9038 !VT.isVector() && 9039 (VT == MVT::i32 || VT == MVT::f32 || 9040 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9041 // max(max(a, b), c) -> max3(a, b, c) 9042 // min(min(a, b), c) -> min3(a, b, c) 9043 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9044 SDLoc DL(N); 9045 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9046 DL, 9047 N->getValueType(0), 9048 Op0.getOperand(0), 9049 Op0.getOperand(1), 9050 Op1); 9051 } 9052 9053 // Try commuted. 9054 // max(a, max(b, c)) -> max3(a, b, c) 9055 // min(a, min(b, c)) -> min3(a, b, c) 9056 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9057 SDLoc DL(N); 9058 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9059 DL, 9060 N->getValueType(0), 9061 Op0, 9062 Op1.getOperand(0), 9063 Op1.getOperand(1)); 9064 } 9065 } 9066 9067 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9068 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9069 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9070 return Med3; 9071 } 9072 9073 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9074 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9075 return Med3; 9076 } 9077 9078 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9079 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9080 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9081 (Opc == AMDGPUISD::FMIN_LEGACY && 9082 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9083 (VT == MVT::f32 || VT == MVT::f64 || 9084 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9085 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9086 Op0.hasOneUse()) { 9087 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9088 return Res; 9089 } 9090 9091 return SDValue(); 9092 } 9093 9094 static bool isClampZeroToOne(SDValue A, SDValue B) { 9095 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9096 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9097 // FIXME: Should this be allowing -0.0? 9098 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9099 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9100 } 9101 } 9102 9103 return false; 9104 } 9105 9106 // FIXME: Should only worry about snans for version with chain. 9107 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9108 DAGCombinerInfo &DCI) const { 9109 EVT VT = N->getValueType(0); 9110 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9111 // NaNs. With a NaN input, the order of the operands may change the result. 9112 9113 SelectionDAG &DAG = DCI.DAG; 9114 SDLoc SL(N); 9115 9116 SDValue Src0 = N->getOperand(0); 9117 SDValue Src1 = N->getOperand(1); 9118 SDValue Src2 = N->getOperand(2); 9119 9120 if (isClampZeroToOne(Src0, Src1)) { 9121 // const_a, const_b, x -> clamp is safe in all cases including signaling 9122 // nans. 9123 // FIXME: Should this be allowing -0.0? 9124 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9125 } 9126 9127 const MachineFunction &MF = DAG.getMachineFunction(); 9128 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9129 9130 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9131 // handling no dx10-clamp? 9132 if (Info->getMode().DX10Clamp) { 9133 // If NaNs is clamped to 0, we are free to reorder the inputs. 9134 9135 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9136 std::swap(Src0, Src1); 9137 9138 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9139 std::swap(Src1, Src2); 9140 9141 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9142 std::swap(Src0, Src1); 9143 9144 if (isClampZeroToOne(Src1, Src2)) 9145 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9146 } 9147 9148 return SDValue(); 9149 } 9150 9151 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9152 DAGCombinerInfo &DCI) const { 9153 SDValue Src0 = N->getOperand(0); 9154 SDValue Src1 = N->getOperand(1); 9155 if (Src0.isUndef() && Src1.isUndef()) 9156 return DCI.DAG.getUNDEF(N->getValueType(0)); 9157 return SDValue(); 9158 } 9159 9160 SDValue SITargetLowering::performExtractVectorEltCombine( 9161 SDNode *N, DAGCombinerInfo &DCI) const { 9162 SDValue Vec = N->getOperand(0); 9163 SelectionDAG &DAG = DCI.DAG; 9164 9165 EVT VecVT = Vec.getValueType(); 9166 EVT EltVT = VecVT.getVectorElementType(); 9167 9168 if ((Vec.getOpcode() == ISD::FNEG || 9169 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9170 SDLoc SL(N); 9171 EVT EltVT = N->getValueType(0); 9172 SDValue Idx = N->getOperand(1); 9173 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9174 Vec.getOperand(0), Idx); 9175 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9176 } 9177 9178 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9179 // => 9180 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9181 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9182 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9183 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9184 SDLoc SL(N); 9185 EVT EltVT = N->getValueType(0); 9186 SDValue Idx = N->getOperand(1); 9187 unsigned Opc = Vec.getOpcode(); 9188 9189 switch(Opc) { 9190 default: 9191 break; 9192 // TODO: Support other binary operations. 9193 case ISD::FADD: 9194 case ISD::FSUB: 9195 case ISD::FMUL: 9196 case ISD::ADD: 9197 case ISD::UMIN: 9198 case ISD::UMAX: 9199 case ISD::SMIN: 9200 case ISD::SMAX: 9201 case ISD::FMAXNUM: 9202 case ISD::FMINNUM: 9203 case ISD::FMAXNUM_IEEE: 9204 case ISD::FMINNUM_IEEE: { 9205 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9206 Vec.getOperand(0), Idx); 9207 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9208 Vec.getOperand(1), Idx); 9209 9210 DCI.AddToWorklist(Elt0.getNode()); 9211 DCI.AddToWorklist(Elt1.getNode()); 9212 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9213 } 9214 } 9215 } 9216 9217 unsigned VecSize = VecVT.getSizeInBits(); 9218 unsigned EltSize = EltVT.getSizeInBits(); 9219 9220 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9221 // This elminates non-constant index and subsequent movrel or scratch access. 9222 // Sub-dword vectors of size 2 dword or less have better implementation. 9223 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9224 // instructions. 9225 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9226 !isa<ConstantSDNode>(N->getOperand(1))) { 9227 SDLoc SL(N); 9228 SDValue Idx = N->getOperand(1); 9229 SDValue V; 9230 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9231 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9232 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9233 if (I == 0) 9234 V = Elt; 9235 else 9236 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9237 } 9238 return V; 9239 } 9240 9241 if (!DCI.isBeforeLegalize()) 9242 return SDValue(); 9243 9244 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9245 // elements. This exposes more load reduction opportunities by replacing 9246 // multiple small extract_vector_elements with a single 32-bit extract. 9247 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9248 if (isa<MemSDNode>(Vec) && 9249 EltSize <= 16 && 9250 EltVT.isByteSized() && 9251 VecSize > 32 && 9252 VecSize % 32 == 0 && 9253 Idx) { 9254 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9255 9256 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9257 unsigned EltIdx = BitIndex / 32; 9258 unsigned LeftoverBitIdx = BitIndex % 32; 9259 SDLoc SL(N); 9260 9261 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9262 DCI.AddToWorklist(Cast.getNode()); 9263 9264 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9265 DAG.getConstant(EltIdx, SL, MVT::i32)); 9266 DCI.AddToWorklist(Elt.getNode()); 9267 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9268 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9269 DCI.AddToWorklist(Srl.getNode()); 9270 9271 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9272 DCI.AddToWorklist(Trunc.getNode()); 9273 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9274 } 9275 9276 return SDValue(); 9277 } 9278 9279 SDValue 9280 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9281 DAGCombinerInfo &DCI) const { 9282 SDValue Vec = N->getOperand(0); 9283 SDValue Idx = N->getOperand(2); 9284 EVT VecVT = Vec.getValueType(); 9285 EVT EltVT = VecVT.getVectorElementType(); 9286 unsigned VecSize = VecVT.getSizeInBits(); 9287 unsigned EltSize = EltVT.getSizeInBits(); 9288 9289 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9290 // => BUILD_VECTOR n x select (e, const-idx) 9291 // This elminates non-constant index and subsequent movrel or scratch access. 9292 // Sub-dword vectors of size 2 dword or less have better implementation. 9293 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9294 // instructions. 9295 if (isa<ConstantSDNode>(Idx) || 9296 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9297 return SDValue(); 9298 9299 SelectionDAG &DAG = DCI.DAG; 9300 SDLoc SL(N); 9301 SDValue Ins = N->getOperand(1); 9302 EVT IdxVT = Idx.getValueType(); 9303 9304 SmallVector<SDValue, 16> Ops; 9305 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9306 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9307 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9308 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9309 Ops.push_back(V); 9310 } 9311 9312 return DAG.getBuildVector(VecVT, SL, Ops); 9313 } 9314 9315 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9316 const SDNode *N0, 9317 const SDNode *N1) const { 9318 EVT VT = N0->getValueType(0); 9319 9320 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9321 // support denormals ever. 9322 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9323 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9324 getSubtarget()->hasMadF16())) && 9325 isOperationLegal(ISD::FMAD, VT)) 9326 return ISD::FMAD; 9327 9328 const TargetOptions &Options = DAG.getTarget().Options; 9329 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9330 (N0->getFlags().hasAllowContract() && 9331 N1->getFlags().hasAllowContract())) && 9332 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9333 return ISD::FMA; 9334 } 9335 9336 return 0; 9337 } 9338 9339 // For a reassociatable opcode perform: 9340 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9341 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9342 SelectionDAG &DAG) const { 9343 EVT VT = N->getValueType(0); 9344 if (VT != MVT::i32 && VT != MVT::i64) 9345 return SDValue(); 9346 9347 unsigned Opc = N->getOpcode(); 9348 SDValue Op0 = N->getOperand(0); 9349 SDValue Op1 = N->getOperand(1); 9350 9351 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9352 return SDValue(); 9353 9354 if (Op0->isDivergent()) 9355 std::swap(Op0, Op1); 9356 9357 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9358 return SDValue(); 9359 9360 SDValue Op2 = Op1.getOperand(1); 9361 Op1 = Op1.getOperand(0); 9362 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9363 return SDValue(); 9364 9365 if (Op1->isDivergent()) 9366 std::swap(Op1, Op2); 9367 9368 // If either operand is constant this will conflict with 9369 // DAGCombiner::ReassociateOps(). 9370 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9371 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9372 return SDValue(); 9373 9374 SDLoc SL(N); 9375 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9376 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9377 } 9378 9379 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9380 EVT VT, 9381 SDValue N0, SDValue N1, SDValue N2, 9382 bool Signed) { 9383 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9384 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9385 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9386 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9387 } 9388 9389 SDValue SITargetLowering::performAddCombine(SDNode *N, 9390 DAGCombinerInfo &DCI) const { 9391 SelectionDAG &DAG = DCI.DAG; 9392 EVT VT = N->getValueType(0); 9393 SDLoc SL(N); 9394 SDValue LHS = N->getOperand(0); 9395 SDValue RHS = N->getOperand(1); 9396 9397 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9398 && Subtarget->hasMad64_32() && 9399 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9400 VT.getScalarSizeInBits() <= 64) { 9401 if (LHS.getOpcode() != ISD::MUL) 9402 std::swap(LHS, RHS); 9403 9404 SDValue MulLHS = LHS.getOperand(0); 9405 SDValue MulRHS = LHS.getOperand(1); 9406 SDValue AddRHS = RHS; 9407 9408 // TODO: Maybe restrict if SGPR inputs. 9409 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9410 numBitsUnsigned(MulRHS, DAG) <= 32) { 9411 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9412 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9413 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9414 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9415 } 9416 9417 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9418 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9419 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9420 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9421 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9422 } 9423 9424 return SDValue(); 9425 } 9426 9427 if (SDValue V = reassociateScalarOps(N, DAG)) { 9428 return V; 9429 } 9430 9431 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9432 return SDValue(); 9433 9434 // add x, zext (setcc) => addcarry x, 0, setcc 9435 // add x, sext (setcc) => subcarry x, 0, setcc 9436 unsigned Opc = LHS.getOpcode(); 9437 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9438 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9439 std::swap(RHS, LHS); 9440 9441 Opc = RHS.getOpcode(); 9442 switch (Opc) { 9443 default: break; 9444 case ISD::ZERO_EXTEND: 9445 case ISD::SIGN_EXTEND: 9446 case ISD::ANY_EXTEND: { 9447 auto Cond = RHS.getOperand(0); 9448 // If this won't be a real VOPC output, we would still need to insert an 9449 // extra instruction anyway. 9450 if (!isBoolSGPR(Cond)) 9451 break; 9452 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9453 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9454 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9455 return DAG.getNode(Opc, SL, VTList, Args); 9456 } 9457 case ISD::ADDCARRY: { 9458 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9459 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9460 if (!C || C->getZExtValue() != 0) break; 9461 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9462 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9463 } 9464 } 9465 return SDValue(); 9466 } 9467 9468 SDValue SITargetLowering::performSubCombine(SDNode *N, 9469 DAGCombinerInfo &DCI) const { 9470 SelectionDAG &DAG = DCI.DAG; 9471 EVT VT = N->getValueType(0); 9472 9473 if (VT != MVT::i32) 9474 return SDValue(); 9475 9476 SDLoc SL(N); 9477 SDValue LHS = N->getOperand(0); 9478 SDValue RHS = N->getOperand(1); 9479 9480 // sub x, zext (setcc) => subcarry x, 0, setcc 9481 // sub x, sext (setcc) => addcarry x, 0, setcc 9482 unsigned Opc = RHS.getOpcode(); 9483 switch (Opc) { 9484 default: break; 9485 case ISD::ZERO_EXTEND: 9486 case ISD::SIGN_EXTEND: 9487 case ISD::ANY_EXTEND: { 9488 auto Cond = RHS.getOperand(0); 9489 // If this won't be a real VOPC output, we would still need to insert an 9490 // extra instruction anyway. 9491 if (!isBoolSGPR(Cond)) 9492 break; 9493 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9494 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9495 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9496 return DAG.getNode(Opc, SL, VTList, Args); 9497 } 9498 } 9499 9500 if (LHS.getOpcode() == ISD::SUBCARRY) { 9501 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9502 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9503 if (!C || !C->isNullValue()) 9504 return SDValue(); 9505 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9506 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9507 } 9508 return SDValue(); 9509 } 9510 9511 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9512 DAGCombinerInfo &DCI) const { 9513 9514 if (N->getValueType(0) != MVT::i32) 9515 return SDValue(); 9516 9517 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9518 if (!C || C->getZExtValue() != 0) 9519 return SDValue(); 9520 9521 SelectionDAG &DAG = DCI.DAG; 9522 SDValue LHS = N->getOperand(0); 9523 9524 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9525 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9526 unsigned LHSOpc = LHS.getOpcode(); 9527 unsigned Opc = N->getOpcode(); 9528 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9529 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9530 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9531 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9532 } 9533 return SDValue(); 9534 } 9535 9536 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9537 DAGCombinerInfo &DCI) const { 9538 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9539 return SDValue(); 9540 9541 SelectionDAG &DAG = DCI.DAG; 9542 EVT VT = N->getValueType(0); 9543 9544 SDLoc SL(N); 9545 SDValue LHS = N->getOperand(0); 9546 SDValue RHS = N->getOperand(1); 9547 9548 // These should really be instruction patterns, but writing patterns with 9549 // source modiifiers is a pain. 9550 9551 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9552 if (LHS.getOpcode() == ISD::FADD) { 9553 SDValue A = LHS.getOperand(0); 9554 if (A == LHS.getOperand(1)) { 9555 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9556 if (FusedOp != 0) { 9557 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9558 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9559 } 9560 } 9561 } 9562 9563 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9564 if (RHS.getOpcode() == ISD::FADD) { 9565 SDValue A = RHS.getOperand(0); 9566 if (A == RHS.getOperand(1)) { 9567 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9568 if (FusedOp != 0) { 9569 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9570 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9571 } 9572 } 9573 } 9574 9575 return SDValue(); 9576 } 9577 9578 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9579 DAGCombinerInfo &DCI) const { 9580 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9581 return SDValue(); 9582 9583 SelectionDAG &DAG = DCI.DAG; 9584 SDLoc SL(N); 9585 EVT VT = N->getValueType(0); 9586 assert(!VT.isVector()); 9587 9588 // Try to get the fneg to fold into the source modifier. This undoes generic 9589 // DAG combines and folds them into the mad. 9590 // 9591 // Only do this if we are not trying to support denormals. v_mad_f32 does 9592 // not support denormals ever. 9593 SDValue LHS = N->getOperand(0); 9594 SDValue RHS = N->getOperand(1); 9595 if (LHS.getOpcode() == ISD::FADD) { 9596 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9597 SDValue A = LHS.getOperand(0); 9598 if (A == LHS.getOperand(1)) { 9599 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9600 if (FusedOp != 0){ 9601 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9602 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9603 9604 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9605 } 9606 } 9607 } 9608 9609 if (RHS.getOpcode() == ISD::FADD) { 9610 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9611 9612 SDValue A = RHS.getOperand(0); 9613 if (A == RHS.getOperand(1)) { 9614 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9615 if (FusedOp != 0){ 9616 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9617 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9618 } 9619 } 9620 } 9621 9622 return SDValue(); 9623 } 9624 9625 SDValue SITargetLowering::performFMACombine(SDNode *N, 9626 DAGCombinerInfo &DCI) const { 9627 SelectionDAG &DAG = DCI.DAG; 9628 EVT VT = N->getValueType(0); 9629 SDLoc SL(N); 9630 9631 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9632 return SDValue(); 9633 9634 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9635 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9636 SDValue Op1 = N->getOperand(0); 9637 SDValue Op2 = N->getOperand(1); 9638 SDValue FMA = N->getOperand(2); 9639 9640 if (FMA.getOpcode() != ISD::FMA || 9641 Op1.getOpcode() != ISD::FP_EXTEND || 9642 Op2.getOpcode() != ISD::FP_EXTEND) 9643 return SDValue(); 9644 9645 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9646 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9647 // is sufficient to allow generaing fdot2. 9648 const TargetOptions &Options = DAG.getTarget().Options; 9649 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9650 (N->getFlags().hasAllowContract() && 9651 FMA->getFlags().hasAllowContract())) { 9652 Op1 = Op1.getOperand(0); 9653 Op2 = Op2.getOperand(0); 9654 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9655 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9656 return SDValue(); 9657 9658 SDValue Vec1 = Op1.getOperand(0); 9659 SDValue Idx1 = Op1.getOperand(1); 9660 SDValue Vec2 = Op2.getOperand(0); 9661 9662 SDValue FMAOp1 = FMA.getOperand(0); 9663 SDValue FMAOp2 = FMA.getOperand(1); 9664 SDValue FMAAcc = FMA.getOperand(2); 9665 9666 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9667 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9668 return SDValue(); 9669 9670 FMAOp1 = FMAOp1.getOperand(0); 9671 FMAOp2 = FMAOp2.getOperand(0); 9672 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9673 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9674 return SDValue(); 9675 9676 SDValue Vec3 = FMAOp1.getOperand(0); 9677 SDValue Vec4 = FMAOp2.getOperand(0); 9678 SDValue Idx2 = FMAOp1.getOperand(1); 9679 9680 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9681 // Idx1 and Idx2 cannot be the same. 9682 Idx1 == Idx2) 9683 return SDValue(); 9684 9685 if (Vec1 == Vec2 || Vec3 == Vec4) 9686 return SDValue(); 9687 9688 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9689 return SDValue(); 9690 9691 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9692 (Vec1 == Vec4 && Vec2 == Vec3)) { 9693 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9694 DAG.getTargetConstant(0, SL, MVT::i1)); 9695 } 9696 } 9697 return SDValue(); 9698 } 9699 9700 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9701 DAGCombinerInfo &DCI) const { 9702 SelectionDAG &DAG = DCI.DAG; 9703 SDLoc SL(N); 9704 9705 SDValue LHS = N->getOperand(0); 9706 SDValue RHS = N->getOperand(1); 9707 EVT VT = LHS.getValueType(); 9708 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9709 9710 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9711 if (!CRHS) { 9712 CRHS = dyn_cast<ConstantSDNode>(LHS); 9713 if (CRHS) { 9714 std::swap(LHS, RHS); 9715 CC = getSetCCSwappedOperands(CC); 9716 } 9717 } 9718 9719 if (CRHS) { 9720 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9721 isBoolSGPR(LHS.getOperand(0))) { 9722 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9723 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9724 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9725 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9726 if ((CRHS->isAllOnesValue() && 9727 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9728 (CRHS->isNullValue() && 9729 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9730 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9731 DAG.getConstant(-1, SL, MVT::i1)); 9732 if ((CRHS->isAllOnesValue() && 9733 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9734 (CRHS->isNullValue() && 9735 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9736 return LHS.getOperand(0); 9737 } 9738 9739 uint64_t CRHSVal = CRHS->getZExtValue(); 9740 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9741 LHS.getOpcode() == ISD::SELECT && 9742 isa<ConstantSDNode>(LHS.getOperand(1)) && 9743 isa<ConstantSDNode>(LHS.getOperand(2)) && 9744 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9745 isBoolSGPR(LHS.getOperand(0))) { 9746 // Given CT != FT: 9747 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9748 // setcc (select cc, CT, CF), CF, ne => cc 9749 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9750 // setcc (select cc, CT, CF), CT, eq => cc 9751 uint64_t CT = LHS.getConstantOperandVal(1); 9752 uint64_t CF = LHS.getConstantOperandVal(2); 9753 9754 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9755 (CT == CRHSVal && CC == ISD::SETNE)) 9756 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9757 DAG.getConstant(-1, SL, MVT::i1)); 9758 if ((CF == CRHSVal && CC == ISD::SETNE) || 9759 (CT == CRHSVal && CC == ISD::SETEQ)) 9760 return LHS.getOperand(0); 9761 } 9762 } 9763 9764 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9765 VT != MVT::f16)) 9766 return SDValue(); 9767 9768 // Match isinf/isfinite pattern 9769 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9770 // (fcmp one (fabs x), inf) -> (fp_class x, 9771 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9772 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9773 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9774 if (!CRHS) 9775 return SDValue(); 9776 9777 const APFloat &APF = CRHS->getValueAPF(); 9778 if (APF.isInfinity() && !APF.isNegative()) { 9779 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9780 SIInstrFlags::N_INFINITY; 9781 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9782 SIInstrFlags::P_ZERO | 9783 SIInstrFlags::N_NORMAL | 9784 SIInstrFlags::P_NORMAL | 9785 SIInstrFlags::N_SUBNORMAL | 9786 SIInstrFlags::P_SUBNORMAL; 9787 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9788 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9789 DAG.getConstant(Mask, SL, MVT::i32)); 9790 } 9791 } 9792 9793 return SDValue(); 9794 } 9795 9796 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9797 DAGCombinerInfo &DCI) const { 9798 SelectionDAG &DAG = DCI.DAG; 9799 SDLoc SL(N); 9800 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9801 9802 SDValue Src = N->getOperand(0); 9803 SDValue Srl = N->getOperand(0); 9804 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9805 Srl = Srl.getOperand(0); 9806 9807 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9808 if (Srl.getOpcode() == ISD::SRL) { 9809 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9810 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9811 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9812 9813 if (const ConstantSDNode *C = 9814 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9815 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9816 EVT(MVT::i32)); 9817 9818 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9819 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9820 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9821 MVT::f32, Srl); 9822 } 9823 } 9824 } 9825 9826 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9827 9828 KnownBits Known; 9829 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9830 !DCI.isBeforeLegalizeOps()); 9831 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9832 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9833 DCI.CommitTargetLoweringOpt(TLO); 9834 } 9835 9836 return SDValue(); 9837 } 9838 9839 SDValue SITargetLowering::performClampCombine(SDNode *N, 9840 DAGCombinerInfo &DCI) const { 9841 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9842 if (!CSrc) 9843 return SDValue(); 9844 9845 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9846 const APFloat &F = CSrc->getValueAPF(); 9847 APFloat Zero = APFloat::getZero(F.getSemantics()); 9848 APFloat::cmpResult Cmp0 = F.compare(Zero); 9849 if (Cmp0 == APFloat::cmpLessThan || 9850 (Cmp0 == APFloat::cmpUnordered && 9851 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9852 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9853 } 9854 9855 APFloat One(F.getSemantics(), "1.0"); 9856 APFloat::cmpResult Cmp1 = F.compare(One); 9857 if (Cmp1 == APFloat::cmpGreaterThan) 9858 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9859 9860 return SDValue(CSrc, 0); 9861 } 9862 9863 9864 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9865 DAGCombinerInfo &DCI) const { 9866 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9867 return SDValue(); 9868 switch (N->getOpcode()) { 9869 default: 9870 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9871 case ISD::ADD: 9872 return performAddCombine(N, DCI); 9873 case ISD::SUB: 9874 return performSubCombine(N, DCI); 9875 case ISD::ADDCARRY: 9876 case ISD::SUBCARRY: 9877 return performAddCarrySubCarryCombine(N, DCI); 9878 case ISD::FADD: 9879 return performFAddCombine(N, DCI); 9880 case ISD::FSUB: 9881 return performFSubCombine(N, DCI); 9882 case ISD::SETCC: 9883 return performSetCCCombine(N, DCI); 9884 case ISD::FMAXNUM: 9885 case ISD::FMINNUM: 9886 case ISD::FMAXNUM_IEEE: 9887 case ISD::FMINNUM_IEEE: 9888 case ISD::SMAX: 9889 case ISD::SMIN: 9890 case ISD::UMAX: 9891 case ISD::UMIN: 9892 case AMDGPUISD::FMIN_LEGACY: 9893 case AMDGPUISD::FMAX_LEGACY: 9894 return performMinMaxCombine(N, DCI); 9895 case ISD::FMA: 9896 return performFMACombine(N, DCI); 9897 case ISD::LOAD: { 9898 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9899 return Widended; 9900 LLVM_FALLTHROUGH; 9901 } 9902 case ISD::STORE: 9903 case ISD::ATOMIC_LOAD: 9904 case ISD::ATOMIC_STORE: 9905 case ISD::ATOMIC_CMP_SWAP: 9906 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9907 case ISD::ATOMIC_SWAP: 9908 case ISD::ATOMIC_LOAD_ADD: 9909 case ISD::ATOMIC_LOAD_SUB: 9910 case ISD::ATOMIC_LOAD_AND: 9911 case ISD::ATOMIC_LOAD_OR: 9912 case ISD::ATOMIC_LOAD_XOR: 9913 case ISD::ATOMIC_LOAD_NAND: 9914 case ISD::ATOMIC_LOAD_MIN: 9915 case ISD::ATOMIC_LOAD_MAX: 9916 case ISD::ATOMIC_LOAD_UMIN: 9917 case ISD::ATOMIC_LOAD_UMAX: 9918 case ISD::ATOMIC_LOAD_FADD: 9919 case AMDGPUISD::ATOMIC_INC: 9920 case AMDGPUISD::ATOMIC_DEC: 9921 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9922 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9923 if (DCI.isBeforeLegalize()) 9924 break; 9925 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9926 case ISD::AND: 9927 return performAndCombine(N, DCI); 9928 case ISD::OR: 9929 return performOrCombine(N, DCI); 9930 case ISD::XOR: 9931 return performXorCombine(N, DCI); 9932 case ISD::ZERO_EXTEND: 9933 return performZeroExtendCombine(N, DCI); 9934 case ISD::SIGN_EXTEND_INREG: 9935 return performSignExtendInRegCombine(N , DCI); 9936 case AMDGPUISD::FP_CLASS: 9937 return performClassCombine(N, DCI); 9938 case ISD::FCANONICALIZE: 9939 return performFCanonicalizeCombine(N, DCI); 9940 case AMDGPUISD::RCP: 9941 return performRcpCombine(N, DCI); 9942 case AMDGPUISD::FRACT: 9943 case AMDGPUISD::RSQ: 9944 case AMDGPUISD::RCP_LEGACY: 9945 case AMDGPUISD::RSQ_LEGACY: 9946 case AMDGPUISD::RCP_IFLAG: 9947 case AMDGPUISD::RSQ_CLAMP: 9948 case AMDGPUISD::LDEXP: { 9949 SDValue Src = N->getOperand(0); 9950 if (Src.isUndef()) 9951 return Src; 9952 break; 9953 } 9954 case ISD::SINT_TO_FP: 9955 case ISD::UINT_TO_FP: 9956 return performUCharToFloatCombine(N, DCI); 9957 case AMDGPUISD::CVT_F32_UBYTE0: 9958 case AMDGPUISD::CVT_F32_UBYTE1: 9959 case AMDGPUISD::CVT_F32_UBYTE2: 9960 case AMDGPUISD::CVT_F32_UBYTE3: 9961 return performCvtF32UByteNCombine(N, DCI); 9962 case AMDGPUISD::FMED3: 9963 return performFMed3Combine(N, DCI); 9964 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9965 return performCvtPkRTZCombine(N, DCI); 9966 case AMDGPUISD::CLAMP: 9967 return performClampCombine(N, DCI); 9968 case ISD::SCALAR_TO_VECTOR: { 9969 SelectionDAG &DAG = DCI.DAG; 9970 EVT VT = N->getValueType(0); 9971 9972 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9973 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9974 SDLoc SL(N); 9975 SDValue Src = N->getOperand(0); 9976 EVT EltVT = Src.getValueType(); 9977 if (EltVT == MVT::f16) 9978 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 9979 9980 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 9981 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 9982 } 9983 9984 break; 9985 } 9986 case ISD::EXTRACT_VECTOR_ELT: 9987 return performExtractVectorEltCombine(N, DCI); 9988 case ISD::INSERT_VECTOR_ELT: 9989 return performInsertVectorEltCombine(N, DCI); 9990 } 9991 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9992 } 9993 9994 /// Helper function for adjustWritemask 9995 static unsigned SubIdx2Lane(unsigned Idx) { 9996 switch (Idx) { 9997 default: return 0; 9998 case AMDGPU::sub0: return 0; 9999 case AMDGPU::sub1: return 1; 10000 case AMDGPU::sub2: return 2; 10001 case AMDGPU::sub3: return 3; 10002 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10003 } 10004 } 10005 10006 /// Adjust the writemask of MIMG instructions 10007 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10008 SelectionDAG &DAG) const { 10009 unsigned Opcode = Node->getMachineOpcode(); 10010 10011 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10012 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10013 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10014 return Node; // not implemented for D16 10015 10016 SDNode *Users[5] = { nullptr }; 10017 unsigned Lane = 0; 10018 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10019 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10020 unsigned NewDmask = 0; 10021 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10022 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10023 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10024 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10025 unsigned TFCLane = 0; 10026 bool HasChain = Node->getNumValues() > 1; 10027 10028 if (OldDmask == 0) { 10029 // These are folded out, but on the chance it happens don't assert. 10030 return Node; 10031 } 10032 10033 unsigned OldBitsSet = countPopulation(OldDmask); 10034 // Work out which is the TFE/LWE lane if that is enabled. 10035 if (UsesTFC) { 10036 TFCLane = OldBitsSet; 10037 } 10038 10039 // Try to figure out the used register components 10040 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10041 I != E; ++I) { 10042 10043 // Don't look at users of the chain. 10044 if (I.getUse().getResNo() != 0) 10045 continue; 10046 10047 // Abort if we can't understand the usage 10048 if (!I->isMachineOpcode() || 10049 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10050 return Node; 10051 10052 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10053 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10054 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10055 // set, etc. 10056 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10057 10058 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10059 if (UsesTFC && Lane == TFCLane) { 10060 Users[Lane] = *I; 10061 } else { 10062 // Set which texture component corresponds to the lane. 10063 unsigned Comp; 10064 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10065 Comp = countTrailingZeros(Dmask); 10066 Dmask &= ~(1 << Comp); 10067 } 10068 10069 // Abort if we have more than one user per component. 10070 if (Users[Lane]) 10071 return Node; 10072 10073 Users[Lane] = *I; 10074 NewDmask |= 1 << Comp; 10075 } 10076 } 10077 10078 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10079 bool NoChannels = !NewDmask; 10080 if (NoChannels) { 10081 if (!UsesTFC) { 10082 // No uses of the result and not using TFC. Then do nothing. 10083 return Node; 10084 } 10085 // If the original dmask has one channel - then nothing to do 10086 if (OldBitsSet == 1) 10087 return Node; 10088 // Use an arbitrary dmask - required for the instruction to work 10089 NewDmask = 1; 10090 } 10091 // Abort if there's no change 10092 if (NewDmask == OldDmask) 10093 return Node; 10094 10095 unsigned BitsSet = countPopulation(NewDmask); 10096 10097 // Check for TFE or LWE - increase the number of channels by one to account 10098 // for the extra return value 10099 // This will need adjustment for D16 if this is also included in 10100 // adjustWriteMask (this function) but at present D16 are excluded. 10101 unsigned NewChannels = BitsSet + UsesTFC; 10102 10103 int NewOpcode = 10104 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10105 assert(NewOpcode != -1 && 10106 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10107 "failed to find equivalent MIMG op"); 10108 10109 // Adjust the writemask in the node 10110 SmallVector<SDValue, 12> Ops; 10111 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10112 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10113 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10114 10115 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10116 10117 MVT ResultVT = NewChannels == 1 ? 10118 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10119 NewChannels == 5 ? 8 : NewChannels); 10120 SDVTList NewVTList = HasChain ? 10121 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10122 10123 10124 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10125 NewVTList, Ops); 10126 10127 if (HasChain) { 10128 // Update chain. 10129 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10130 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10131 } 10132 10133 if (NewChannels == 1) { 10134 assert(Node->hasNUsesOfValue(1, 0)); 10135 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10136 SDLoc(Node), Users[Lane]->getValueType(0), 10137 SDValue(NewNode, 0)); 10138 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10139 return nullptr; 10140 } 10141 10142 // Update the users of the node with the new indices 10143 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10144 SDNode *User = Users[i]; 10145 if (!User) { 10146 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10147 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10148 if (i || !NoChannels) 10149 continue; 10150 } else { 10151 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10152 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10153 } 10154 10155 switch (Idx) { 10156 default: break; 10157 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10158 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10159 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10160 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10161 } 10162 } 10163 10164 DAG.RemoveDeadNode(Node); 10165 return nullptr; 10166 } 10167 10168 static bool isFrameIndexOp(SDValue Op) { 10169 if (Op.getOpcode() == ISD::AssertZext) 10170 Op = Op.getOperand(0); 10171 10172 return isa<FrameIndexSDNode>(Op); 10173 } 10174 10175 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10176 /// with frame index operands. 10177 /// LLVM assumes that inputs are to these instructions are registers. 10178 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10179 SelectionDAG &DAG) const { 10180 if (Node->getOpcode() == ISD::CopyToReg) { 10181 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10182 SDValue SrcVal = Node->getOperand(2); 10183 10184 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10185 // to try understanding copies to physical registers. 10186 if (SrcVal.getValueType() == MVT::i1 && 10187 Register::isPhysicalRegister(DestReg->getReg())) { 10188 SDLoc SL(Node); 10189 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10190 SDValue VReg = DAG.getRegister( 10191 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10192 10193 SDNode *Glued = Node->getGluedNode(); 10194 SDValue ToVReg 10195 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10196 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10197 SDValue ToResultReg 10198 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10199 VReg, ToVReg.getValue(1)); 10200 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10201 DAG.RemoveDeadNode(Node); 10202 return ToResultReg.getNode(); 10203 } 10204 } 10205 10206 SmallVector<SDValue, 8> Ops; 10207 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10208 if (!isFrameIndexOp(Node->getOperand(i))) { 10209 Ops.push_back(Node->getOperand(i)); 10210 continue; 10211 } 10212 10213 SDLoc DL(Node); 10214 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10215 Node->getOperand(i).getValueType(), 10216 Node->getOperand(i)), 0)); 10217 } 10218 10219 return DAG.UpdateNodeOperands(Node, Ops); 10220 } 10221 10222 /// Fold the instructions after selecting them. 10223 /// Returns null if users were already updated. 10224 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10225 SelectionDAG &DAG) const { 10226 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10227 unsigned Opcode = Node->getMachineOpcode(); 10228 10229 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10230 !TII->isGather4(Opcode)) { 10231 return adjustWritemask(Node, DAG); 10232 } 10233 10234 if (Opcode == AMDGPU::INSERT_SUBREG || 10235 Opcode == AMDGPU::REG_SEQUENCE) { 10236 legalizeTargetIndependentNode(Node, DAG); 10237 return Node; 10238 } 10239 10240 switch (Opcode) { 10241 case AMDGPU::V_DIV_SCALE_F32: 10242 case AMDGPU::V_DIV_SCALE_F64: { 10243 // Satisfy the operand register constraint when one of the inputs is 10244 // undefined. Ordinarily each undef value will have its own implicit_def of 10245 // a vreg, so force these to use a single register. 10246 SDValue Src0 = Node->getOperand(0); 10247 SDValue Src1 = Node->getOperand(1); 10248 SDValue Src2 = Node->getOperand(2); 10249 10250 if ((Src0.isMachineOpcode() && 10251 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10252 (Src0 == Src1 || Src0 == Src2)) 10253 break; 10254 10255 MVT VT = Src0.getValueType().getSimpleVT(); 10256 const TargetRegisterClass *RC = 10257 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10258 10259 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10260 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10261 10262 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10263 UndefReg, Src0, SDValue()); 10264 10265 // src0 must be the same register as src1 or src2, even if the value is 10266 // undefined, so make sure we don't violate this constraint. 10267 if (Src0.isMachineOpcode() && 10268 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10269 if (Src1.isMachineOpcode() && 10270 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10271 Src0 = Src1; 10272 else if (Src2.isMachineOpcode() && 10273 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10274 Src0 = Src2; 10275 else { 10276 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10277 Src0 = UndefReg; 10278 Src1 = UndefReg; 10279 } 10280 } else 10281 break; 10282 10283 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10284 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10285 Ops.push_back(Node->getOperand(I)); 10286 10287 Ops.push_back(ImpDef.getValue(1)); 10288 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10289 } 10290 default: 10291 break; 10292 } 10293 10294 return Node; 10295 } 10296 10297 /// Assign the register class depending on the number of 10298 /// bits set in the writemask 10299 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10300 SDNode *Node) const { 10301 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10302 10303 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10304 10305 if (TII->isVOP3(MI.getOpcode())) { 10306 // Make sure constant bus requirements are respected. 10307 TII->legalizeOperandsVOP3(MRI, MI); 10308 10309 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10310 // This saves a chain-copy of registers and better ballance register 10311 // use between vgpr and agpr as agpr tuples tend to be big. 10312 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10313 unsigned Opc = MI.getOpcode(); 10314 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10315 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10316 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10317 if (I == -1) 10318 break; 10319 MachineOperand &Op = MI.getOperand(I); 10320 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10321 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10322 !Register::isVirtualRegister(Op.getReg()) || 10323 !TRI->isAGPR(MRI, Op.getReg())) 10324 continue; 10325 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10326 if (!Src || !Src->isCopy() || 10327 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10328 continue; 10329 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10330 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10331 // All uses of agpr64 and agpr32 can also accept vgpr except for 10332 // v_accvgpr_read, but we do not produce agpr reads during selection, 10333 // so no use checks are needed. 10334 MRI.setRegClass(Op.getReg(), NewRC); 10335 } 10336 } 10337 10338 return; 10339 } 10340 10341 // Replace unused atomics with the no return version. 10342 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10343 if (NoRetAtomicOp != -1) { 10344 if (!Node->hasAnyUseOfValue(0)) { 10345 MI.setDesc(TII->get(NoRetAtomicOp)); 10346 MI.RemoveOperand(0); 10347 return; 10348 } 10349 10350 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10351 // instruction, because the return type of these instructions is a vec2 of 10352 // the memory type, so it can be tied to the input operand. 10353 // This means these instructions always have a use, so we need to add a 10354 // special case to check if the atomic has only one extract_subreg use, 10355 // which itself has no uses. 10356 if ((Node->hasNUsesOfValue(1, 0) && 10357 Node->use_begin()->isMachineOpcode() && 10358 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10359 !Node->use_begin()->hasAnyUseOfValue(0))) { 10360 Register Def = MI.getOperand(0).getReg(); 10361 10362 // Change this into a noret atomic. 10363 MI.setDesc(TII->get(NoRetAtomicOp)); 10364 MI.RemoveOperand(0); 10365 10366 // If we only remove the def operand from the atomic instruction, the 10367 // extract_subreg will be left with a use of a vreg without a def. 10368 // So we need to insert an implicit_def to avoid machine verifier 10369 // errors. 10370 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10371 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10372 } 10373 return; 10374 } 10375 } 10376 10377 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10378 uint64_t Val) { 10379 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10380 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10381 } 10382 10383 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10384 const SDLoc &DL, 10385 SDValue Ptr) const { 10386 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10387 10388 // Build the half of the subregister with the constants before building the 10389 // full 128-bit register. If we are building multiple resource descriptors, 10390 // this will allow CSEing of the 2-component register. 10391 const SDValue Ops0[] = { 10392 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10393 buildSMovImm32(DAG, DL, 0), 10394 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10395 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10396 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10397 }; 10398 10399 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10400 MVT::v2i32, Ops0), 0); 10401 10402 // Combine the constants and the pointer. 10403 const SDValue Ops1[] = { 10404 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10405 Ptr, 10406 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10407 SubRegHi, 10408 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10409 }; 10410 10411 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10412 } 10413 10414 /// Return a resource descriptor with the 'Add TID' bit enabled 10415 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10416 /// of the resource descriptor) to create an offset, which is added to 10417 /// the resource pointer. 10418 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10419 SDValue Ptr, uint32_t RsrcDword1, 10420 uint64_t RsrcDword2And3) const { 10421 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10422 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10423 if (RsrcDword1) { 10424 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10425 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10426 0); 10427 } 10428 10429 SDValue DataLo = buildSMovImm32(DAG, DL, 10430 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10431 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10432 10433 const SDValue Ops[] = { 10434 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10435 PtrLo, 10436 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10437 PtrHi, 10438 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10439 DataLo, 10440 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10441 DataHi, 10442 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10443 }; 10444 10445 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10446 } 10447 10448 //===----------------------------------------------------------------------===// 10449 // SI Inline Assembly Support 10450 //===----------------------------------------------------------------------===// 10451 10452 std::pair<unsigned, const TargetRegisterClass *> 10453 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10454 StringRef Constraint, 10455 MVT VT) const { 10456 const TargetRegisterClass *RC = nullptr; 10457 if (Constraint.size() == 1) { 10458 switch (Constraint[0]) { 10459 default: 10460 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10461 case 's': 10462 case 'r': 10463 switch (VT.getSizeInBits()) { 10464 default: 10465 return std::make_pair(0U, nullptr); 10466 case 32: 10467 case 16: 10468 RC = &AMDGPU::SReg_32RegClass; 10469 break; 10470 case 64: 10471 RC = &AMDGPU::SGPR_64RegClass; 10472 break; 10473 case 96: 10474 RC = &AMDGPU::SReg_96RegClass; 10475 break; 10476 case 128: 10477 RC = &AMDGPU::SGPR_128RegClass; 10478 break; 10479 case 160: 10480 RC = &AMDGPU::SReg_160RegClass; 10481 break; 10482 case 256: 10483 RC = &AMDGPU::SReg_256RegClass; 10484 break; 10485 case 512: 10486 RC = &AMDGPU::SReg_512RegClass; 10487 break; 10488 } 10489 break; 10490 case 'v': 10491 switch (VT.getSizeInBits()) { 10492 default: 10493 return std::make_pair(0U, nullptr); 10494 case 32: 10495 case 16: 10496 RC = &AMDGPU::VGPR_32RegClass; 10497 break; 10498 case 64: 10499 RC = &AMDGPU::VReg_64RegClass; 10500 break; 10501 case 96: 10502 RC = &AMDGPU::VReg_96RegClass; 10503 break; 10504 case 128: 10505 RC = &AMDGPU::VReg_128RegClass; 10506 break; 10507 case 160: 10508 RC = &AMDGPU::VReg_160RegClass; 10509 break; 10510 case 256: 10511 RC = &AMDGPU::VReg_256RegClass; 10512 break; 10513 case 512: 10514 RC = &AMDGPU::VReg_512RegClass; 10515 break; 10516 } 10517 break; 10518 case 'a': 10519 if (!Subtarget->hasMAIInsts()) 10520 break; 10521 switch (VT.getSizeInBits()) { 10522 default: 10523 return std::make_pair(0U, nullptr); 10524 case 32: 10525 case 16: 10526 RC = &AMDGPU::AGPR_32RegClass; 10527 break; 10528 case 64: 10529 RC = &AMDGPU::AReg_64RegClass; 10530 break; 10531 case 128: 10532 RC = &AMDGPU::AReg_128RegClass; 10533 break; 10534 case 512: 10535 RC = &AMDGPU::AReg_512RegClass; 10536 break; 10537 case 1024: 10538 RC = &AMDGPU::AReg_1024RegClass; 10539 // v32 types are not legal but we support them here. 10540 return std::make_pair(0U, RC); 10541 } 10542 break; 10543 } 10544 // We actually support i128, i16 and f16 as inline parameters 10545 // even if they are not reported as legal 10546 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10547 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10548 return std::make_pair(0U, RC); 10549 } 10550 10551 if (Constraint.size() > 1) { 10552 if (Constraint[1] == 'v') { 10553 RC = &AMDGPU::VGPR_32RegClass; 10554 } else if (Constraint[1] == 's') { 10555 RC = &AMDGPU::SGPR_32RegClass; 10556 } else if (Constraint[1] == 'a') { 10557 RC = &AMDGPU::AGPR_32RegClass; 10558 } 10559 10560 if (RC) { 10561 uint32_t Idx; 10562 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10563 if (!Failed && Idx < RC->getNumRegs()) 10564 return std::make_pair(RC->getRegister(Idx), RC); 10565 } 10566 } 10567 10568 // FIXME: Returns VS_32 for physical SGPR constraints 10569 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10570 } 10571 10572 SITargetLowering::ConstraintType 10573 SITargetLowering::getConstraintType(StringRef Constraint) const { 10574 if (Constraint.size() == 1) { 10575 switch (Constraint[0]) { 10576 default: break; 10577 case 's': 10578 case 'v': 10579 case 'a': 10580 return C_RegisterClass; 10581 } 10582 } 10583 return TargetLowering::getConstraintType(Constraint); 10584 } 10585 10586 // Figure out which registers should be reserved for stack access. Only after 10587 // the function is legalized do we know all of the non-spill stack objects or if 10588 // calls are present. 10589 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10590 MachineRegisterInfo &MRI = MF.getRegInfo(); 10591 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10592 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10593 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10594 10595 if (Info->isEntryFunction()) { 10596 // Callable functions have fixed registers used for stack access. 10597 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10598 } 10599 10600 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10601 Info->getStackPtrOffsetReg())); 10602 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10603 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10604 10605 // We need to worry about replacing the default register with itself in case 10606 // of MIR testcases missing the MFI. 10607 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10608 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10609 10610 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10611 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10612 10613 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10614 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10615 Info->getScratchWaveOffsetReg()); 10616 } 10617 10618 Info->limitOccupancy(MF); 10619 10620 if (ST.isWave32() && !MF.empty()) { 10621 // Add VCC_HI def because many instructions marked as imp-use VCC where 10622 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10623 // having a use of undef. 10624 10625 const SIInstrInfo *TII = ST.getInstrInfo(); 10626 DebugLoc DL; 10627 10628 MachineBasicBlock &MBB = MF.front(); 10629 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10630 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10631 10632 for (auto &MBB : MF) { 10633 for (auto &MI : MBB) { 10634 TII->fixImplicitOperands(MI); 10635 } 10636 } 10637 } 10638 10639 TargetLoweringBase::finalizeLowering(MF); 10640 } 10641 10642 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10643 KnownBits &Known, 10644 const APInt &DemandedElts, 10645 const SelectionDAG &DAG, 10646 unsigned Depth) const { 10647 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10648 DAG, Depth); 10649 10650 // Set the high bits to zero based on the maximum allowed scratch size per 10651 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10652 // calculation won't overflow, so assume the sign bit is never set. 10653 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10654 } 10655 10656 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10657 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10658 const Align CacheLineAlign = Align(64); 10659 10660 // Pre-GFX10 target did not benefit from loop alignment 10661 if (!ML || DisableLoopAlignment || 10662 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10663 getSubtarget()->hasInstFwdPrefetchBug()) 10664 return PrefAlign; 10665 10666 // On GFX10 I$ is 4 x 64 bytes cache lines. 10667 // By default prefetcher keeps one cache line behind and reads two ahead. 10668 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10669 // behind and one ahead. 10670 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10671 // If loop fits 64 bytes it always spans no more than two cache lines and 10672 // does not need an alignment. 10673 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10674 // Else if loop is less or equal 192 bytes we need two lines behind. 10675 10676 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10677 const MachineBasicBlock *Header = ML->getHeader(); 10678 if (Header->getAlignment() != PrefAlign) 10679 return Header->getAlignment(); // Already processed. 10680 10681 unsigned LoopSize = 0; 10682 for (const MachineBasicBlock *MBB : ML->blocks()) { 10683 // If inner loop block is aligned assume in average half of the alignment 10684 // size to be added as nops. 10685 if (MBB != Header) 10686 LoopSize += MBB->getAlignment().value() / 2; 10687 10688 for (const MachineInstr &MI : *MBB) { 10689 LoopSize += TII->getInstSizeInBytes(MI); 10690 if (LoopSize > 192) 10691 return PrefAlign; 10692 } 10693 } 10694 10695 if (LoopSize <= 64) 10696 return PrefAlign; 10697 10698 if (LoopSize <= 128) 10699 return CacheLineAlign; 10700 10701 // If any of parent loops is surrounded by prefetch instructions do not 10702 // insert new for inner loop, which would reset parent's settings. 10703 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10704 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10705 auto I = Exit->getFirstNonDebugInstr(); 10706 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10707 return CacheLineAlign; 10708 } 10709 } 10710 10711 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10712 MachineBasicBlock *Exit = ML->getExitBlock(); 10713 10714 if (Pre && Exit) { 10715 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10716 TII->get(AMDGPU::S_INST_PREFETCH)) 10717 .addImm(1); // prefetch 2 lines behind PC 10718 10719 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10720 TII->get(AMDGPU::S_INST_PREFETCH)) 10721 .addImm(2); // prefetch 1 line behind PC 10722 } 10723 10724 return CacheLineAlign; 10725 } 10726 10727 LLVM_ATTRIBUTE_UNUSED 10728 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10729 assert(N->getOpcode() == ISD::CopyFromReg); 10730 do { 10731 // Follow the chain until we find an INLINEASM node. 10732 N = N->getOperand(0).getNode(); 10733 if (N->getOpcode() == ISD::INLINEASM || 10734 N->getOpcode() == ISD::INLINEASM_BR) 10735 return true; 10736 } while (N->getOpcode() == ISD::CopyFromReg); 10737 return false; 10738 } 10739 10740 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10741 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10742 { 10743 switch (N->getOpcode()) { 10744 case ISD::CopyFromReg: 10745 { 10746 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10747 const MachineFunction * MF = FLI->MF; 10748 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10749 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10750 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10751 unsigned Reg = R->getReg(); 10752 if (Register::isPhysicalRegister(Reg)) 10753 return !TRI.isSGPRReg(MRI, Reg); 10754 10755 if (MRI.isLiveIn(Reg)) { 10756 // workitem.id.x workitem.id.y workitem.id.z 10757 // Any VGPR formal argument is also considered divergent 10758 if (!TRI.isSGPRReg(MRI, Reg)) 10759 return true; 10760 // Formal arguments of non-entry functions 10761 // are conservatively considered divergent 10762 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10763 return true; 10764 return false; 10765 } 10766 const Value *V = FLI->getValueFromVirtualReg(Reg); 10767 if (V) 10768 return KDA->isDivergent(V); 10769 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10770 return !TRI.isSGPRReg(MRI, Reg); 10771 } 10772 break; 10773 case ISD::LOAD: { 10774 const LoadSDNode *L = cast<LoadSDNode>(N); 10775 unsigned AS = L->getAddressSpace(); 10776 // A flat load may access private memory. 10777 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10778 } break; 10779 case ISD::CALLSEQ_END: 10780 return true; 10781 break; 10782 case ISD::INTRINSIC_WO_CHAIN: 10783 { 10784 10785 } 10786 return AMDGPU::isIntrinsicSourceOfDivergence( 10787 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10788 case ISD::INTRINSIC_W_CHAIN: 10789 return AMDGPU::isIntrinsicSourceOfDivergence( 10790 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10791 } 10792 return false; 10793 } 10794 10795 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10796 EVT VT) const { 10797 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10798 case MVT::f32: 10799 return hasFP32Denormals(DAG.getMachineFunction()); 10800 case MVT::f64: 10801 case MVT::f16: 10802 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10803 default: 10804 return false; 10805 } 10806 } 10807 10808 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10809 const SelectionDAG &DAG, 10810 bool SNaN, 10811 unsigned Depth) const { 10812 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10813 const MachineFunction &MF = DAG.getMachineFunction(); 10814 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10815 10816 if (Info->getMode().DX10Clamp) 10817 return true; // Clamped to 0. 10818 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10819 } 10820 10821 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10822 SNaN, Depth); 10823 } 10824 10825 TargetLowering::AtomicExpansionKind 10826 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10827 switch (RMW->getOperation()) { 10828 case AtomicRMWInst::FAdd: { 10829 Type *Ty = RMW->getType(); 10830 10831 // We don't have a way to support 16-bit atomics now, so just leave them 10832 // as-is. 10833 if (Ty->isHalfTy()) 10834 return AtomicExpansionKind::None; 10835 10836 if (!Ty->isFloatTy()) 10837 return AtomicExpansionKind::CmpXChg; 10838 10839 // TODO: Do have these for flat. Older targets also had them for buffers. 10840 unsigned AS = RMW->getPointerAddressSpace(); 10841 10842 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10843 return RMW->use_empty() ? AtomicExpansionKind::None : 10844 AtomicExpansionKind::CmpXChg; 10845 } 10846 10847 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10848 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10849 } 10850 default: 10851 break; 10852 } 10853 10854 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10855 } 10856 10857 const TargetRegisterClass * 10858 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10859 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10860 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10861 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10862 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10863 : &AMDGPU::SReg_32RegClass; 10864 if (!TRI->isSGPRClass(RC) && !isDivergent) 10865 return TRI->getEquivalentSGPRClass(RC); 10866 else if (TRI->isSGPRClass(RC) && isDivergent) 10867 return TRI->getEquivalentVGPRClass(RC); 10868 10869 return RC; 10870 } 10871 10872 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 10873 unsigned WaveSize) { 10874 // FIXME: We asssume we never cast the mask results of a control flow 10875 // intrinsic. 10876 // Early exit if the type won't be consistent as a compile time hack. 10877 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 10878 if (!IT || IT->getBitWidth() != WaveSize) 10879 return false; 10880 10881 if (!isa<Instruction>(V)) 10882 return false; 10883 if (!Visited.insert(V).second) 10884 return false; 10885 bool Result = false; 10886 for (auto U : V->users()) { 10887 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10888 if (V == U->getOperand(1)) { 10889 switch (Intrinsic->getIntrinsicID()) { 10890 default: 10891 Result = false; 10892 break; 10893 case Intrinsic::amdgcn_if_break: 10894 case Intrinsic::amdgcn_if: 10895 case Intrinsic::amdgcn_else: 10896 Result = true; 10897 break; 10898 } 10899 } 10900 if (V == U->getOperand(0)) { 10901 switch (Intrinsic->getIntrinsicID()) { 10902 default: 10903 Result = false; 10904 break; 10905 case Intrinsic::amdgcn_end_cf: 10906 case Intrinsic::amdgcn_loop: 10907 Result = true; 10908 break; 10909 } 10910 } 10911 } else { 10912 Result = hasCFUser(U, Visited, WaveSize); 10913 } 10914 if (Result) 10915 break; 10916 } 10917 return Result; 10918 } 10919 10920 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 10921 const Value *V) const { 10922 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 10923 switch (Intrinsic->getIntrinsicID()) { 10924 default: 10925 return false; 10926 case Intrinsic::amdgcn_if_break: 10927 return true; 10928 } 10929 } 10930 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 10931 if (const IntrinsicInst *Intrinsic = 10932 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 10933 switch (Intrinsic->getIntrinsicID()) { 10934 default: 10935 return false; 10936 case Intrinsic::amdgcn_if: 10937 case Intrinsic::amdgcn_else: { 10938 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 10939 if (Indices.size() == 1 && Indices[0] == 1) { 10940 return true; 10941 } 10942 } 10943 } 10944 } 10945 } 10946 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 10947 if (isa<InlineAsm>(CI->getCalledValue())) { 10948 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 10949 ImmutableCallSite CS(CI); 10950 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 10951 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 10952 for (auto &TC : TargetConstraints) { 10953 if (TC.Type == InlineAsm::isOutput) { 10954 ComputeConstraintToUse(TC, SDValue()); 10955 unsigned AssignedReg; 10956 const TargetRegisterClass *RC; 10957 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 10958 SIRI, TC.ConstraintCode, TC.ConstraintVT); 10959 if (RC) { 10960 MachineRegisterInfo &MRI = MF.getRegInfo(); 10961 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 10962 return true; 10963 else if (SIRI->isSGPRClass(RC)) 10964 return true; 10965 } 10966 } 10967 } 10968 } 10969 } 10970 SmallPtrSet<const Value *, 16> Visited; 10971 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 10972 } 10973