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 cl::opt<bool> VGPRReserveforSGPRSpill( 99 "amdgpu-reserve-vgpr-for-sgpr-spill", 100 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 101 102 static bool hasFP32Denormals(const MachineFunction &MF) { 103 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 104 return Info->getMode().allFP32Denormals(); 105 } 106 107 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 108 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 109 return Info->getMode().allFP64FP16Denormals(); 110 } 111 112 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 113 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 114 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 115 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 116 return AMDGPU::SGPR0 + Reg; 117 } 118 } 119 llvm_unreachable("Cannot allocate sgpr"); 120 } 121 122 SITargetLowering::SITargetLowering(const TargetMachine &TM, 123 const GCNSubtarget &STI) 124 : AMDGPUTargetLowering(TM, STI), 125 Subtarget(&STI) { 126 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 127 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 128 129 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 130 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 131 132 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 133 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 134 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 135 136 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 137 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 138 139 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 140 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 141 142 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 143 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 144 145 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 146 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 147 148 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 149 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 150 151 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 152 addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass); 153 154 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 155 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 156 157 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 158 addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass); 159 160 if (Subtarget->has16BitInsts()) { 161 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 162 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 163 164 // Unless there are also VOP3P operations, not operations are really legal. 165 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 166 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 167 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 168 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 169 } 170 171 if (Subtarget->hasMAIInsts()) { 172 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 173 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 174 } 175 176 computeRegisterProperties(Subtarget->getRegisterInfo()); 177 178 // The boolean content concept here is too inflexible. Compares only ever 179 // really produce a 1-bit result. Any copy/extend from these will turn into a 180 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 181 // it's what most targets use. 182 setBooleanContents(ZeroOrOneBooleanContent); 183 setBooleanVectorContents(ZeroOrOneBooleanContent); 184 185 // We need to custom lower vector stores from local memory 186 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 187 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 188 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 189 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 190 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 191 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 192 setOperationAction(ISD::LOAD, MVT::i1, Custom); 193 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 194 195 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 196 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 197 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 198 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 199 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 200 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 201 setOperationAction(ISD::STORE, MVT::i1, Custom); 202 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 203 204 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 205 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 206 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 207 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 208 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 209 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 210 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 211 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 212 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 213 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 214 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 215 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 216 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 217 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 218 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 219 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 220 221 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 222 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 223 224 setOperationAction(ISD::SELECT, MVT::i1, Promote); 225 setOperationAction(ISD::SELECT, MVT::i64, Custom); 226 setOperationAction(ISD::SELECT, MVT::f64, Promote); 227 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 228 229 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 230 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 231 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 232 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 233 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 234 235 setOperationAction(ISD::SETCC, MVT::i1, Promote); 236 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 237 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 238 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 239 240 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 241 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 242 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 243 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 244 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 245 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 246 247 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 248 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 249 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 250 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 251 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 252 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 253 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 254 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 255 256 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 257 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 258 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 259 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 260 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 261 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 262 263 setOperationAction(ISD::UADDO, MVT::i32, Legal); 264 setOperationAction(ISD::USUBO, MVT::i32, Legal); 265 266 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 267 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 268 269 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 270 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 271 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 272 273 #if 0 274 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 275 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 276 #endif 277 278 // We only support LOAD/STORE and vector manipulation ops for vectors 279 // with > 4 elements. 280 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 281 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 282 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 283 MVT::v32i32, MVT::v32f32 }) { 284 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 285 switch (Op) { 286 case ISD::LOAD: 287 case ISD::STORE: 288 case ISD::BUILD_VECTOR: 289 case ISD::BITCAST: 290 case ISD::EXTRACT_VECTOR_ELT: 291 case ISD::INSERT_VECTOR_ELT: 292 case ISD::INSERT_SUBVECTOR: 293 case ISD::EXTRACT_SUBVECTOR: 294 case ISD::SCALAR_TO_VECTOR: 295 break; 296 case ISD::CONCAT_VECTORS: 297 setOperationAction(Op, VT, Custom); 298 break; 299 default: 300 setOperationAction(Op, VT, Expand); 301 break; 302 } 303 } 304 } 305 306 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 307 308 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 309 // is expanded to avoid having two separate loops in case the index is a VGPR. 310 311 // Most operations are naturally 32-bit vector operations. We only support 312 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 313 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 314 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 315 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 316 317 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 318 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 319 320 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 321 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 322 323 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 324 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 325 } 326 327 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 328 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 329 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 330 331 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 332 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 333 334 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 335 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 336 337 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 338 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 339 } 340 341 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 342 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 343 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 344 345 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 346 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 347 348 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 349 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 350 351 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 352 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 353 } 354 355 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 356 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 357 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 358 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 359 360 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 361 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 362 363 // Avoid stack access for these. 364 // TODO: Generalize to more vector types. 365 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 366 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 367 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 368 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 369 370 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 371 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 372 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 373 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 374 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 375 376 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 377 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 378 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 379 380 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 381 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 382 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 383 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 384 385 // Deal with vec3 vector operations when widened to vec4. 386 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 387 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 388 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 389 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 390 391 // Deal with vec5 vector operations when widened to vec8. 392 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 393 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 394 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 395 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 396 397 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 398 // and output demarshalling 399 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 400 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 401 402 // We can't return success/failure, only the old value, 403 // let LLVM add the comparison 404 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 405 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 406 407 if (Subtarget->hasFlatAddressSpace()) { 408 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 409 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 410 } 411 412 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 413 414 // FIXME: This should be narrowed to i32, but that only happens if i64 is 415 // illegal. 416 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 417 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 418 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 419 420 // On SI this is s_memtime and s_memrealtime on VI. 421 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 422 setOperationAction(ISD::TRAP, MVT::Other, Custom); 423 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 424 425 if (Subtarget->has16BitInsts()) { 426 setOperationAction(ISD::FPOW, MVT::f16, Promote); 427 setOperationAction(ISD::FLOG, MVT::f16, Custom); 428 setOperationAction(ISD::FEXP, MVT::f16, Custom); 429 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 430 } 431 432 // v_mad_f32 does not support denormals. We report it as unconditionally 433 // legal, and the context where it is formed will disallow it when fp32 434 // denormals are enabled. 435 setOperationAction(ISD::FMAD, MVT::f32, Legal); 436 437 if (!Subtarget->hasBFI()) { 438 // fcopysign can be done in a single instruction with BFI. 439 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 440 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 441 } 442 443 if (!Subtarget->hasBCNT(32)) 444 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 445 446 if (!Subtarget->hasBCNT(64)) 447 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 448 449 if (Subtarget->hasFFBH()) 450 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 451 452 if (Subtarget->hasFFBL()) 453 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 454 455 // We only really have 32-bit BFE instructions (and 16-bit on VI). 456 // 457 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 458 // effort to match them now. We want this to be false for i64 cases when the 459 // extraction isn't restricted to the upper or lower half. Ideally we would 460 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 461 // span the midpoint are probably relatively rare, so don't worry about them 462 // for now. 463 if (Subtarget->hasBFE()) 464 setHasExtractBitsInsn(true); 465 466 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 467 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 468 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 469 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 470 471 472 // These are really only legal for ieee_mode functions. We should be avoiding 473 // them for functions that don't have ieee_mode enabled, so just say they are 474 // legal. 475 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 476 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 477 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 478 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 479 480 481 if (Subtarget->haveRoundOpsF64()) { 482 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 483 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 484 setOperationAction(ISD::FRINT, MVT::f64, Legal); 485 } else { 486 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 487 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 488 setOperationAction(ISD::FRINT, MVT::f64, Custom); 489 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 490 } 491 492 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 493 494 setOperationAction(ISD::FSIN, MVT::f32, Custom); 495 setOperationAction(ISD::FCOS, MVT::f32, Custom); 496 setOperationAction(ISD::FDIV, MVT::f32, Custom); 497 setOperationAction(ISD::FDIV, MVT::f64, Custom); 498 499 if (Subtarget->has16BitInsts()) { 500 setOperationAction(ISD::Constant, MVT::i16, Legal); 501 502 setOperationAction(ISD::SMIN, MVT::i16, Legal); 503 setOperationAction(ISD::SMAX, MVT::i16, Legal); 504 505 setOperationAction(ISD::UMIN, MVT::i16, Legal); 506 setOperationAction(ISD::UMAX, MVT::i16, Legal); 507 508 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 509 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 510 511 setOperationAction(ISD::ROTR, MVT::i16, Promote); 512 setOperationAction(ISD::ROTL, MVT::i16, Promote); 513 514 setOperationAction(ISD::SDIV, MVT::i16, Promote); 515 setOperationAction(ISD::UDIV, MVT::i16, Promote); 516 setOperationAction(ISD::SREM, MVT::i16, Promote); 517 setOperationAction(ISD::UREM, MVT::i16, Promote); 518 519 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 520 521 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 522 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 523 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 524 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 525 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 526 527 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 528 529 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 530 531 setOperationAction(ISD::LOAD, MVT::i16, Custom); 532 533 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 534 535 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 536 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 537 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 538 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 539 540 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 541 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 542 543 // F16 - Constant Actions. 544 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 545 546 // F16 - Load/Store Actions. 547 setOperationAction(ISD::LOAD, MVT::f16, Promote); 548 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 549 setOperationAction(ISD::STORE, MVT::f16, Promote); 550 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 551 552 // F16 - VOP1 Actions. 553 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 554 setOperationAction(ISD::FCOS, MVT::f16, Custom); 555 setOperationAction(ISD::FSIN, MVT::f16, Custom); 556 557 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 558 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 559 560 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 561 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 562 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 563 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 564 setOperationAction(ISD::FROUND, MVT::f16, Custom); 565 566 // F16 - VOP2 Actions. 567 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 568 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 569 570 setOperationAction(ISD::FDIV, MVT::f16, Custom); 571 572 // F16 - VOP3 Actions. 573 setOperationAction(ISD::FMA, MVT::f16, Legal); 574 if (STI.hasMadF16()) 575 setOperationAction(ISD::FMAD, MVT::f16, Legal); 576 577 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 578 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 579 switch (Op) { 580 case ISD::LOAD: 581 case ISD::STORE: 582 case ISD::BUILD_VECTOR: 583 case ISD::BITCAST: 584 case ISD::EXTRACT_VECTOR_ELT: 585 case ISD::INSERT_VECTOR_ELT: 586 case ISD::INSERT_SUBVECTOR: 587 case ISD::EXTRACT_SUBVECTOR: 588 case ISD::SCALAR_TO_VECTOR: 589 break; 590 case ISD::CONCAT_VECTORS: 591 setOperationAction(Op, VT, Custom); 592 break; 593 default: 594 setOperationAction(Op, VT, Expand); 595 break; 596 } 597 } 598 } 599 600 // v_perm_b32 can handle either of these. 601 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 602 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 603 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 604 605 // XXX - Do these do anything? Vector constants turn into build_vector. 606 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 607 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 608 609 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 610 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 611 612 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 613 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 614 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 615 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 616 617 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 618 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 619 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 620 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 621 622 setOperationAction(ISD::AND, MVT::v2i16, Promote); 623 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 624 setOperationAction(ISD::OR, MVT::v2i16, Promote); 625 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 626 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 627 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 628 629 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 630 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 631 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 632 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 633 634 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 635 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 636 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 637 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 638 639 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 640 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 641 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 642 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 643 644 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 645 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 646 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 647 648 if (!Subtarget->hasVOP3PInsts()) { 649 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 650 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 651 } 652 653 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 654 // This isn't really legal, but this avoids the legalizer unrolling it (and 655 // allows matching fneg (fabs x) patterns) 656 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 657 658 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 659 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 660 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 661 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 662 663 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 664 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 665 666 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 667 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 668 } 669 670 if (Subtarget->hasVOP3PInsts()) { 671 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 672 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 673 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 674 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 675 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 676 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 677 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 678 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 679 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 680 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 681 682 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 683 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 684 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 685 686 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 687 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 688 689 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 690 691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 692 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 693 694 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 695 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 696 697 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 698 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 699 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 700 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 701 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 702 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 703 704 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 705 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 706 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 707 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 708 709 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 710 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 711 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 712 713 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 714 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 715 716 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 717 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 718 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 719 720 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 721 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 722 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 723 } 724 725 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 726 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 727 728 if (Subtarget->has16BitInsts()) { 729 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 730 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 731 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 732 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 733 } else { 734 // Legalization hack. 735 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 736 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 737 738 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 739 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 740 } 741 742 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 743 setOperationAction(ISD::SELECT, VT, Custom); 744 } 745 746 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 747 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 748 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 749 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 750 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 751 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 752 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 753 754 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 755 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 756 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 757 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 758 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 759 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 760 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 761 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 762 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 763 764 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 765 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 766 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 767 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 768 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 769 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 770 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 771 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 772 773 setTargetDAGCombine(ISD::ADD); 774 setTargetDAGCombine(ISD::ADDCARRY); 775 setTargetDAGCombine(ISD::SUB); 776 setTargetDAGCombine(ISD::SUBCARRY); 777 setTargetDAGCombine(ISD::FADD); 778 setTargetDAGCombine(ISD::FSUB); 779 setTargetDAGCombine(ISD::FMINNUM); 780 setTargetDAGCombine(ISD::FMAXNUM); 781 setTargetDAGCombine(ISD::FMINNUM_IEEE); 782 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 783 setTargetDAGCombine(ISD::FMA); 784 setTargetDAGCombine(ISD::SMIN); 785 setTargetDAGCombine(ISD::SMAX); 786 setTargetDAGCombine(ISD::UMIN); 787 setTargetDAGCombine(ISD::UMAX); 788 setTargetDAGCombine(ISD::SETCC); 789 setTargetDAGCombine(ISD::AND); 790 setTargetDAGCombine(ISD::OR); 791 setTargetDAGCombine(ISD::XOR); 792 setTargetDAGCombine(ISD::SINT_TO_FP); 793 setTargetDAGCombine(ISD::UINT_TO_FP); 794 setTargetDAGCombine(ISD::FCANONICALIZE); 795 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 796 setTargetDAGCombine(ISD::ZERO_EXTEND); 797 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 798 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 799 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 800 801 // All memory operations. Some folding on the pointer operand is done to help 802 // matching the constant offsets in the addressing modes. 803 setTargetDAGCombine(ISD::LOAD); 804 setTargetDAGCombine(ISD::STORE); 805 setTargetDAGCombine(ISD::ATOMIC_LOAD); 806 setTargetDAGCombine(ISD::ATOMIC_STORE); 807 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 808 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 809 setTargetDAGCombine(ISD::ATOMIC_SWAP); 810 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 811 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 812 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 813 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 814 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 815 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 816 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 817 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 818 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 819 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 820 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 821 822 setSchedulingPreference(Sched::RegPressure); 823 } 824 825 const GCNSubtarget *SITargetLowering::getSubtarget() const { 826 return Subtarget; 827 } 828 829 //===----------------------------------------------------------------------===// 830 // TargetLowering queries 831 //===----------------------------------------------------------------------===// 832 833 // v_mad_mix* support a conversion from f16 to f32. 834 // 835 // There is only one special case when denormals are enabled we don't currently, 836 // where this is OK to use. 837 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 838 EVT DestVT, EVT SrcVT) const { 839 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 840 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 841 DestVT.getScalarType() == MVT::f32 && 842 SrcVT.getScalarType() == MVT::f16 && 843 // TODO: This probably only requires no input flushing? 844 !hasFP32Denormals(DAG.getMachineFunction()); 845 } 846 847 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 848 // SI has some legal vector types, but no legal vector operations. Say no 849 // shuffles are legal in order to prefer scalarizing some vector operations. 850 return false; 851 } 852 853 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 854 CallingConv::ID CC, 855 EVT VT) const { 856 if (CC == CallingConv::AMDGPU_KERNEL) 857 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 858 859 if (VT.isVector()) { 860 EVT ScalarVT = VT.getScalarType(); 861 unsigned Size = ScalarVT.getSizeInBits(); 862 if (Size == 32) 863 return ScalarVT.getSimpleVT(); 864 865 if (Size > 32) 866 return MVT::i32; 867 868 if (Size == 16 && Subtarget->has16BitInsts()) 869 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 870 } else if (VT.getSizeInBits() > 32) 871 return MVT::i32; 872 873 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 874 } 875 876 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 877 CallingConv::ID CC, 878 EVT VT) const { 879 if (CC == CallingConv::AMDGPU_KERNEL) 880 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 881 882 if (VT.isVector()) { 883 unsigned NumElts = VT.getVectorNumElements(); 884 EVT ScalarVT = VT.getScalarType(); 885 unsigned Size = ScalarVT.getSizeInBits(); 886 887 if (Size == 32) 888 return NumElts; 889 890 if (Size > 32) 891 return NumElts * ((Size + 31) / 32); 892 893 if (Size == 16 && Subtarget->has16BitInsts()) 894 return (NumElts + 1) / 2; 895 } else if (VT.getSizeInBits() > 32) 896 return (VT.getSizeInBits() + 31) / 32; 897 898 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 899 } 900 901 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 902 LLVMContext &Context, CallingConv::ID CC, 903 EVT VT, EVT &IntermediateVT, 904 unsigned &NumIntermediates, MVT &RegisterVT) const { 905 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 906 unsigned NumElts = VT.getVectorNumElements(); 907 EVT ScalarVT = VT.getScalarType(); 908 unsigned Size = ScalarVT.getSizeInBits(); 909 if (Size == 32) { 910 RegisterVT = ScalarVT.getSimpleVT(); 911 IntermediateVT = RegisterVT; 912 NumIntermediates = NumElts; 913 return NumIntermediates; 914 } 915 916 if (Size > 32) { 917 RegisterVT = MVT::i32; 918 IntermediateVT = RegisterVT; 919 NumIntermediates = NumElts * ((Size + 31) / 32); 920 return NumIntermediates; 921 } 922 923 // FIXME: We should fix the ABI to be the same on targets without 16-bit 924 // support, but unless we can properly handle 3-vectors, it will be still be 925 // inconsistent. 926 if (Size == 16 && Subtarget->has16BitInsts()) { 927 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 928 IntermediateVT = RegisterVT; 929 NumIntermediates = (NumElts + 1) / 2; 930 return NumIntermediates; 931 } 932 } 933 934 return TargetLowering::getVectorTypeBreakdownForCallingConv( 935 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 936 } 937 938 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 939 assert(DMaskLanes != 0); 940 941 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 942 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 943 return EVT::getVectorVT(Ty->getContext(), 944 EVT::getEVT(VT->getElementType()), 945 NumElts); 946 } 947 948 return EVT::getEVT(Ty); 949 } 950 951 // Peek through TFE struct returns to only use the data size. 952 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 953 auto *ST = dyn_cast<StructType>(Ty); 954 if (!ST) 955 return memVTFromImageData(Ty, DMaskLanes); 956 957 // Some intrinsics return an aggregate type - special case to work out the 958 // correct memVT. 959 // 960 // Only limited forms of aggregate type currently expected. 961 if (ST->getNumContainedTypes() != 2 || 962 !ST->getContainedType(1)->isIntegerTy(32)) 963 return EVT(); 964 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 965 } 966 967 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 968 const CallInst &CI, 969 MachineFunction &MF, 970 unsigned IntrID) const { 971 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 972 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 973 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 974 (Intrinsic::ID)IntrID); 975 if (Attr.hasFnAttribute(Attribute::ReadNone)) 976 return false; 977 978 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 979 980 if (RsrcIntr->IsImage) { 981 Info.ptrVal = MFI->getImagePSV( 982 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 983 CI.getArgOperand(RsrcIntr->RsrcArg)); 984 Info.align.reset(); 985 } else { 986 Info.ptrVal = MFI->getBufferPSV( 987 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 988 CI.getArgOperand(RsrcIntr->RsrcArg)); 989 } 990 991 Info.flags = MachineMemOperand::MODereferenceable; 992 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 993 unsigned DMaskLanes = 4; 994 995 if (RsrcIntr->IsImage) { 996 const AMDGPU::ImageDimIntrinsicInfo *Intr 997 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 998 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 999 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1000 1001 if (!BaseOpcode->Gather4) { 1002 // If this isn't a gather, we may have excess loaded elements in the 1003 // IR type. Check the dmask for the real number of elements loaded. 1004 unsigned DMask 1005 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1006 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1007 } 1008 1009 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1010 } else 1011 Info.memVT = EVT::getEVT(CI.getType()); 1012 1013 // FIXME: What does alignment mean for an image? 1014 Info.opc = ISD::INTRINSIC_W_CHAIN; 1015 Info.flags |= MachineMemOperand::MOLoad; 1016 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1017 Info.opc = ISD::INTRINSIC_VOID; 1018 1019 Type *DataTy = CI.getArgOperand(0)->getType(); 1020 if (RsrcIntr->IsImage) { 1021 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1022 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1023 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1024 } else 1025 Info.memVT = EVT::getEVT(DataTy); 1026 1027 Info.flags |= MachineMemOperand::MOStore; 1028 } else { 1029 // Atomic 1030 Info.opc = ISD::INTRINSIC_W_CHAIN; 1031 Info.memVT = MVT::getVT(CI.getType()); 1032 Info.flags = MachineMemOperand::MOLoad | 1033 MachineMemOperand::MOStore | 1034 MachineMemOperand::MODereferenceable; 1035 1036 // XXX - Should this be volatile without known ordering? 1037 Info.flags |= MachineMemOperand::MOVolatile; 1038 } 1039 return true; 1040 } 1041 1042 switch (IntrID) { 1043 case Intrinsic::amdgcn_atomic_inc: 1044 case Intrinsic::amdgcn_atomic_dec: 1045 case Intrinsic::amdgcn_ds_ordered_add: 1046 case Intrinsic::amdgcn_ds_ordered_swap: 1047 case Intrinsic::amdgcn_ds_fadd: 1048 case Intrinsic::amdgcn_ds_fmin: 1049 case Intrinsic::amdgcn_ds_fmax: { 1050 Info.opc = ISD::INTRINSIC_W_CHAIN; 1051 Info.memVT = MVT::getVT(CI.getType()); 1052 Info.ptrVal = CI.getOperand(0); 1053 Info.align.reset(); 1054 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1055 1056 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1057 if (!Vol->isZero()) 1058 Info.flags |= MachineMemOperand::MOVolatile; 1059 1060 return true; 1061 } 1062 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1063 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1064 1065 Info.opc = ISD::INTRINSIC_VOID; 1066 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1067 Info.ptrVal = MFI->getBufferPSV( 1068 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1069 CI.getArgOperand(1)); 1070 Info.align.reset(); 1071 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1072 1073 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1074 if (!Vol || !Vol->isZero()) 1075 Info.flags |= MachineMemOperand::MOVolatile; 1076 1077 return true; 1078 } 1079 case Intrinsic::amdgcn_global_atomic_fadd: { 1080 Info.opc = ISD::INTRINSIC_VOID; 1081 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1082 ->getPointerElementType()); 1083 Info.ptrVal = CI.getOperand(0); 1084 Info.align.reset(); 1085 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1086 1087 return true; 1088 } 1089 case Intrinsic::amdgcn_ds_append: 1090 case Intrinsic::amdgcn_ds_consume: { 1091 Info.opc = ISD::INTRINSIC_W_CHAIN; 1092 Info.memVT = MVT::getVT(CI.getType()); 1093 Info.ptrVal = CI.getOperand(0); 1094 Info.align.reset(); 1095 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1096 1097 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1098 if (!Vol->isZero()) 1099 Info.flags |= MachineMemOperand::MOVolatile; 1100 1101 return true; 1102 } 1103 case Intrinsic::amdgcn_ds_gws_init: 1104 case Intrinsic::amdgcn_ds_gws_barrier: 1105 case Intrinsic::amdgcn_ds_gws_sema_v: 1106 case Intrinsic::amdgcn_ds_gws_sema_br: 1107 case Intrinsic::amdgcn_ds_gws_sema_p: 1108 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1109 Info.opc = ISD::INTRINSIC_VOID; 1110 1111 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1112 Info.ptrVal = 1113 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1114 1115 // This is an abstract access, but we need to specify a type and size. 1116 Info.memVT = MVT::i32; 1117 Info.size = 4; 1118 Info.align = Align(4); 1119 1120 Info.flags = MachineMemOperand::MOStore; 1121 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1122 Info.flags = MachineMemOperand::MOLoad; 1123 return true; 1124 } 1125 default: 1126 return false; 1127 } 1128 } 1129 1130 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1131 SmallVectorImpl<Value*> &Ops, 1132 Type *&AccessTy) const { 1133 switch (II->getIntrinsicID()) { 1134 case Intrinsic::amdgcn_atomic_inc: 1135 case Intrinsic::amdgcn_atomic_dec: 1136 case Intrinsic::amdgcn_ds_ordered_add: 1137 case Intrinsic::amdgcn_ds_ordered_swap: 1138 case Intrinsic::amdgcn_ds_fadd: 1139 case Intrinsic::amdgcn_ds_fmin: 1140 case Intrinsic::amdgcn_ds_fmax: { 1141 Value *Ptr = II->getArgOperand(0); 1142 AccessTy = II->getType(); 1143 Ops.push_back(Ptr); 1144 return true; 1145 } 1146 default: 1147 return false; 1148 } 1149 } 1150 1151 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1152 if (!Subtarget->hasFlatInstOffsets()) { 1153 // Flat instructions do not have offsets, and only have the register 1154 // address. 1155 return AM.BaseOffs == 0 && AM.Scale == 0; 1156 } 1157 1158 return AM.Scale == 0 && 1159 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1160 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1161 /*Signed=*/false)); 1162 } 1163 1164 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1165 if (Subtarget->hasFlatGlobalInsts()) 1166 return AM.Scale == 0 && 1167 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1168 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1169 /*Signed=*/true)); 1170 1171 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1172 // Assume the we will use FLAT for all global memory accesses 1173 // on VI. 1174 // FIXME: This assumption is currently wrong. On VI we still use 1175 // MUBUF instructions for the r + i addressing mode. As currently 1176 // implemented, the MUBUF instructions only work on buffer < 4GB. 1177 // It may be possible to support > 4GB buffers with MUBUF instructions, 1178 // by setting the stride value in the resource descriptor which would 1179 // increase the size limit to (stride * 4GB). However, this is risky, 1180 // because it has never been validated. 1181 return isLegalFlatAddressingMode(AM); 1182 } 1183 1184 return isLegalMUBUFAddressingMode(AM); 1185 } 1186 1187 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1188 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1189 // additionally can do r + r + i with addr64. 32-bit has more addressing 1190 // mode options. Depending on the resource constant, it can also do 1191 // (i64 r0) + (i32 r1) * (i14 i). 1192 // 1193 // Private arrays end up using a scratch buffer most of the time, so also 1194 // assume those use MUBUF instructions. Scratch loads / stores are currently 1195 // implemented as mubuf instructions with offen bit set, so slightly 1196 // different than the normal addr64. 1197 if (!isUInt<12>(AM.BaseOffs)) 1198 return false; 1199 1200 // FIXME: Since we can split immediate into soffset and immediate offset, 1201 // would it make sense to allow any immediate? 1202 1203 switch (AM.Scale) { 1204 case 0: // r + i or just i, depending on HasBaseReg. 1205 return true; 1206 case 1: 1207 return true; // We have r + r or r + i. 1208 case 2: 1209 if (AM.HasBaseReg) { 1210 // Reject 2 * r + r. 1211 return false; 1212 } 1213 1214 // Allow 2 * r as r + r 1215 // Or 2 * r + i is allowed as r + r + i. 1216 return true; 1217 default: // Don't allow n * r 1218 return false; 1219 } 1220 } 1221 1222 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1223 const AddrMode &AM, Type *Ty, 1224 unsigned AS, Instruction *I) const { 1225 // No global is ever allowed as a base. 1226 if (AM.BaseGV) 1227 return false; 1228 1229 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1230 return isLegalGlobalAddressingMode(AM); 1231 1232 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1233 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1234 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1235 // If the offset isn't a multiple of 4, it probably isn't going to be 1236 // correctly aligned. 1237 // FIXME: Can we get the real alignment here? 1238 if (AM.BaseOffs % 4 != 0) 1239 return isLegalMUBUFAddressingMode(AM); 1240 1241 // There are no SMRD extloads, so if we have to do a small type access we 1242 // will use a MUBUF load. 1243 // FIXME?: We also need to do this if unaligned, but we don't know the 1244 // alignment here. 1245 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1246 return isLegalGlobalAddressingMode(AM); 1247 1248 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1249 // SMRD instructions have an 8-bit, dword offset on SI. 1250 if (!isUInt<8>(AM.BaseOffs / 4)) 1251 return false; 1252 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1253 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1254 // in 8-bits, it can use a smaller encoding. 1255 if (!isUInt<32>(AM.BaseOffs / 4)) 1256 return false; 1257 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1258 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1259 if (!isUInt<20>(AM.BaseOffs)) 1260 return false; 1261 } else 1262 llvm_unreachable("unhandled generation"); 1263 1264 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1265 return true; 1266 1267 if (AM.Scale == 1 && AM.HasBaseReg) 1268 return true; 1269 1270 return false; 1271 1272 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1273 return isLegalMUBUFAddressingMode(AM); 1274 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1275 AS == AMDGPUAS::REGION_ADDRESS) { 1276 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1277 // field. 1278 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1279 // an 8-bit dword offset but we don't know the alignment here. 1280 if (!isUInt<16>(AM.BaseOffs)) 1281 return false; 1282 1283 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1284 return true; 1285 1286 if (AM.Scale == 1 && AM.HasBaseReg) 1287 return true; 1288 1289 return false; 1290 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1291 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1292 // For an unknown address space, this usually means that this is for some 1293 // reason being used for pure arithmetic, and not based on some addressing 1294 // computation. We don't have instructions that compute pointers with any 1295 // addressing modes, so treat them as having no offset like flat 1296 // instructions. 1297 return isLegalFlatAddressingMode(AM); 1298 } 1299 1300 // Assume a user alias of global for unknown address spaces. 1301 return isLegalGlobalAddressingMode(AM); 1302 } 1303 1304 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1305 const SelectionDAG &DAG) const { 1306 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1307 return (MemVT.getSizeInBits() <= 4 * 32); 1308 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1309 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1310 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1311 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1312 return (MemVT.getSizeInBits() <= 2 * 32); 1313 } 1314 return true; 1315 } 1316 1317 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1318 unsigned Size, unsigned AddrSpace, unsigned Align, 1319 MachineMemOperand::Flags Flags, bool *IsFast) const { 1320 if (IsFast) 1321 *IsFast = false; 1322 1323 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1324 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1325 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1326 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1327 // with adjacent offsets. 1328 bool AlignedBy4 = (Align % 4 == 0); 1329 if (IsFast) 1330 *IsFast = AlignedBy4; 1331 1332 return AlignedBy4; 1333 } 1334 1335 // FIXME: We have to be conservative here and assume that flat operations 1336 // will access scratch. If we had access to the IR function, then we 1337 // could determine if any private memory was used in the function. 1338 if (!Subtarget->hasUnalignedScratchAccess() && 1339 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1340 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1341 bool AlignedBy4 = Align >= 4; 1342 if (IsFast) 1343 *IsFast = AlignedBy4; 1344 1345 return AlignedBy4; 1346 } 1347 1348 if (Subtarget->hasUnalignedBufferAccess()) { 1349 // If we have an uniform constant load, it still requires using a slow 1350 // buffer instruction if unaligned. 1351 if (IsFast) { 1352 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1353 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1354 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1355 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1356 Align >= 4 : Align != 2; 1357 } 1358 1359 return true; 1360 } 1361 1362 // Smaller than dword value must be aligned. 1363 if (Size < 32) 1364 return false; 1365 1366 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1367 // byte-address are ignored, thus forcing Dword alignment. 1368 // This applies to private, global, and constant memory. 1369 if (IsFast) 1370 *IsFast = true; 1371 1372 return Size >= 32 && Align >= 4; 1373 } 1374 1375 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1376 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1377 bool *IsFast) const { 1378 if (IsFast) 1379 *IsFast = false; 1380 1381 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1382 // which isn't a simple VT. 1383 // Until MVT is extended to handle this, simply check for the size and 1384 // rely on the condition below: allow accesses if the size is a multiple of 4. 1385 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1386 VT.getStoreSize() > 16)) { 1387 return false; 1388 } 1389 1390 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1391 Align, Flags, IsFast); 1392 } 1393 1394 EVT SITargetLowering::getOptimalMemOpType( 1395 const MemOp &Op, const AttributeList &FuncAttributes) const { 1396 // FIXME: Should account for address space here. 1397 1398 // The default fallback uses the private pointer size as a guess for a type to 1399 // use. Make sure we switch these to 64-bit accesses. 1400 1401 if (Op.size() >= 16 && 1402 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1403 return MVT::v4i32; 1404 1405 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1406 return MVT::v2i32; 1407 1408 // Use the default. 1409 return MVT::Other; 1410 } 1411 1412 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1413 unsigned DestAS) const { 1414 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1415 } 1416 1417 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1418 const MemSDNode *MemNode = cast<MemSDNode>(N); 1419 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1420 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1421 return I && I->getMetadata("amdgpu.noclobber"); 1422 } 1423 1424 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1425 unsigned DestAS) const { 1426 // Flat -> private/local is a simple truncate. 1427 // Flat -> global is no-op 1428 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1429 return true; 1430 1431 return isNoopAddrSpaceCast(SrcAS, DestAS); 1432 } 1433 1434 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1435 const MemSDNode *MemNode = cast<MemSDNode>(N); 1436 1437 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1438 } 1439 1440 TargetLoweringBase::LegalizeTypeAction 1441 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1442 int NumElts = VT.getVectorNumElements(); 1443 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1444 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1445 return TargetLoweringBase::getPreferredVectorAction(VT); 1446 } 1447 1448 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1449 Type *Ty) const { 1450 // FIXME: Could be smarter if called for vector constants. 1451 return true; 1452 } 1453 1454 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1455 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1456 switch (Op) { 1457 case ISD::LOAD: 1458 case ISD::STORE: 1459 1460 // These operations are done with 32-bit instructions anyway. 1461 case ISD::AND: 1462 case ISD::OR: 1463 case ISD::XOR: 1464 case ISD::SELECT: 1465 // TODO: Extensions? 1466 return true; 1467 default: 1468 return false; 1469 } 1470 } 1471 1472 // SimplifySetCC uses this function to determine whether or not it should 1473 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1474 if (VT == MVT::i1 && Op == ISD::SETCC) 1475 return false; 1476 1477 return TargetLowering::isTypeDesirableForOp(Op, VT); 1478 } 1479 1480 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1481 const SDLoc &SL, 1482 SDValue Chain, 1483 uint64_t Offset) const { 1484 const DataLayout &DL = DAG.getDataLayout(); 1485 MachineFunction &MF = DAG.getMachineFunction(); 1486 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1487 1488 const ArgDescriptor *InputPtrReg; 1489 const TargetRegisterClass *RC; 1490 1491 std::tie(InputPtrReg, RC) 1492 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1493 1494 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1495 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1496 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1497 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1498 1499 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1500 } 1501 1502 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1503 const SDLoc &SL) const { 1504 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1505 FIRST_IMPLICIT); 1506 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1507 } 1508 1509 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1510 const SDLoc &SL, SDValue Val, 1511 bool Signed, 1512 const ISD::InputArg *Arg) const { 1513 // First, if it is a widened vector, narrow it. 1514 if (VT.isVector() && 1515 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1516 EVT NarrowedVT = 1517 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1518 VT.getVectorNumElements()); 1519 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1520 DAG.getConstant(0, SL, MVT::i32)); 1521 } 1522 1523 // Then convert the vector elements or scalar value. 1524 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1525 VT.bitsLT(MemVT)) { 1526 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1527 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1528 } 1529 1530 if (MemVT.isFloatingPoint()) 1531 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1532 else if (Signed) 1533 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1534 else 1535 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1536 1537 return Val; 1538 } 1539 1540 SDValue SITargetLowering::lowerKernargMemParameter( 1541 SelectionDAG &DAG, EVT VT, EVT MemVT, 1542 const SDLoc &SL, SDValue Chain, 1543 uint64_t Offset, unsigned Align, bool Signed, 1544 const ISD::InputArg *Arg) const { 1545 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1546 1547 // Try to avoid using an extload by loading earlier than the argument address, 1548 // and extracting the relevant bits. The load should hopefully be merged with 1549 // the previous argument. 1550 if (MemVT.getStoreSize() < 4 && Align < 4) { 1551 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1552 int64_t AlignDownOffset = alignDown(Offset, 4); 1553 int64_t OffsetDiff = Offset - AlignDownOffset; 1554 1555 EVT IntVT = MemVT.changeTypeToInteger(); 1556 1557 // TODO: If we passed in the base kernel offset we could have a better 1558 // alignment than 4, but we don't really need it. 1559 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1560 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1561 MachineMemOperand::MODereferenceable | 1562 MachineMemOperand::MOInvariant); 1563 1564 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1565 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1566 1567 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1568 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1569 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1570 1571 1572 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1573 } 1574 1575 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1576 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1577 MachineMemOperand::MODereferenceable | 1578 MachineMemOperand::MOInvariant); 1579 1580 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1581 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1582 } 1583 1584 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1585 const SDLoc &SL, SDValue Chain, 1586 const ISD::InputArg &Arg) const { 1587 MachineFunction &MF = DAG.getMachineFunction(); 1588 MachineFrameInfo &MFI = MF.getFrameInfo(); 1589 1590 if (Arg.Flags.isByVal()) { 1591 unsigned Size = Arg.Flags.getByValSize(); 1592 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1593 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1594 } 1595 1596 unsigned ArgOffset = VA.getLocMemOffset(); 1597 unsigned ArgSize = VA.getValVT().getStoreSize(); 1598 1599 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1600 1601 // Create load nodes to retrieve arguments from the stack. 1602 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1603 SDValue ArgValue; 1604 1605 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1606 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1607 MVT MemVT = VA.getValVT(); 1608 1609 switch (VA.getLocInfo()) { 1610 default: 1611 break; 1612 case CCValAssign::BCvt: 1613 MemVT = VA.getLocVT(); 1614 break; 1615 case CCValAssign::SExt: 1616 ExtType = ISD::SEXTLOAD; 1617 break; 1618 case CCValAssign::ZExt: 1619 ExtType = ISD::ZEXTLOAD; 1620 break; 1621 case CCValAssign::AExt: 1622 ExtType = ISD::EXTLOAD; 1623 break; 1624 } 1625 1626 ArgValue = DAG.getExtLoad( 1627 ExtType, SL, VA.getLocVT(), Chain, FIN, 1628 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1629 MemVT); 1630 return ArgValue; 1631 } 1632 1633 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1634 const SIMachineFunctionInfo &MFI, 1635 EVT VT, 1636 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1637 const ArgDescriptor *Reg; 1638 const TargetRegisterClass *RC; 1639 1640 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1641 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1642 } 1643 1644 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1645 CallingConv::ID CallConv, 1646 ArrayRef<ISD::InputArg> Ins, 1647 BitVector &Skipped, 1648 FunctionType *FType, 1649 SIMachineFunctionInfo *Info) { 1650 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1651 const ISD::InputArg *Arg = &Ins[I]; 1652 1653 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1654 "vector type argument should have been split"); 1655 1656 // First check if it's a PS input addr. 1657 if (CallConv == CallingConv::AMDGPU_PS && 1658 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1659 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1660 1661 // Inconveniently only the first part of the split is marked as isSplit, 1662 // so skip to the end. We only want to increment PSInputNum once for the 1663 // entire split argument. 1664 if (Arg->Flags.isSplit()) { 1665 while (!Arg->Flags.isSplitEnd()) { 1666 assert((!Arg->VT.isVector() || 1667 Arg->VT.getScalarSizeInBits() == 16) && 1668 "unexpected vector split in ps argument type"); 1669 if (!SkipArg) 1670 Splits.push_back(*Arg); 1671 Arg = &Ins[++I]; 1672 } 1673 } 1674 1675 if (SkipArg) { 1676 // We can safely skip PS inputs. 1677 Skipped.set(Arg->getOrigArgIndex()); 1678 ++PSInputNum; 1679 continue; 1680 } 1681 1682 Info->markPSInputAllocated(PSInputNum); 1683 if (Arg->Used) 1684 Info->markPSInputEnabled(PSInputNum); 1685 1686 ++PSInputNum; 1687 } 1688 1689 Splits.push_back(*Arg); 1690 } 1691 } 1692 1693 // Allocate special inputs passed in VGPRs. 1694 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1695 MachineFunction &MF, 1696 const SIRegisterInfo &TRI, 1697 SIMachineFunctionInfo &Info) const { 1698 const LLT S32 = LLT::scalar(32); 1699 MachineRegisterInfo &MRI = MF.getRegInfo(); 1700 1701 if (Info.hasWorkItemIDX()) { 1702 Register Reg = AMDGPU::VGPR0; 1703 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1704 1705 CCInfo.AllocateReg(Reg); 1706 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1707 } 1708 1709 if (Info.hasWorkItemIDY()) { 1710 Register Reg = AMDGPU::VGPR1; 1711 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1712 1713 CCInfo.AllocateReg(Reg); 1714 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1715 } 1716 1717 if (Info.hasWorkItemIDZ()) { 1718 Register Reg = AMDGPU::VGPR2; 1719 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1720 1721 CCInfo.AllocateReg(Reg); 1722 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1723 } 1724 } 1725 1726 // Try to allocate a VGPR at the end of the argument list, or if no argument 1727 // VGPRs are left allocating a stack slot. 1728 // If \p Mask is is given it indicates bitfield position in the register. 1729 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1730 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1731 ArgDescriptor Arg = ArgDescriptor()) { 1732 if (Arg.isSet()) 1733 return ArgDescriptor::createArg(Arg, Mask); 1734 1735 ArrayRef<MCPhysReg> ArgVGPRs 1736 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1737 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1738 if (RegIdx == ArgVGPRs.size()) { 1739 // Spill to stack required. 1740 int64_t Offset = CCInfo.AllocateStack(4, 4); 1741 1742 return ArgDescriptor::createStack(Offset, Mask); 1743 } 1744 1745 unsigned Reg = ArgVGPRs[RegIdx]; 1746 Reg = CCInfo.AllocateReg(Reg); 1747 assert(Reg != AMDGPU::NoRegister); 1748 1749 MachineFunction &MF = CCInfo.getMachineFunction(); 1750 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1751 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1752 return ArgDescriptor::createRegister(Reg, Mask); 1753 } 1754 1755 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1756 const TargetRegisterClass *RC, 1757 unsigned NumArgRegs) { 1758 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1759 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1760 if (RegIdx == ArgSGPRs.size()) 1761 report_fatal_error("ran out of SGPRs for arguments"); 1762 1763 unsigned Reg = ArgSGPRs[RegIdx]; 1764 Reg = CCInfo.AllocateReg(Reg); 1765 assert(Reg != AMDGPU::NoRegister); 1766 1767 MachineFunction &MF = CCInfo.getMachineFunction(); 1768 MF.addLiveIn(Reg, RC); 1769 return ArgDescriptor::createRegister(Reg); 1770 } 1771 1772 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1773 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1774 } 1775 1776 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1777 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1778 } 1779 1780 /// Allocate implicit function VGPR arguments at the end of allocated user 1781 /// arguments. 1782 void SITargetLowering::allocateSpecialInputVGPRs( 1783 CCState &CCInfo, MachineFunction &MF, 1784 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1785 const unsigned Mask = 0x3ff; 1786 ArgDescriptor Arg; 1787 1788 if (Info.hasWorkItemIDX()) { 1789 Arg = allocateVGPR32Input(CCInfo, Mask); 1790 Info.setWorkItemIDX(Arg); 1791 } 1792 1793 if (Info.hasWorkItemIDY()) { 1794 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1795 Info.setWorkItemIDY(Arg); 1796 } 1797 1798 if (Info.hasWorkItemIDZ()) 1799 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1800 } 1801 1802 /// Allocate implicit function VGPR arguments in fixed registers. 1803 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1804 CCState &CCInfo, MachineFunction &MF, 1805 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1806 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1807 if (!Reg) 1808 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1809 1810 const unsigned Mask = 0x3ff; 1811 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1812 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1813 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1814 } 1815 1816 void SITargetLowering::allocateSpecialInputSGPRs( 1817 CCState &CCInfo, 1818 MachineFunction &MF, 1819 const SIRegisterInfo &TRI, 1820 SIMachineFunctionInfo &Info) const { 1821 auto &ArgInfo = Info.getArgInfo(); 1822 1823 // TODO: Unify handling with private memory pointers. 1824 1825 if (Info.hasDispatchPtr()) 1826 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1827 1828 if (Info.hasQueuePtr()) 1829 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1830 1831 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1832 // constant offset from the kernarg segment. 1833 if (Info.hasImplicitArgPtr()) 1834 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1835 1836 if (Info.hasDispatchID()) 1837 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1838 1839 // flat_scratch_init is not applicable for non-kernel functions. 1840 1841 if (Info.hasWorkGroupIDX()) 1842 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1843 1844 if (Info.hasWorkGroupIDY()) 1845 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1846 1847 if (Info.hasWorkGroupIDZ()) 1848 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1849 } 1850 1851 // Allocate special inputs passed in user SGPRs. 1852 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1853 MachineFunction &MF, 1854 const SIRegisterInfo &TRI, 1855 SIMachineFunctionInfo &Info) const { 1856 if (Info.hasImplicitBufferPtr()) { 1857 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1858 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1859 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1860 } 1861 1862 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1863 if (Info.hasPrivateSegmentBuffer()) { 1864 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1865 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1866 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1867 } 1868 1869 if (Info.hasDispatchPtr()) { 1870 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1871 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1872 CCInfo.AllocateReg(DispatchPtrReg); 1873 } 1874 1875 if (Info.hasQueuePtr()) { 1876 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1877 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1878 CCInfo.AllocateReg(QueuePtrReg); 1879 } 1880 1881 if (Info.hasKernargSegmentPtr()) { 1882 MachineRegisterInfo &MRI = MF.getRegInfo(); 1883 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1884 CCInfo.AllocateReg(InputPtrReg); 1885 1886 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1887 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1888 } 1889 1890 if (Info.hasDispatchID()) { 1891 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1892 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1893 CCInfo.AllocateReg(DispatchIDReg); 1894 } 1895 1896 if (Info.hasFlatScratchInit()) { 1897 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1898 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1899 CCInfo.AllocateReg(FlatScratchInitReg); 1900 } 1901 1902 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1903 // these from the dispatch pointer. 1904 } 1905 1906 // Allocate special input registers that are initialized per-wave. 1907 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1908 MachineFunction &MF, 1909 SIMachineFunctionInfo &Info, 1910 CallingConv::ID CallConv, 1911 bool IsShader) const { 1912 if (Info.hasWorkGroupIDX()) { 1913 unsigned Reg = Info.addWorkGroupIDX(); 1914 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1915 CCInfo.AllocateReg(Reg); 1916 } 1917 1918 if (Info.hasWorkGroupIDY()) { 1919 unsigned Reg = Info.addWorkGroupIDY(); 1920 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1921 CCInfo.AllocateReg(Reg); 1922 } 1923 1924 if (Info.hasWorkGroupIDZ()) { 1925 unsigned Reg = Info.addWorkGroupIDZ(); 1926 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1927 CCInfo.AllocateReg(Reg); 1928 } 1929 1930 if (Info.hasWorkGroupInfo()) { 1931 unsigned Reg = Info.addWorkGroupInfo(); 1932 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1933 CCInfo.AllocateReg(Reg); 1934 } 1935 1936 if (Info.hasPrivateSegmentWaveByteOffset()) { 1937 // Scratch wave offset passed in system SGPR. 1938 unsigned PrivateSegmentWaveByteOffsetReg; 1939 1940 if (IsShader) { 1941 PrivateSegmentWaveByteOffsetReg = 1942 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1943 1944 // This is true if the scratch wave byte offset doesn't have a fixed 1945 // location. 1946 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1947 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1948 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1949 } 1950 } else 1951 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1952 1953 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1954 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1955 } 1956 } 1957 1958 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1959 MachineFunction &MF, 1960 const SIRegisterInfo &TRI, 1961 SIMachineFunctionInfo &Info) { 1962 // Now that we've figured out where the scratch register inputs are, see if 1963 // should reserve the arguments and use them directly. 1964 MachineFrameInfo &MFI = MF.getFrameInfo(); 1965 bool HasStackObjects = MFI.hasStackObjects(); 1966 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1967 1968 // Record that we know we have non-spill stack objects so we don't need to 1969 // check all stack objects later. 1970 if (HasStackObjects) 1971 Info.setHasNonSpillStackObjects(true); 1972 1973 // Everything live out of a block is spilled with fast regalloc, so it's 1974 // almost certain that spilling will be required. 1975 if (TM.getOptLevel() == CodeGenOpt::None) 1976 HasStackObjects = true; 1977 1978 // For now assume stack access is needed in any callee functions, so we need 1979 // the scratch registers to pass in. 1980 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1981 1982 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1983 // If we have stack objects, we unquestionably need the private buffer 1984 // resource. For the Code Object V2 ABI, this will be the first 4 user 1985 // SGPR inputs. We can reserve those and use them directly. 1986 1987 Register PrivateSegmentBufferReg = 1988 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1989 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1990 } else { 1991 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1992 // We tentatively reserve the last registers (skipping the last registers 1993 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1994 // we'll replace these with the ones immediately after those which were 1995 // really allocated. In the prologue copies will be inserted from the 1996 // argument to these reserved registers. 1997 1998 // Without HSA, relocations are used for the scratch pointer and the 1999 // buffer resource setup is always inserted in the prologue. Scratch wave 2000 // offset is still in an input SGPR. 2001 Info.setScratchRSrcReg(ReservedBufferReg); 2002 } 2003 2004 MachineRegisterInfo &MRI = MF.getRegInfo(); 2005 2006 // For entry functions we have to set up the stack pointer if we use it, 2007 // whereas non-entry functions get this "for free". This means there is no 2008 // intrinsic advantage to using S32 over S34 in cases where we do not have 2009 // calls but do need a frame pointer (i.e. if we are requested to have one 2010 // because frame pointer elimination is disabled). To keep things simple we 2011 // only ever use S32 as the call ABI stack pointer, and so using it does not 2012 // imply we need a separate frame pointer. 2013 // 2014 // Try to use s32 as the SP, but move it if it would interfere with input 2015 // arguments. This won't work with calls though. 2016 // 2017 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2018 // registers. 2019 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2020 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2021 } else { 2022 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2023 2024 if (MFI.hasCalls()) 2025 report_fatal_error("call in graphics shader with too many input SGPRs"); 2026 2027 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2028 if (!MRI.isLiveIn(Reg)) { 2029 Info.setStackPtrOffsetReg(Reg); 2030 break; 2031 } 2032 } 2033 2034 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2035 report_fatal_error("failed to find register for SP"); 2036 } 2037 2038 // hasFP should be accurate for entry functions even before the frame is 2039 // finalized, because it does not rely on the known stack size, only 2040 // properties like whether variable sized objects are present. 2041 if (ST.getFrameLowering()->hasFP(MF)) { 2042 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2043 } 2044 } 2045 2046 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2047 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2048 return !Info->isEntryFunction(); 2049 } 2050 2051 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2052 2053 } 2054 2055 void SITargetLowering::insertCopiesSplitCSR( 2056 MachineBasicBlock *Entry, 2057 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2058 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2059 2060 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2061 if (!IStart) 2062 return; 2063 2064 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2065 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2066 MachineBasicBlock::iterator MBBI = Entry->begin(); 2067 for (const MCPhysReg *I = IStart; *I; ++I) { 2068 const TargetRegisterClass *RC = nullptr; 2069 if (AMDGPU::SReg_64RegClass.contains(*I)) 2070 RC = &AMDGPU::SGPR_64RegClass; 2071 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2072 RC = &AMDGPU::SGPR_32RegClass; 2073 else 2074 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2075 2076 Register NewVR = MRI->createVirtualRegister(RC); 2077 // Create copy from CSR to a virtual register. 2078 Entry->addLiveIn(*I); 2079 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2080 .addReg(*I); 2081 2082 // Insert the copy-back instructions right before the terminator. 2083 for (auto *Exit : Exits) 2084 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2085 TII->get(TargetOpcode::COPY), *I) 2086 .addReg(NewVR); 2087 } 2088 } 2089 2090 SDValue SITargetLowering::LowerFormalArguments( 2091 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2092 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2093 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2094 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2095 2096 MachineFunction &MF = DAG.getMachineFunction(); 2097 const Function &Fn = MF.getFunction(); 2098 FunctionType *FType = MF.getFunction().getFunctionType(); 2099 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2100 2101 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2102 DiagnosticInfoUnsupported NoGraphicsHSA( 2103 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2104 DAG.getContext()->diagnose(NoGraphicsHSA); 2105 return DAG.getEntryNode(); 2106 } 2107 2108 SmallVector<ISD::InputArg, 16> Splits; 2109 SmallVector<CCValAssign, 16> ArgLocs; 2110 BitVector Skipped(Ins.size()); 2111 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2112 *DAG.getContext()); 2113 2114 bool IsShader = AMDGPU::isShader(CallConv); 2115 bool IsKernel = AMDGPU::isKernel(CallConv); 2116 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2117 2118 if (IsShader) { 2119 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2120 2121 // At least one interpolation mode must be enabled or else the GPU will 2122 // hang. 2123 // 2124 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2125 // set PSInputAddr, the user wants to enable some bits after the compilation 2126 // based on run-time states. Since we can't know what the final PSInputEna 2127 // will look like, so we shouldn't do anything here and the user should take 2128 // responsibility for the correct programming. 2129 // 2130 // Otherwise, the following restrictions apply: 2131 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2132 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2133 // enabled too. 2134 if (CallConv == CallingConv::AMDGPU_PS) { 2135 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2136 ((Info->getPSInputAddr() & 0xF) == 0 && 2137 Info->isPSInputAllocated(11))) { 2138 CCInfo.AllocateReg(AMDGPU::VGPR0); 2139 CCInfo.AllocateReg(AMDGPU::VGPR1); 2140 Info->markPSInputAllocated(0); 2141 Info->markPSInputEnabled(0); 2142 } 2143 if (Subtarget->isAmdPalOS()) { 2144 // For isAmdPalOS, the user does not enable some bits after compilation 2145 // based on run-time states; the register values being generated here are 2146 // the final ones set in hardware. Therefore we need to apply the 2147 // workaround to PSInputAddr and PSInputEnable together. (The case where 2148 // a bit is set in PSInputAddr but not PSInputEnable is where the 2149 // frontend set up an input arg for a particular interpolation mode, but 2150 // nothing uses that input arg. Really we should have an earlier pass 2151 // that removes such an arg.) 2152 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2153 if ((PsInputBits & 0x7F) == 0 || 2154 ((PsInputBits & 0xF) == 0 && 2155 (PsInputBits >> 11 & 1))) 2156 Info->markPSInputEnabled( 2157 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2158 } 2159 } 2160 2161 assert(!Info->hasDispatchPtr() && 2162 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2163 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2164 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2165 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2166 !Info->hasWorkItemIDZ()); 2167 } else if (IsKernel) { 2168 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2169 } else { 2170 Splits.append(Ins.begin(), Ins.end()); 2171 } 2172 2173 if (IsEntryFunc) { 2174 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2175 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2176 } else { 2177 // For the fixed ABI, pass workitem IDs in the last argument register. 2178 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2179 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2180 } 2181 2182 if (IsKernel) { 2183 analyzeFormalArgumentsCompute(CCInfo, Ins); 2184 } else { 2185 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2186 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2187 } 2188 2189 SmallVector<SDValue, 16> Chains; 2190 2191 // FIXME: This is the minimum kernel argument alignment. We should improve 2192 // this to the maximum alignment of the arguments. 2193 // 2194 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2195 // kern arg offset. 2196 const unsigned KernelArgBaseAlign = 16; 2197 2198 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2199 const ISD::InputArg &Arg = Ins[i]; 2200 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2201 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2202 continue; 2203 } 2204 2205 CCValAssign &VA = ArgLocs[ArgIdx++]; 2206 MVT VT = VA.getLocVT(); 2207 2208 if (IsEntryFunc && VA.isMemLoc()) { 2209 VT = Ins[i].VT; 2210 EVT MemVT = VA.getLocVT(); 2211 2212 const uint64_t Offset = VA.getLocMemOffset(); 2213 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2214 2215 SDValue Arg = lowerKernargMemParameter( 2216 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2217 Chains.push_back(Arg.getValue(1)); 2218 2219 auto *ParamTy = 2220 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2221 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2222 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2223 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2224 // On SI local pointers are just offsets into LDS, so they are always 2225 // less than 16-bits. On CI and newer they could potentially be 2226 // real pointers, so we can't guarantee their size. 2227 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2228 DAG.getValueType(MVT::i16)); 2229 } 2230 2231 InVals.push_back(Arg); 2232 continue; 2233 } else if (!IsEntryFunc && VA.isMemLoc()) { 2234 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2235 InVals.push_back(Val); 2236 if (!Arg.Flags.isByVal()) 2237 Chains.push_back(Val.getValue(1)); 2238 continue; 2239 } 2240 2241 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2242 2243 Register Reg = VA.getLocReg(); 2244 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2245 EVT ValVT = VA.getValVT(); 2246 2247 Reg = MF.addLiveIn(Reg, RC); 2248 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2249 2250 if (Arg.Flags.isSRet()) { 2251 // The return object should be reasonably addressable. 2252 2253 // FIXME: This helps when the return is a real sret. If it is a 2254 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2255 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2256 unsigned NumBits 2257 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2258 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2259 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2260 } 2261 2262 // If this is an 8 or 16-bit value, it is really passed promoted 2263 // to 32 bits. Insert an assert[sz]ext to capture this, then 2264 // truncate to the right size. 2265 switch (VA.getLocInfo()) { 2266 case CCValAssign::Full: 2267 break; 2268 case CCValAssign::BCvt: 2269 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2270 break; 2271 case CCValAssign::SExt: 2272 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2273 DAG.getValueType(ValVT)); 2274 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2275 break; 2276 case CCValAssign::ZExt: 2277 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2278 DAG.getValueType(ValVT)); 2279 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2280 break; 2281 case CCValAssign::AExt: 2282 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2283 break; 2284 default: 2285 llvm_unreachable("Unknown loc info!"); 2286 } 2287 2288 InVals.push_back(Val); 2289 } 2290 2291 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2292 // Special inputs come after user arguments. 2293 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2294 } 2295 2296 // Start adding system SGPRs. 2297 if (IsEntryFunc) { 2298 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2299 } else { 2300 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2301 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2302 } 2303 2304 auto &ArgUsageInfo = 2305 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2306 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2307 2308 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2309 Info->setBytesInStackArgArea(StackArgSize); 2310 2311 return Chains.empty() ? Chain : 2312 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2313 } 2314 2315 // TODO: If return values can't fit in registers, we should return as many as 2316 // possible in registers before passing on stack. 2317 bool SITargetLowering::CanLowerReturn( 2318 CallingConv::ID CallConv, 2319 MachineFunction &MF, bool IsVarArg, 2320 const SmallVectorImpl<ISD::OutputArg> &Outs, 2321 LLVMContext &Context) const { 2322 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2323 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2324 // for shaders. Vector types should be explicitly handled by CC. 2325 if (AMDGPU::isEntryFunctionCC(CallConv)) 2326 return true; 2327 2328 SmallVector<CCValAssign, 16> RVLocs; 2329 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2330 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2331 } 2332 2333 SDValue 2334 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2335 bool isVarArg, 2336 const SmallVectorImpl<ISD::OutputArg> &Outs, 2337 const SmallVectorImpl<SDValue> &OutVals, 2338 const SDLoc &DL, SelectionDAG &DAG) const { 2339 MachineFunction &MF = DAG.getMachineFunction(); 2340 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2341 2342 if (AMDGPU::isKernel(CallConv)) { 2343 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2344 OutVals, DL, DAG); 2345 } 2346 2347 bool IsShader = AMDGPU::isShader(CallConv); 2348 2349 Info->setIfReturnsVoid(Outs.empty()); 2350 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2351 2352 // CCValAssign - represent the assignment of the return value to a location. 2353 SmallVector<CCValAssign, 48> RVLocs; 2354 SmallVector<ISD::OutputArg, 48> Splits; 2355 2356 // CCState - Info about the registers and stack slots. 2357 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2358 *DAG.getContext()); 2359 2360 // Analyze outgoing return values. 2361 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2362 2363 SDValue Flag; 2364 SmallVector<SDValue, 48> RetOps; 2365 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2366 2367 // Add return address for callable functions. 2368 if (!Info->isEntryFunction()) { 2369 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2370 SDValue ReturnAddrReg = CreateLiveInRegister( 2371 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2372 2373 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2374 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2375 MVT::i64); 2376 Chain = 2377 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2378 Flag = Chain.getValue(1); 2379 RetOps.push_back(ReturnAddrVirtualReg); 2380 } 2381 2382 // Copy the result values into the output registers. 2383 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2384 ++I, ++RealRVLocIdx) { 2385 CCValAssign &VA = RVLocs[I]; 2386 assert(VA.isRegLoc() && "Can only return in registers!"); 2387 // TODO: Partially return in registers if return values don't fit. 2388 SDValue Arg = OutVals[RealRVLocIdx]; 2389 2390 // Copied from other backends. 2391 switch (VA.getLocInfo()) { 2392 case CCValAssign::Full: 2393 break; 2394 case CCValAssign::BCvt: 2395 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2396 break; 2397 case CCValAssign::SExt: 2398 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2399 break; 2400 case CCValAssign::ZExt: 2401 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2402 break; 2403 case CCValAssign::AExt: 2404 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2405 break; 2406 default: 2407 llvm_unreachable("Unknown loc info!"); 2408 } 2409 2410 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2411 Flag = Chain.getValue(1); 2412 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2413 } 2414 2415 // FIXME: Does sret work properly? 2416 if (!Info->isEntryFunction()) { 2417 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2418 const MCPhysReg *I = 2419 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2420 if (I) { 2421 for (; *I; ++I) { 2422 if (AMDGPU::SReg_64RegClass.contains(*I)) 2423 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2424 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2425 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2426 else 2427 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2428 } 2429 } 2430 } 2431 2432 // Update chain and glue. 2433 RetOps[0] = Chain; 2434 if (Flag.getNode()) 2435 RetOps.push_back(Flag); 2436 2437 unsigned Opc = AMDGPUISD::ENDPGM; 2438 if (!IsWaveEnd) 2439 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2440 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2441 } 2442 2443 SDValue SITargetLowering::LowerCallResult( 2444 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2445 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2446 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2447 SDValue ThisVal) const { 2448 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2449 2450 // Assign locations to each value returned by this call. 2451 SmallVector<CCValAssign, 16> RVLocs; 2452 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2453 *DAG.getContext()); 2454 CCInfo.AnalyzeCallResult(Ins, RetCC); 2455 2456 // Copy all of the result registers out of their specified physreg. 2457 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2458 CCValAssign VA = RVLocs[i]; 2459 SDValue Val; 2460 2461 if (VA.isRegLoc()) { 2462 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2463 Chain = Val.getValue(1); 2464 InFlag = Val.getValue(2); 2465 } else if (VA.isMemLoc()) { 2466 report_fatal_error("TODO: return values in memory"); 2467 } else 2468 llvm_unreachable("unknown argument location type"); 2469 2470 switch (VA.getLocInfo()) { 2471 case CCValAssign::Full: 2472 break; 2473 case CCValAssign::BCvt: 2474 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2475 break; 2476 case CCValAssign::ZExt: 2477 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2478 DAG.getValueType(VA.getValVT())); 2479 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2480 break; 2481 case CCValAssign::SExt: 2482 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2483 DAG.getValueType(VA.getValVT())); 2484 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2485 break; 2486 case CCValAssign::AExt: 2487 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2488 break; 2489 default: 2490 llvm_unreachable("Unknown loc info!"); 2491 } 2492 2493 InVals.push_back(Val); 2494 } 2495 2496 return Chain; 2497 } 2498 2499 // Add code to pass special inputs required depending on used features separate 2500 // from the explicit user arguments present in the IR. 2501 void SITargetLowering::passSpecialInputs( 2502 CallLoweringInfo &CLI, 2503 CCState &CCInfo, 2504 const SIMachineFunctionInfo &Info, 2505 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2506 SmallVectorImpl<SDValue> &MemOpChains, 2507 SDValue Chain) const { 2508 // If we don't have a call site, this was a call inserted by 2509 // legalization. These can never use special inputs. 2510 if (!CLI.CB) 2511 return; 2512 2513 SelectionDAG &DAG = CLI.DAG; 2514 const SDLoc &DL = CLI.DL; 2515 2516 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2517 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2518 2519 const AMDGPUFunctionArgInfo *CalleeArgInfo 2520 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2521 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2522 auto &ArgUsageInfo = 2523 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2524 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2525 } 2526 2527 // TODO: Unify with private memory register handling. This is complicated by 2528 // the fact that at least in kernels, the input argument is not necessarily 2529 // in the same location as the input. 2530 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2531 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2532 AMDGPUFunctionArgInfo::QUEUE_PTR, 2533 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2534 AMDGPUFunctionArgInfo::DISPATCH_ID, 2535 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2536 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2537 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2538 }; 2539 2540 for (auto InputID : InputRegs) { 2541 const ArgDescriptor *OutgoingArg; 2542 const TargetRegisterClass *ArgRC; 2543 2544 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID); 2545 if (!OutgoingArg) 2546 continue; 2547 2548 const ArgDescriptor *IncomingArg; 2549 const TargetRegisterClass *IncomingArgRC; 2550 std::tie(IncomingArg, IncomingArgRC) 2551 = CallerArgInfo.getPreloadedValue(InputID); 2552 assert(IncomingArgRC == ArgRC); 2553 2554 // All special arguments are ints for now. 2555 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2556 SDValue InputReg; 2557 2558 if (IncomingArg) { 2559 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2560 } else { 2561 // The implicit arg ptr is special because it doesn't have a corresponding 2562 // input for kernels, and is computed from the kernarg segment pointer. 2563 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2564 InputReg = getImplicitArgPtr(DAG, DL); 2565 } 2566 2567 if (OutgoingArg->isRegister()) { 2568 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2569 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2570 report_fatal_error("failed to allocate implicit input argument"); 2571 } else { 2572 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2573 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2574 SpecialArgOffset); 2575 MemOpChains.push_back(ArgStore); 2576 } 2577 } 2578 2579 // Pack workitem IDs into a single register or pass it as is if already 2580 // packed. 2581 const ArgDescriptor *OutgoingArg; 2582 const TargetRegisterClass *ArgRC; 2583 2584 std::tie(OutgoingArg, ArgRC) = 2585 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2586 if (!OutgoingArg) 2587 std::tie(OutgoingArg, ArgRC) = 2588 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2589 if (!OutgoingArg) 2590 std::tie(OutgoingArg, ArgRC) = 2591 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2592 if (!OutgoingArg) 2593 return; 2594 2595 const ArgDescriptor *IncomingArgX 2596 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2597 const ArgDescriptor *IncomingArgY 2598 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2599 const ArgDescriptor *IncomingArgZ 2600 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2601 2602 SDValue InputReg; 2603 SDLoc SL; 2604 2605 // If incoming ids are not packed we need to pack them. 2606 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2607 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2608 2609 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2610 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2611 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2612 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2613 InputReg = InputReg.getNode() ? 2614 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2615 } 2616 2617 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2618 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2619 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2620 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2621 InputReg = InputReg.getNode() ? 2622 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2623 } 2624 2625 if (!InputReg.getNode()) { 2626 // Workitem ids are already packed, any of present incoming arguments 2627 // will carry all required fields. 2628 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2629 IncomingArgX ? *IncomingArgX : 2630 IncomingArgY ? *IncomingArgY : 2631 *IncomingArgZ, ~0u); 2632 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2633 } 2634 2635 if (OutgoingArg->isRegister()) { 2636 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2637 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2638 } else { 2639 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2640 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2641 SpecialArgOffset); 2642 MemOpChains.push_back(ArgStore); 2643 } 2644 } 2645 2646 static bool canGuaranteeTCO(CallingConv::ID CC) { 2647 return CC == CallingConv::Fast; 2648 } 2649 2650 /// Return true if we might ever do TCO for calls with this calling convention. 2651 static bool mayTailCallThisCC(CallingConv::ID CC) { 2652 switch (CC) { 2653 case CallingConv::C: 2654 return true; 2655 default: 2656 return canGuaranteeTCO(CC); 2657 } 2658 } 2659 2660 bool SITargetLowering::isEligibleForTailCallOptimization( 2661 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2662 const SmallVectorImpl<ISD::OutputArg> &Outs, 2663 const SmallVectorImpl<SDValue> &OutVals, 2664 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2665 if (!mayTailCallThisCC(CalleeCC)) 2666 return false; 2667 2668 MachineFunction &MF = DAG.getMachineFunction(); 2669 const Function &CallerF = MF.getFunction(); 2670 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2671 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2672 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2673 2674 // Kernels aren't callable, and don't have a live in return address so it 2675 // doesn't make sense to do a tail call with entry functions. 2676 if (!CallerPreserved) 2677 return false; 2678 2679 bool CCMatch = CallerCC == CalleeCC; 2680 2681 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2682 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2683 return true; 2684 return false; 2685 } 2686 2687 // TODO: Can we handle var args? 2688 if (IsVarArg) 2689 return false; 2690 2691 for (const Argument &Arg : CallerF.args()) { 2692 if (Arg.hasByValAttr()) 2693 return false; 2694 } 2695 2696 LLVMContext &Ctx = *DAG.getContext(); 2697 2698 // Check that the call results are passed in the same way. 2699 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2700 CCAssignFnForCall(CalleeCC, IsVarArg), 2701 CCAssignFnForCall(CallerCC, IsVarArg))) 2702 return false; 2703 2704 // The callee has to preserve all registers the caller needs to preserve. 2705 if (!CCMatch) { 2706 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2707 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2708 return false; 2709 } 2710 2711 // Nothing more to check if the callee is taking no arguments. 2712 if (Outs.empty()) 2713 return true; 2714 2715 SmallVector<CCValAssign, 16> ArgLocs; 2716 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2717 2718 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2719 2720 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2721 // If the stack arguments for this call do not fit into our own save area then 2722 // the call cannot be made tail. 2723 // TODO: Is this really necessary? 2724 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2725 return false; 2726 2727 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2728 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2729 } 2730 2731 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2732 if (!CI->isTailCall()) 2733 return false; 2734 2735 const Function *ParentFn = CI->getParent()->getParent(); 2736 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2737 return false; 2738 return true; 2739 } 2740 2741 // The wave scratch offset register is used as the global base pointer. 2742 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2743 SmallVectorImpl<SDValue> &InVals) const { 2744 SelectionDAG &DAG = CLI.DAG; 2745 const SDLoc &DL = CLI.DL; 2746 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2747 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2748 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2749 SDValue Chain = CLI.Chain; 2750 SDValue Callee = CLI.Callee; 2751 bool &IsTailCall = CLI.IsTailCall; 2752 CallingConv::ID CallConv = CLI.CallConv; 2753 bool IsVarArg = CLI.IsVarArg; 2754 bool IsSibCall = false; 2755 bool IsThisReturn = false; 2756 MachineFunction &MF = DAG.getMachineFunction(); 2757 2758 if (Callee.isUndef() || isNullConstant(Callee)) { 2759 if (!CLI.IsTailCall) { 2760 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2761 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2762 } 2763 2764 return Chain; 2765 } 2766 2767 if (IsVarArg) { 2768 return lowerUnhandledCall(CLI, InVals, 2769 "unsupported call to variadic function "); 2770 } 2771 2772 if (!CLI.CB) 2773 report_fatal_error("unsupported libcall legalization"); 2774 2775 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2776 !CLI.CB->getCalledFunction()) { 2777 return lowerUnhandledCall(CLI, InVals, 2778 "unsupported indirect call to function "); 2779 } 2780 2781 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2782 return lowerUnhandledCall(CLI, InVals, 2783 "unsupported required tail call to function "); 2784 } 2785 2786 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2787 // Note the issue is with the CC of the calling function, not of the call 2788 // itself. 2789 return lowerUnhandledCall(CLI, InVals, 2790 "unsupported call from graphics shader of function "); 2791 } 2792 2793 if (IsTailCall) { 2794 IsTailCall = isEligibleForTailCallOptimization( 2795 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2796 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2797 report_fatal_error("failed to perform tail call elimination on a call " 2798 "site marked musttail"); 2799 } 2800 2801 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2802 2803 // A sibling call is one where we're under the usual C ABI and not planning 2804 // to change that but can still do a tail call: 2805 if (!TailCallOpt && IsTailCall) 2806 IsSibCall = true; 2807 2808 if (IsTailCall) 2809 ++NumTailCalls; 2810 } 2811 2812 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2813 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2814 SmallVector<SDValue, 8> MemOpChains; 2815 2816 // Analyze operands of the call, assigning locations to each operand. 2817 SmallVector<CCValAssign, 16> ArgLocs; 2818 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2819 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2820 2821 if (AMDGPUTargetMachine::EnableFixedFunctionABI) { 2822 // With a fixed ABI, allocate fixed registers before user arguments. 2823 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2824 } 2825 2826 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2827 2828 // Get a count of how many bytes are to be pushed on the stack. 2829 unsigned NumBytes = CCInfo.getNextStackOffset(); 2830 2831 if (IsSibCall) { 2832 // Since we're not changing the ABI to make this a tail call, the memory 2833 // operands are already available in the caller's incoming argument space. 2834 NumBytes = 0; 2835 } 2836 2837 // FPDiff is the byte offset of the call's argument area from the callee's. 2838 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2839 // by this amount for a tail call. In a sibling call it must be 0 because the 2840 // caller will deallocate the entire stack and the callee still expects its 2841 // arguments to begin at SP+0. Completely unused for non-tail calls. 2842 int32_t FPDiff = 0; 2843 MachineFrameInfo &MFI = MF.getFrameInfo(); 2844 2845 // Adjust the stack pointer for the new arguments... 2846 // These operations are automatically eliminated by the prolog/epilog pass 2847 if (!IsSibCall) { 2848 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2849 2850 SmallVector<SDValue, 4> CopyFromChains; 2851 2852 // In the HSA case, this should be an identity copy. 2853 SDValue ScratchRSrcReg 2854 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2855 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2856 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2857 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2858 } 2859 2860 MVT PtrVT = MVT::i32; 2861 2862 // Walk the register/memloc assignments, inserting copies/loads. 2863 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2864 CCValAssign &VA = ArgLocs[i]; 2865 SDValue Arg = OutVals[i]; 2866 2867 // Promote the value if needed. 2868 switch (VA.getLocInfo()) { 2869 case CCValAssign::Full: 2870 break; 2871 case CCValAssign::BCvt: 2872 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2873 break; 2874 case CCValAssign::ZExt: 2875 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2876 break; 2877 case CCValAssign::SExt: 2878 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2879 break; 2880 case CCValAssign::AExt: 2881 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2882 break; 2883 case CCValAssign::FPExt: 2884 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2885 break; 2886 default: 2887 llvm_unreachable("Unknown loc info!"); 2888 } 2889 2890 if (VA.isRegLoc()) { 2891 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2892 } else { 2893 assert(VA.isMemLoc()); 2894 2895 SDValue DstAddr; 2896 MachinePointerInfo DstInfo; 2897 2898 unsigned LocMemOffset = VA.getLocMemOffset(); 2899 int32_t Offset = LocMemOffset; 2900 2901 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2902 MaybeAlign Alignment; 2903 2904 if (IsTailCall) { 2905 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2906 unsigned OpSize = Flags.isByVal() ? 2907 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2908 2909 // FIXME: We can have better than the minimum byval required alignment. 2910 Alignment = 2911 Flags.isByVal() 2912 ? Flags.getNonZeroByValAlign() 2913 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2914 2915 Offset = Offset + FPDiff; 2916 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2917 2918 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2919 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2920 2921 // Make sure any stack arguments overlapping with where we're storing 2922 // are loaded before this eventual operation. Otherwise they'll be 2923 // clobbered. 2924 2925 // FIXME: Why is this really necessary? This seems to just result in a 2926 // lot of code to copy the stack and write them back to the same 2927 // locations, which are supposed to be immutable? 2928 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2929 } else { 2930 DstAddr = PtrOff; 2931 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2932 Alignment = 2933 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2934 } 2935 2936 if (Outs[i].Flags.isByVal()) { 2937 SDValue SizeNode = 2938 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2939 SDValue Cpy = 2940 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2941 Outs[i].Flags.getNonZeroByValAlign(), 2942 /*isVol = */ false, /*AlwaysInline = */ true, 2943 /*isTailCall = */ false, DstInfo, 2944 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2945 2946 MemOpChains.push_back(Cpy); 2947 } else { 2948 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2949 Alignment ? Alignment->value() : 0); 2950 MemOpChains.push_back(Store); 2951 } 2952 } 2953 } 2954 2955 if (!AMDGPUTargetMachine::EnableFixedFunctionABI) { 2956 // Copy special input registers after user input arguments. 2957 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2958 } 2959 2960 if (!MemOpChains.empty()) 2961 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2962 2963 // Build a sequence of copy-to-reg nodes chained together with token chain 2964 // and flag operands which copy the outgoing args into the appropriate regs. 2965 SDValue InFlag; 2966 for (auto &RegToPass : RegsToPass) { 2967 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2968 RegToPass.second, InFlag); 2969 InFlag = Chain.getValue(1); 2970 } 2971 2972 2973 SDValue PhysReturnAddrReg; 2974 if (IsTailCall) { 2975 // Since the return is being combined with the call, we need to pass on the 2976 // return address. 2977 2978 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2979 SDValue ReturnAddrReg = CreateLiveInRegister( 2980 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2981 2982 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2983 MVT::i64); 2984 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2985 InFlag = Chain.getValue(1); 2986 } 2987 2988 // We don't usually want to end the call-sequence here because we would tidy 2989 // the frame up *after* the call, however in the ABI-changing tail-call case 2990 // we've carefully laid out the parameters so that when sp is reset they'll be 2991 // in the correct location. 2992 if (IsTailCall && !IsSibCall) { 2993 Chain = DAG.getCALLSEQ_END(Chain, 2994 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2995 DAG.getTargetConstant(0, DL, MVT::i32), 2996 InFlag, DL); 2997 InFlag = Chain.getValue(1); 2998 } 2999 3000 std::vector<SDValue> Ops; 3001 Ops.push_back(Chain); 3002 Ops.push_back(Callee); 3003 // Add a redundant copy of the callee global which will not be legalized, as 3004 // we need direct access to the callee later. 3005 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3006 const GlobalValue *GV = GSD->getGlobal(); 3007 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3008 } else { 3009 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3010 } 3011 3012 if (IsTailCall) { 3013 // Each tail call may have to adjust the stack by a different amount, so 3014 // this information must travel along with the operation for eventual 3015 // consumption by emitEpilogue. 3016 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3017 3018 Ops.push_back(PhysReturnAddrReg); 3019 } 3020 3021 // Add argument registers to the end of the list so that they are known live 3022 // into the call. 3023 for (auto &RegToPass : RegsToPass) { 3024 Ops.push_back(DAG.getRegister(RegToPass.first, 3025 RegToPass.second.getValueType())); 3026 } 3027 3028 // Add a register mask operand representing the call-preserved registers. 3029 3030 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3031 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3032 assert(Mask && "Missing call preserved mask for calling convention"); 3033 Ops.push_back(DAG.getRegisterMask(Mask)); 3034 3035 if (InFlag.getNode()) 3036 Ops.push_back(InFlag); 3037 3038 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3039 3040 // If we're doing a tall call, use a TC_RETURN here rather than an 3041 // actual call instruction. 3042 if (IsTailCall) { 3043 MFI.setHasTailCall(); 3044 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3045 } 3046 3047 // Returns a chain and a flag for retval copy to use. 3048 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3049 Chain = Call.getValue(0); 3050 InFlag = Call.getValue(1); 3051 3052 uint64_t CalleePopBytes = NumBytes; 3053 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3054 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3055 InFlag, DL); 3056 if (!Ins.empty()) 3057 InFlag = Chain.getValue(1); 3058 3059 // Handle result values, copying them out of physregs into vregs that we 3060 // return. 3061 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3062 InVals, IsThisReturn, 3063 IsThisReturn ? OutVals[0] : SDValue()); 3064 } 3065 3066 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3067 const MachineFunction &MF) const { 3068 Register Reg = StringSwitch<Register>(RegName) 3069 .Case("m0", AMDGPU::M0) 3070 .Case("exec", AMDGPU::EXEC) 3071 .Case("exec_lo", AMDGPU::EXEC_LO) 3072 .Case("exec_hi", AMDGPU::EXEC_HI) 3073 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3074 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3075 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3076 .Default(Register()); 3077 3078 if (Reg == AMDGPU::NoRegister) { 3079 report_fatal_error(Twine("invalid register name \"" 3080 + StringRef(RegName) + "\".")); 3081 3082 } 3083 3084 if (!Subtarget->hasFlatScrRegister() && 3085 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3086 report_fatal_error(Twine("invalid register \"" 3087 + StringRef(RegName) + "\" for subtarget.")); 3088 } 3089 3090 switch (Reg) { 3091 case AMDGPU::M0: 3092 case AMDGPU::EXEC_LO: 3093 case AMDGPU::EXEC_HI: 3094 case AMDGPU::FLAT_SCR_LO: 3095 case AMDGPU::FLAT_SCR_HI: 3096 if (VT.getSizeInBits() == 32) 3097 return Reg; 3098 break; 3099 case AMDGPU::EXEC: 3100 case AMDGPU::FLAT_SCR: 3101 if (VT.getSizeInBits() == 64) 3102 return Reg; 3103 break; 3104 default: 3105 llvm_unreachable("missing register type checking"); 3106 } 3107 3108 report_fatal_error(Twine("invalid type for register \"" 3109 + StringRef(RegName) + "\".")); 3110 } 3111 3112 // If kill is not the last instruction, split the block so kill is always a 3113 // proper terminator. 3114 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3115 MachineBasicBlock *BB) const { 3116 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3117 3118 MachineBasicBlock::iterator SplitPoint(&MI); 3119 ++SplitPoint; 3120 3121 if (SplitPoint == BB->end()) { 3122 // Don't bother with a new block. 3123 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3124 return BB; 3125 } 3126 3127 MachineFunction *MF = BB->getParent(); 3128 MachineBasicBlock *SplitBB 3129 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3130 3131 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3132 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3133 3134 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3135 BB->addSuccessor(SplitBB); 3136 3137 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3138 return SplitBB; 3139 } 3140 3141 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3142 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3143 // be the first instruction in the remainder block. 3144 // 3145 /// \returns { LoopBody, Remainder } 3146 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3147 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3148 MachineFunction *MF = MBB.getParent(); 3149 MachineBasicBlock::iterator I(&MI); 3150 3151 // To insert the loop we need to split the block. Move everything after this 3152 // point to a new block, and insert a new empty block between the two. 3153 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3154 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3155 MachineFunction::iterator MBBI(MBB); 3156 ++MBBI; 3157 3158 MF->insert(MBBI, LoopBB); 3159 MF->insert(MBBI, RemainderBB); 3160 3161 LoopBB->addSuccessor(LoopBB); 3162 LoopBB->addSuccessor(RemainderBB); 3163 3164 // Move the rest of the block into a new block. 3165 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3166 3167 if (InstInLoop) { 3168 auto Next = std::next(I); 3169 3170 // Move instruction to loop body. 3171 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3172 3173 // Move the rest of the block. 3174 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3175 } else { 3176 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3177 } 3178 3179 MBB.addSuccessor(LoopBB); 3180 3181 return std::make_pair(LoopBB, RemainderBB); 3182 } 3183 3184 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3185 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3186 MachineBasicBlock *MBB = MI.getParent(); 3187 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3188 auto I = MI.getIterator(); 3189 auto E = std::next(I); 3190 3191 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3192 .addImm(0); 3193 3194 MIBundleBuilder Bundler(*MBB, I, E); 3195 finalizeBundle(*MBB, Bundler.begin()); 3196 } 3197 3198 MachineBasicBlock * 3199 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3200 MachineBasicBlock *BB) const { 3201 const DebugLoc &DL = MI.getDebugLoc(); 3202 3203 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3204 3205 MachineBasicBlock *LoopBB; 3206 MachineBasicBlock *RemainderBB; 3207 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3208 3209 // Apparently kill flags are only valid if the def is in the same block? 3210 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3211 Src->setIsKill(false); 3212 3213 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3214 3215 MachineBasicBlock::iterator I = LoopBB->end(); 3216 3217 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3218 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3219 3220 // Clear TRAP_STS.MEM_VIOL 3221 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3222 .addImm(0) 3223 .addImm(EncodedReg); 3224 3225 bundleInstWithWaitcnt(MI); 3226 3227 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3228 3229 // Load and check TRAP_STS.MEM_VIOL 3230 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3231 .addImm(EncodedReg); 3232 3233 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3234 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3235 .addReg(Reg, RegState::Kill) 3236 .addImm(0); 3237 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3238 .addMBB(LoopBB); 3239 3240 return RemainderBB; 3241 } 3242 3243 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3244 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3245 // will only do one iteration. In the worst case, this will loop 64 times. 3246 // 3247 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3248 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3249 const SIInstrInfo *TII, 3250 MachineRegisterInfo &MRI, 3251 MachineBasicBlock &OrigBB, 3252 MachineBasicBlock &LoopBB, 3253 const DebugLoc &DL, 3254 const MachineOperand &IdxReg, 3255 unsigned InitReg, 3256 unsigned ResultReg, 3257 unsigned PhiReg, 3258 unsigned InitSaveExecReg, 3259 int Offset, 3260 bool UseGPRIdxMode, 3261 bool IsIndirectSrc) { 3262 MachineFunction *MF = OrigBB.getParent(); 3263 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3264 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3265 MachineBasicBlock::iterator I = LoopBB.begin(); 3266 3267 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3268 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3269 Register NewExec = MRI.createVirtualRegister(BoolRC); 3270 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3271 Register CondReg = MRI.createVirtualRegister(BoolRC); 3272 3273 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3274 .addReg(InitReg) 3275 .addMBB(&OrigBB) 3276 .addReg(ResultReg) 3277 .addMBB(&LoopBB); 3278 3279 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3280 .addReg(InitSaveExecReg) 3281 .addMBB(&OrigBB) 3282 .addReg(NewExec) 3283 .addMBB(&LoopBB); 3284 3285 // Read the next variant <- also loop target. 3286 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3287 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3288 3289 // Compare the just read M0 value to all possible Idx values. 3290 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3291 .addReg(CurrentIdxReg) 3292 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3293 3294 // Update EXEC, save the original EXEC value to VCC. 3295 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3296 : AMDGPU::S_AND_SAVEEXEC_B64), 3297 NewExec) 3298 .addReg(CondReg, RegState::Kill); 3299 3300 MRI.setSimpleHint(NewExec, CondReg); 3301 3302 if (UseGPRIdxMode) { 3303 unsigned IdxReg; 3304 if (Offset == 0) { 3305 IdxReg = CurrentIdxReg; 3306 } else { 3307 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3308 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3309 .addReg(CurrentIdxReg, RegState::Kill) 3310 .addImm(Offset); 3311 } 3312 unsigned IdxMode = IsIndirectSrc ? 3313 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3314 MachineInstr *SetOn = 3315 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3316 .addReg(IdxReg, RegState::Kill) 3317 .addImm(IdxMode); 3318 SetOn->getOperand(3).setIsUndef(); 3319 } else { 3320 // Move index from VCC into M0 3321 if (Offset == 0) { 3322 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3323 .addReg(CurrentIdxReg, RegState::Kill); 3324 } else { 3325 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3326 .addReg(CurrentIdxReg, RegState::Kill) 3327 .addImm(Offset); 3328 } 3329 } 3330 3331 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3332 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3333 MachineInstr *InsertPt = 3334 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3335 : AMDGPU::S_XOR_B64_term), Exec) 3336 .addReg(Exec) 3337 .addReg(NewExec); 3338 3339 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3340 // s_cbranch_scc0? 3341 3342 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3343 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3344 .addMBB(&LoopBB); 3345 3346 return InsertPt->getIterator(); 3347 } 3348 3349 // This has slightly sub-optimal regalloc when the source vector is killed by 3350 // the read. The register allocator does not understand that the kill is 3351 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3352 // subregister from it, using 1 more VGPR than necessary. This was saved when 3353 // this was expanded after register allocation. 3354 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3355 MachineBasicBlock &MBB, 3356 MachineInstr &MI, 3357 unsigned InitResultReg, 3358 unsigned PhiReg, 3359 int Offset, 3360 bool UseGPRIdxMode, 3361 bool IsIndirectSrc) { 3362 MachineFunction *MF = MBB.getParent(); 3363 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3364 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3365 MachineRegisterInfo &MRI = MF->getRegInfo(); 3366 const DebugLoc &DL = MI.getDebugLoc(); 3367 MachineBasicBlock::iterator I(&MI); 3368 3369 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3370 Register DstReg = MI.getOperand(0).getReg(); 3371 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3372 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3373 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3374 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3375 3376 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3377 3378 // Save the EXEC mask 3379 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3380 .addReg(Exec); 3381 3382 MachineBasicBlock *LoopBB; 3383 MachineBasicBlock *RemainderBB; 3384 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3385 3386 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3387 3388 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3389 InitResultReg, DstReg, PhiReg, TmpExec, 3390 Offset, UseGPRIdxMode, IsIndirectSrc); 3391 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3392 MachineFunction::iterator MBBI(LoopBB); 3393 ++MBBI; 3394 MF->insert(MBBI, LandingPad); 3395 LoopBB->removeSuccessor(RemainderBB); 3396 LandingPad->addSuccessor(RemainderBB); 3397 LoopBB->addSuccessor(LandingPad); 3398 MachineBasicBlock::iterator First = LandingPad->begin(); 3399 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3400 .addReg(SaveExec); 3401 3402 return InsPt; 3403 } 3404 3405 // Returns subreg index, offset 3406 static std::pair<unsigned, int> 3407 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3408 const TargetRegisterClass *SuperRC, 3409 unsigned VecReg, 3410 int Offset) { 3411 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3412 3413 // Skip out of bounds offsets, or else we would end up using an undefined 3414 // register. 3415 if (Offset >= NumElts || Offset < 0) 3416 return std::make_pair(AMDGPU::sub0, Offset); 3417 3418 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3419 } 3420 3421 // Return true if the index is an SGPR and was set. 3422 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3423 MachineRegisterInfo &MRI, 3424 MachineInstr &MI, 3425 int Offset, 3426 bool UseGPRIdxMode, 3427 bool IsIndirectSrc) { 3428 MachineBasicBlock *MBB = MI.getParent(); 3429 const DebugLoc &DL = MI.getDebugLoc(); 3430 MachineBasicBlock::iterator I(&MI); 3431 3432 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3433 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3434 3435 assert(Idx->getReg() != AMDGPU::NoRegister); 3436 3437 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3438 return false; 3439 3440 if (UseGPRIdxMode) { 3441 unsigned IdxMode = IsIndirectSrc ? 3442 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3443 if (Offset == 0) { 3444 MachineInstr *SetOn = 3445 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3446 .add(*Idx) 3447 .addImm(IdxMode); 3448 3449 SetOn->getOperand(3).setIsUndef(); 3450 } else { 3451 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3452 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3453 .add(*Idx) 3454 .addImm(Offset); 3455 MachineInstr *SetOn = 3456 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3457 .addReg(Tmp, RegState::Kill) 3458 .addImm(IdxMode); 3459 3460 SetOn->getOperand(3).setIsUndef(); 3461 } 3462 3463 return true; 3464 } 3465 3466 if (Offset == 0) { 3467 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3468 .add(*Idx); 3469 } else { 3470 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3471 .add(*Idx) 3472 .addImm(Offset); 3473 } 3474 3475 return true; 3476 } 3477 3478 // Control flow needs to be inserted if indexing with a VGPR. 3479 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3480 MachineBasicBlock &MBB, 3481 const GCNSubtarget &ST) { 3482 const SIInstrInfo *TII = ST.getInstrInfo(); 3483 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3484 MachineFunction *MF = MBB.getParent(); 3485 MachineRegisterInfo &MRI = MF->getRegInfo(); 3486 3487 Register Dst = MI.getOperand(0).getReg(); 3488 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3489 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3490 3491 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3492 3493 unsigned SubReg; 3494 std::tie(SubReg, Offset) 3495 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3496 3497 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3498 3499 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3500 MachineBasicBlock::iterator I(&MI); 3501 const DebugLoc &DL = MI.getDebugLoc(); 3502 3503 if (UseGPRIdxMode) { 3504 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3505 // to avoid interfering with other uses, so probably requires a new 3506 // optimization pass. 3507 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3508 .addReg(SrcReg, RegState::Undef, SubReg) 3509 .addReg(SrcReg, RegState::Implicit) 3510 .addReg(AMDGPU::M0, RegState::Implicit); 3511 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3512 } else { 3513 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3514 .addReg(SrcReg, RegState::Undef, SubReg) 3515 .addReg(SrcReg, RegState::Implicit); 3516 } 3517 3518 MI.eraseFromParent(); 3519 3520 return &MBB; 3521 } 3522 3523 const DebugLoc &DL = MI.getDebugLoc(); 3524 MachineBasicBlock::iterator I(&MI); 3525 3526 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3527 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3528 3529 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3530 3531 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3532 Offset, UseGPRIdxMode, true); 3533 MachineBasicBlock *LoopBB = InsPt->getParent(); 3534 3535 if (UseGPRIdxMode) { 3536 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3537 .addReg(SrcReg, RegState::Undef, SubReg) 3538 .addReg(SrcReg, RegState::Implicit) 3539 .addReg(AMDGPU::M0, RegState::Implicit); 3540 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3541 } else { 3542 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3543 .addReg(SrcReg, RegState::Undef, SubReg) 3544 .addReg(SrcReg, RegState::Implicit); 3545 } 3546 3547 MI.eraseFromParent(); 3548 3549 return LoopBB; 3550 } 3551 3552 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3553 MachineBasicBlock &MBB, 3554 const GCNSubtarget &ST) { 3555 const SIInstrInfo *TII = ST.getInstrInfo(); 3556 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3557 MachineFunction *MF = MBB.getParent(); 3558 MachineRegisterInfo &MRI = MF->getRegInfo(); 3559 3560 Register Dst = MI.getOperand(0).getReg(); 3561 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3562 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3563 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3564 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3565 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3566 3567 // This can be an immediate, but will be folded later. 3568 assert(Val->getReg()); 3569 3570 unsigned SubReg; 3571 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3572 SrcVec->getReg(), 3573 Offset); 3574 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3575 3576 if (Idx->getReg() == AMDGPU::NoRegister) { 3577 MachineBasicBlock::iterator I(&MI); 3578 const DebugLoc &DL = MI.getDebugLoc(); 3579 3580 assert(Offset == 0); 3581 3582 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3583 .add(*SrcVec) 3584 .add(*Val) 3585 .addImm(SubReg); 3586 3587 MI.eraseFromParent(); 3588 return &MBB; 3589 } 3590 3591 const MCInstrDesc &MovRelDesc 3592 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3593 3594 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3595 MachineBasicBlock::iterator I(&MI); 3596 const DebugLoc &DL = MI.getDebugLoc(); 3597 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3598 .addReg(SrcVec->getReg()) 3599 .add(*Val) 3600 .addImm(SubReg); 3601 if (UseGPRIdxMode) 3602 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3603 3604 MI.eraseFromParent(); 3605 return &MBB; 3606 } 3607 3608 if (Val->isReg()) 3609 MRI.clearKillFlags(Val->getReg()); 3610 3611 const DebugLoc &DL = MI.getDebugLoc(); 3612 3613 Register PhiReg = MRI.createVirtualRegister(VecRC); 3614 3615 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3616 Offset, UseGPRIdxMode, false); 3617 MachineBasicBlock *LoopBB = InsPt->getParent(); 3618 3619 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3620 .addReg(PhiReg) 3621 .add(*Val) 3622 .addImm(AMDGPU::sub0); 3623 if (UseGPRIdxMode) 3624 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3625 3626 MI.eraseFromParent(); 3627 return LoopBB; 3628 } 3629 3630 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3631 MachineInstr &MI, MachineBasicBlock *BB) const { 3632 3633 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3634 MachineFunction *MF = BB->getParent(); 3635 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3636 3637 if (TII->isMIMG(MI)) { 3638 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3639 report_fatal_error("missing mem operand from MIMG instruction"); 3640 } 3641 // Add a memoperand for mimg instructions so that they aren't assumed to 3642 // be ordered memory instuctions. 3643 3644 return BB; 3645 } 3646 3647 switch (MI.getOpcode()) { 3648 case AMDGPU::S_UADDO_PSEUDO: 3649 case AMDGPU::S_USUBO_PSEUDO: { 3650 const DebugLoc &DL = MI.getDebugLoc(); 3651 MachineOperand &Dest0 = MI.getOperand(0); 3652 MachineOperand &Dest1 = MI.getOperand(1); 3653 MachineOperand &Src0 = MI.getOperand(2); 3654 MachineOperand &Src1 = MI.getOperand(3); 3655 3656 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3657 ? AMDGPU::S_ADD_I32 3658 : AMDGPU::S_SUB_I32; 3659 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3660 3661 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3662 .addImm(1) 3663 .addImm(0); 3664 3665 MI.eraseFromParent(); 3666 return BB; 3667 } 3668 case AMDGPU::S_ADD_U64_PSEUDO: 3669 case AMDGPU::S_SUB_U64_PSEUDO: { 3670 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3671 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3672 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3673 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3674 const DebugLoc &DL = MI.getDebugLoc(); 3675 3676 MachineOperand &Dest = MI.getOperand(0); 3677 MachineOperand &Src0 = MI.getOperand(1); 3678 MachineOperand &Src1 = MI.getOperand(2); 3679 3680 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3681 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3682 3683 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3684 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3685 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3686 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3687 3688 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3689 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3690 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3691 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3692 3693 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3694 3695 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3696 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3697 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3698 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3699 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3700 .addReg(DestSub0) 3701 .addImm(AMDGPU::sub0) 3702 .addReg(DestSub1) 3703 .addImm(AMDGPU::sub1); 3704 MI.eraseFromParent(); 3705 return BB; 3706 } 3707 case AMDGPU::V_ADD_U64_PSEUDO: 3708 case AMDGPU::V_SUB_U64_PSEUDO: { 3709 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3710 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3711 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3712 const DebugLoc &DL = MI.getDebugLoc(); 3713 3714 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3715 3716 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3717 3718 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3719 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3720 3721 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3722 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3723 3724 MachineOperand &Dest = MI.getOperand(0); 3725 MachineOperand &Src0 = MI.getOperand(1); 3726 MachineOperand &Src1 = MI.getOperand(2); 3727 3728 const TargetRegisterClass *Src0RC = Src0.isReg() 3729 ? MRI.getRegClass(Src0.getReg()) 3730 : &AMDGPU::VReg_64RegClass; 3731 const TargetRegisterClass *Src1RC = Src1.isReg() 3732 ? MRI.getRegClass(Src1.getReg()) 3733 : &AMDGPU::VReg_64RegClass; 3734 3735 const TargetRegisterClass *Src0SubRC = 3736 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3737 const TargetRegisterClass *Src1SubRC = 3738 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3739 3740 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3741 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3742 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3743 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3744 3745 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3746 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3747 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3748 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3749 3750 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64; 3751 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3752 .addReg(CarryReg, RegState::Define) 3753 .add(SrcReg0Sub0) 3754 .add(SrcReg1Sub0) 3755 .addImm(0); // clamp bit 3756 3757 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3758 MachineInstr *HiHalf = 3759 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3760 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3761 .add(SrcReg0Sub1) 3762 .add(SrcReg1Sub1) 3763 .addReg(CarryReg, RegState::Kill) 3764 .addImm(0); // clamp bit 3765 3766 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3767 .addReg(DestSub0) 3768 .addImm(AMDGPU::sub0) 3769 .addReg(DestSub1) 3770 .addImm(AMDGPU::sub1); 3771 TII->legalizeOperands(*LoHalf); 3772 TII->legalizeOperands(*HiHalf); 3773 MI.eraseFromParent(); 3774 return BB; 3775 } 3776 case AMDGPU::S_ADD_CO_PSEUDO: 3777 case AMDGPU::S_SUB_CO_PSEUDO: { 3778 // This pseudo has a chance to be selected 3779 // only from uniform add/subcarry node. All the VGPR operands 3780 // therefore assumed to be splat vectors. 3781 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3782 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3783 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3784 MachineBasicBlock::iterator MII = MI; 3785 const DebugLoc &DL = MI.getDebugLoc(); 3786 MachineOperand &Dest = MI.getOperand(0); 3787 MachineOperand &Src0 = MI.getOperand(2); 3788 MachineOperand &Src1 = MI.getOperand(3); 3789 MachineOperand &Src2 = MI.getOperand(4); 3790 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 3791 ? AMDGPU::S_ADDC_U32 3792 : AMDGPU::S_SUBB_U32; 3793 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 3794 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3795 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 3796 .addReg(Src0.getReg()); 3797 Src0.setReg(RegOp0); 3798 } 3799 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 3800 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3801 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 3802 .addReg(Src1.getReg()); 3803 Src1.setReg(RegOp1); 3804 } 3805 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3806 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 3807 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 3808 .addReg(Src2.getReg()); 3809 Src2.setReg(RegOp2); 3810 } 3811 3812 if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) { 3813 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 3814 .addReg(Src2.getReg()) 3815 .addImm(0); 3816 } else { 3817 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 3818 .addReg(Src2.getReg()) 3819 .addImm(0); 3820 } 3821 3822 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 3823 MI.eraseFromParent(); 3824 return BB; 3825 } 3826 case AMDGPU::SI_INIT_M0: { 3827 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3828 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3829 .add(MI.getOperand(0)); 3830 MI.eraseFromParent(); 3831 return BB; 3832 } 3833 case AMDGPU::SI_INIT_EXEC: 3834 // This should be before all vector instructions. 3835 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3836 AMDGPU::EXEC) 3837 .addImm(MI.getOperand(0).getImm()); 3838 MI.eraseFromParent(); 3839 return BB; 3840 3841 case AMDGPU::SI_INIT_EXEC_LO: 3842 // This should be before all vector instructions. 3843 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3844 AMDGPU::EXEC_LO) 3845 .addImm(MI.getOperand(0).getImm()); 3846 MI.eraseFromParent(); 3847 return BB; 3848 3849 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3850 // Extract the thread count from an SGPR input and set EXEC accordingly. 3851 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3852 // 3853 // S_BFE_U32 count, input, {shift, 7} 3854 // S_BFM_B64 exec, count, 0 3855 // S_CMP_EQ_U32 count, 64 3856 // S_CMOV_B64 exec, -1 3857 MachineInstr *FirstMI = &*BB->begin(); 3858 MachineRegisterInfo &MRI = MF->getRegInfo(); 3859 Register InputReg = MI.getOperand(0).getReg(); 3860 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3861 bool Found = false; 3862 3863 // Move the COPY of the input reg to the beginning, so that we can use it. 3864 for (auto I = BB->begin(); I != &MI; I++) { 3865 if (I->getOpcode() != TargetOpcode::COPY || 3866 I->getOperand(0).getReg() != InputReg) 3867 continue; 3868 3869 if (I == FirstMI) { 3870 FirstMI = &*++BB->begin(); 3871 } else { 3872 I->removeFromParent(); 3873 BB->insert(FirstMI, &*I); 3874 } 3875 Found = true; 3876 break; 3877 } 3878 assert(Found); 3879 (void)Found; 3880 3881 // This should be before all vector instructions. 3882 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3883 bool isWave32 = getSubtarget()->isWave32(); 3884 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3885 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3886 .addReg(InputReg) 3887 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3888 BuildMI(*BB, FirstMI, DebugLoc(), 3889 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3890 Exec) 3891 .addReg(CountReg) 3892 .addImm(0); 3893 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3894 .addReg(CountReg, RegState::Kill) 3895 .addImm(getSubtarget()->getWavefrontSize()); 3896 BuildMI(*BB, FirstMI, DebugLoc(), 3897 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3898 Exec) 3899 .addImm(-1); 3900 MI.eraseFromParent(); 3901 return BB; 3902 } 3903 3904 case AMDGPU::GET_GROUPSTATICSIZE: { 3905 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3906 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3907 DebugLoc DL = MI.getDebugLoc(); 3908 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3909 .add(MI.getOperand(0)) 3910 .addImm(MFI->getLDSSize()); 3911 MI.eraseFromParent(); 3912 return BB; 3913 } 3914 case AMDGPU::SI_INDIRECT_SRC_V1: 3915 case AMDGPU::SI_INDIRECT_SRC_V2: 3916 case AMDGPU::SI_INDIRECT_SRC_V4: 3917 case AMDGPU::SI_INDIRECT_SRC_V8: 3918 case AMDGPU::SI_INDIRECT_SRC_V16: 3919 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3920 case AMDGPU::SI_INDIRECT_DST_V1: 3921 case AMDGPU::SI_INDIRECT_DST_V2: 3922 case AMDGPU::SI_INDIRECT_DST_V4: 3923 case AMDGPU::SI_INDIRECT_DST_V8: 3924 case AMDGPU::SI_INDIRECT_DST_V16: 3925 return emitIndirectDst(MI, *BB, *getSubtarget()); 3926 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3927 case AMDGPU::SI_KILL_I1_PSEUDO: 3928 return splitKillBlock(MI, BB); 3929 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3930 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3931 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3932 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3933 3934 Register Dst = MI.getOperand(0).getReg(); 3935 Register Src0 = MI.getOperand(1).getReg(); 3936 Register Src1 = MI.getOperand(2).getReg(); 3937 const DebugLoc &DL = MI.getDebugLoc(); 3938 Register SrcCond = MI.getOperand(3).getReg(); 3939 3940 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3941 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3942 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3943 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3944 3945 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3946 .addReg(SrcCond); 3947 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3948 .addImm(0) 3949 .addReg(Src0, 0, AMDGPU::sub0) 3950 .addImm(0) 3951 .addReg(Src1, 0, AMDGPU::sub0) 3952 .addReg(SrcCondCopy); 3953 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3954 .addImm(0) 3955 .addReg(Src0, 0, AMDGPU::sub1) 3956 .addImm(0) 3957 .addReg(Src1, 0, AMDGPU::sub1) 3958 .addReg(SrcCondCopy); 3959 3960 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3961 .addReg(DstLo) 3962 .addImm(AMDGPU::sub0) 3963 .addReg(DstHi) 3964 .addImm(AMDGPU::sub1); 3965 MI.eraseFromParent(); 3966 return BB; 3967 } 3968 case AMDGPU::SI_BR_UNDEF: { 3969 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3970 const DebugLoc &DL = MI.getDebugLoc(); 3971 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3972 .add(MI.getOperand(0)); 3973 Br->getOperand(1).setIsUndef(true); // read undef SCC 3974 MI.eraseFromParent(); 3975 return BB; 3976 } 3977 case AMDGPU::ADJCALLSTACKUP: 3978 case AMDGPU::ADJCALLSTACKDOWN: { 3979 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3980 MachineInstrBuilder MIB(*MF, &MI); 3981 3982 // Add an implicit use of the frame offset reg to prevent the restore copy 3983 // inserted after the call from being reorderd after stack operations in the 3984 // the caller's frame. 3985 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3986 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3987 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3988 return BB; 3989 } 3990 case AMDGPU::SI_CALL_ISEL: { 3991 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3992 const DebugLoc &DL = MI.getDebugLoc(); 3993 3994 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3995 3996 MachineInstrBuilder MIB; 3997 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3998 3999 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4000 MIB.add(MI.getOperand(I)); 4001 4002 MIB.cloneMemRefs(MI); 4003 MI.eraseFromParent(); 4004 return BB; 4005 } 4006 case AMDGPU::V_ADD_I32_e32: 4007 case AMDGPU::V_SUB_I32_e32: 4008 case AMDGPU::V_SUBREV_I32_e32: { 4009 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4010 const DebugLoc &DL = MI.getDebugLoc(); 4011 unsigned Opc = MI.getOpcode(); 4012 4013 bool NeedClampOperand = false; 4014 if (TII->pseudoToMCOpcode(Opc) == -1) { 4015 Opc = AMDGPU::getVOPe64(Opc); 4016 NeedClampOperand = true; 4017 } 4018 4019 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4020 if (TII->isVOP3(*I)) { 4021 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4022 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4023 I.addReg(TRI->getVCC(), RegState::Define); 4024 } 4025 I.add(MI.getOperand(1)) 4026 .add(MI.getOperand(2)); 4027 if (NeedClampOperand) 4028 I.addImm(0); // clamp bit for e64 encoding 4029 4030 TII->legalizeOperands(*I); 4031 4032 MI.eraseFromParent(); 4033 return BB; 4034 } 4035 case AMDGPU::DS_GWS_INIT: 4036 case AMDGPU::DS_GWS_SEMA_V: 4037 case AMDGPU::DS_GWS_SEMA_BR: 4038 case AMDGPU::DS_GWS_SEMA_P: 4039 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4040 case AMDGPU::DS_GWS_BARRIER: 4041 // A s_waitcnt 0 is required to be the instruction immediately following. 4042 if (getSubtarget()->hasGWSAutoReplay()) { 4043 bundleInstWithWaitcnt(MI); 4044 return BB; 4045 } 4046 4047 return emitGWSMemViolTestLoop(MI, BB); 4048 default: 4049 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4050 } 4051 } 4052 4053 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4054 return isTypeLegal(VT.getScalarType()); 4055 } 4056 4057 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4058 // This currently forces unfolding various combinations of fsub into fma with 4059 // free fneg'd operands. As long as we have fast FMA (controlled by 4060 // isFMAFasterThanFMulAndFAdd), we should perform these. 4061 4062 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4063 // most of these combines appear to be cycle neutral but save on instruction 4064 // count / code size. 4065 return true; 4066 } 4067 4068 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4069 EVT VT) const { 4070 if (!VT.isVector()) { 4071 return MVT::i1; 4072 } 4073 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4074 } 4075 4076 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4077 // TODO: Should i16 be used always if legal? For now it would force VALU 4078 // shifts. 4079 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4080 } 4081 4082 // Answering this is somewhat tricky and depends on the specific device which 4083 // have different rates for fma or all f64 operations. 4084 // 4085 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4086 // regardless of which device (although the number of cycles differs between 4087 // devices), so it is always profitable for f64. 4088 // 4089 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4090 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4091 // which we can always do even without fused FP ops since it returns the same 4092 // result as the separate operations and since it is always full 4093 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4094 // however does not support denormals, so we do report fma as faster if we have 4095 // a fast fma device and require denormals. 4096 // 4097 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4098 EVT VT) const { 4099 VT = VT.getScalarType(); 4100 4101 switch (VT.getSimpleVT().SimpleTy) { 4102 case MVT::f32: { 4103 // This is as fast on some subtargets. However, we always have full rate f32 4104 // mad available which returns the same result as the separate operations 4105 // which we should prefer over fma. We can't use this if we want to support 4106 // denormals, so only report this in these cases. 4107 if (hasFP32Denormals(MF)) 4108 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4109 4110 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4111 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4112 } 4113 case MVT::f64: 4114 return true; 4115 case MVT::f16: 4116 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4117 default: 4118 break; 4119 } 4120 4121 return false; 4122 } 4123 4124 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4125 const SDNode *N) const { 4126 // TODO: Check future ftz flag 4127 // v_mad_f32/v_mac_f32 do not support denormals. 4128 EVT VT = N->getValueType(0); 4129 if (VT == MVT::f32) 4130 return !hasFP32Denormals(DAG.getMachineFunction()); 4131 if (VT == MVT::f16) { 4132 return Subtarget->hasMadF16() && 4133 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4134 } 4135 4136 return false; 4137 } 4138 4139 //===----------------------------------------------------------------------===// 4140 // Custom DAG Lowering Operations 4141 //===----------------------------------------------------------------------===// 4142 4143 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4144 // wider vector type is legal. 4145 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4146 SelectionDAG &DAG) const { 4147 unsigned Opc = Op.getOpcode(); 4148 EVT VT = Op.getValueType(); 4149 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4150 4151 SDValue Lo, Hi; 4152 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4153 4154 SDLoc SL(Op); 4155 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4156 Op->getFlags()); 4157 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4158 Op->getFlags()); 4159 4160 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4161 } 4162 4163 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4164 // wider vector type is legal. 4165 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4166 SelectionDAG &DAG) const { 4167 unsigned Opc = Op.getOpcode(); 4168 EVT VT = Op.getValueType(); 4169 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4170 4171 SDValue Lo0, Hi0; 4172 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4173 SDValue Lo1, Hi1; 4174 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4175 4176 SDLoc SL(Op); 4177 4178 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4179 Op->getFlags()); 4180 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4181 Op->getFlags()); 4182 4183 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4184 } 4185 4186 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4187 SelectionDAG &DAG) const { 4188 unsigned Opc = Op.getOpcode(); 4189 EVT VT = Op.getValueType(); 4190 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4191 4192 SDValue Lo0, Hi0; 4193 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4194 SDValue Lo1, Hi1; 4195 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4196 SDValue Lo2, Hi2; 4197 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4198 4199 SDLoc SL(Op); 4200 4201 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4202 Op->getFlags()); 4203 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4204 Op->getFlags()); 4205 4206 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4207 } 4208 4209 4210 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4211 switch (Op.getOpcode()) { 4212 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4213 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4214 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4215 case ISD::LOAD: { 4216 SDValue Result = LowerLOAD(Op, DAG); 4217 assert((!Result.getNode() || 4218 Result.getNode()->getNumValues() == 2) && 4219 "Load should return a value and a chain"); 4220 return Result; 4221 } 4222 4223 case ISD::FSIN: 4224 case ISD::FCOS: 4225 return LowerTrig(Op, DAG); 4226 case ISD::SELECT: return LowerSELECT(Op, DAG); 4227 case ISD::FDIV: return LowerFDIV(Op, DAG); 4228 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4229 case ISD::STORE: return LowerSTORE(Op, DAG); 4230 case ISD::GlobalAddress: { 4231 MachineFunction &MF = DAG.getMachineFunction(); 4232 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4233 return LowerGlobalAddress(MFI, Op, DAG); 4234 } 4235 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4236 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4237 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4238 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4239 case ISD::INSERT_SUBVECTOR: 4240 return lowerINSERT_SUBVECTOR(Op, DAG); 4241 case ISD::INSERT_VECTOR_ELT: 4242 return lowerINSERT_VECTOR_ELT(Op, DAG); 4243 case ISD::EXTRACT_VECTOR_ELT: 4244 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4245 case ISD::VECTOR_SHUFFLE: 4246 return lowerVECTOR_SHUFFLE(Op, DAG); 4247 case ISD::BUILD_VECTOR: 4248 return lowerBUILD_VECTOR(Op, DAG); 4249 case ISD::FP_ROUND: 4250 return lowerFP_ROUND(Op, DAG); 4251 case ISD::TRAP: 4252 return lowerTRAP(Op, DAG); 4253 case ISD::DEBUGTRAP: 4254 return lowerDEBUGTRAP(Op, DAG); 4255 case ISD::FABS: 4256 case ISD::FNEG: 4257 case ISD::FCANONICALIZE: 4258 case ISD::BSWAP: 4259 return splitUnaryVectorOp(Op, DAG); 4260 case ISD::FMINNUM: 4261 case ISD::FMAXNUM: 4262 return lowerFMINNUM_FMAXNUM(Op, DAG); 4263 case ISD::FMA: 4264 return splitTernaryVectorOp(Op, DAG); 4265 case ISD::SHL: 4266 case ISD::SRA: 4267 case ISD::SRL: 4268 case ISD::ADD: 4269 case ISD::SUB: 4270 case ISD::MUL: 4271 case ISD::SMIN: 4272 case ISD::SMAX: 4273 case ISD::UMIN: 4274 case ISD::UMAX: 4275 case ISD::FADD: 4276 case ISD::FMUL: 4277 case ISD::FMINNUM_IEEE: 4278 case ISD::FMAXNUM_IEEE: 4279 return splitBinaryVectorOp(Op, DAG); 4280 } 4281 return SDValue(); 4282 } 4283 4284 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4285 const SDLoc &DL, 4286 SelectionDAG &DAG, bool Unpacked) { 4287 if (!LoadVT.isVector()) 4288 return Result; 4289 4290 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4291 // Truncate to v2i16/v4i16. 4292 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4293 4294 // Workaround legalizer not scalarizing truncate after vector op 4295 // legalization byt not creating intermediate vector trunc. 4296 SmallVector<SDValue, 4> Elts; 4297 DAG.ExtractVectorElements(Result, Elts); 4298 for (SDValue &Elt : Elts) 4299 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4300 4301 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4302 4303 // Bitcast to original type (v2f16/v4f16). 4304 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4305 } 4306 4307 // Cast back to the original packed type. 4308 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4309 } 4310 4311 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4312 MemSDNode *M, 4313 SelectionDAG &DAG, 4314 ArrayRef<SDValue> Ops, 4315 bool IsIntrinsic) const { 4316 SDLoc DL(M); 4317 4318 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4319 EVT LoadVT = M->getValueType(0); 4320 4321 EVT EquivLoadVT = LoadVT; 4322 if (Unpacked && LoadVT.isVector()) { 4323 EquivLoadVT = LoadVT.isVector() ? 4324 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4325 LoadVT.getVectorNumElements()) : LoadVT; 4326 } 4327 4328 // Change from v4f16/v2f16 to EquivLoadVT. 4329 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4330 4331 SDValue Load 4332 = DAG.getMemIntrinsicNode( 4333 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4334 VTList, Ops, M->getMemoryVT(), 4335 M->getMemOperand()); 4336 if (!Unpacked) // Just adjusted the opcode. 4337 return Load; 4338 4339 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4340 4341 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4342 } 4343 4344 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4345 SelectionDAG &DAG, 4346 ArrayRef<SDValue> Ops) const { 4347 SDLoc DL(M); 4348 EVT LoadVT = M->getValueType(0); 4349 EVT EltType = LoadVT.getScalarType(); 4350 EVT IntVT = LoadVT.changeTypeToInteger(); 4351 4352 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4353 4354 unsigned Opc = 4355 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4356 4357 if (IsD16) { 4358 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4359 } 4360 4361 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4362 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4363 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4364 4365 if (isTypeLegal(LoadVT)) { 4366 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4367 M->getMemOperand(), DAG); 4368 } 4369 4370 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4371 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4372 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4373 M->getMemOperand(), DAG); 4374 return DAG.getMergeValues( 4375 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4376 DL); 4377 } 4378 4379 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4380 SDNode *N, SelectionDAG &DAG) { 4381 EVT VT = N->getValueType(0); 4382 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4383 int CondCode = CD->getSExtValue(); 4384 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4385 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4386 return DAG.getUNDEF(VT); 4387 4388 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4389 4390 SDValue LHS = N->getOperand(1); 4391 SDValue RHS = N->getOperand(2); 4392 4393 SDLoc DL(N); 4394 4395 EVT CmpVT = LHS.getValueType(); 4396 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4397 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4398 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4399 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4400 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4401 } 4402 4403 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4404 4405 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4406 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4407 4408 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4409 DAG.getCondCode(CCOpcode)); 4410 if (VT.bitsEq(CCVT)) 4411 return SetCC; 4412 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4413 } 4414 4415 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4416 SDNode *N, SelectionDAG &DAG) { 4417 EVT VT = N->getValueType(0); 4418 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4419 4420 int CondCode = CD->getSExtValue(); 4421 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4422 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4423 return DAG.getUNDEF(VT); 4424 } 4425 4426 SDValue Src0 = N->getOperand(1); 4427 SDValue Src1 = N->getOperand(2); 4428 EVT CmpVT = Src0.getValueType(); 4429 SDLoc SL(N); 4430 4431 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4432 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4433 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4434 } 4435 4436 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4437 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4438 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4439 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4440 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4441 Src1, DAG.getCondCode(CCOpcode)); 4442 if (VT.bitsEq(CCVT)) 4443 return SetCC; 4444 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4445 } 4446 4447 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4448 SelectionDAG &DAG) { 4449 EVT VT = N->getValueType(0); 4450 SDValue Src = N->getOperand(1); 4451 SDLoc SL(N); 4452 4453 if (Src.getOpcode() == ISD::SETCC) { 4454 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4455 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4456 Src.getOperand(1), Src.getOperand(2)); 4457 } 4458 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4459 // (ballot 0) -> 0 4460 if (Arg->isNullValue()) 4461 return DAG.getConstant(0, SL, VT); 4462 4463 // (ballot 1) -> EXEC/EXEC_LO 4464 if (Arg->isOne()) { 4465 Register Exec; 4466 if (VT.getScalarSizeInBits() == 32) 4467 Exec = AMDGPU::EXEC_LO; 4468 else if (VT.getScalarSizeInBits() == 64) 4469 Exec = AMDGPU::EXEC; 4470 else 4471 return SDValue(); 4472 4473 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4474 } 4475 } 4476 4477 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4478 // ISD::SETNE) 4479 return DAG.getNode( 4480 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4481 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4482 } 4483 4484 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4485 SmallVectorImpl<SDValue> &Results, 4486 SelectionDAG &DAG) const { 4487 switch (N->getOpcode()) { 4488 case ISD::INSERT_VECTOR_ELT: { 4489 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4490 Results.push_back(Res); 4491 return; 4492 } 4493 case ISD::EXTRACT_VECTOR_ELT: { 4494 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4495 Results.push_back(Res); 4496 return; 4497 } 4498 case ISD::INTRINSIC_WO_CHAIN: { 4499 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4500 switch (IID) { 4501 case Intrinsic::amdgcn_cvt_pkrtz: { 4502 SDValue Src0 = N->getOperand(1); 4503 SDValue Src1 = N->getOperand(2); 4504 SDLoc SL(N); 4505 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4506 Src0, Src1); 4507 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4508 return; 4509 } 4510 case Intrinsic::amdgcn_cvt_pknorm_i16: 4511 case Intrinsic::amdgcn_cvt_pknorm_u16: 4512 case Intrinsic::amdgcn_cvt_pk_i16: 4513 case Intrinsic::amdgcn_cvt_pk_u16: { 4514 SDValue Src0 = N->getOperand(1); 4515 SDValue Src1 = N->getOperand(2); 4516 SDLoc SL(N); 4517 unsigned Opcode; 4518 4519 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4520 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4521 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4522 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4523 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4524 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4525 else 4526 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4527 4528 EVT VT = N->getValueType(0); 4529 if (isTypeLegal(VT)) 4530 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4531 else { 4532 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4533 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4534 } 4535 return; 4536 } 4537 } 4538 break; 4539 } 4540 case ISD::INTRINSIC_W_CHAIN: { 4541 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4542 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4543 // FIXME: Hacky 4544 Results.push_back(Res.getOperand(0)); 4545 Results.push_back(Res.getOperand(1)); 4546 } else { 4547 Results.push_back(Res); 4548 Results.push_back(Res.getValue(1)); 4549 } 4550 return; 4551 } 4552 4553 break; 4554 } 4555 case ISD::SELECT: { 4556 SDLoc SL(N); 4557 EVT VT = N->getValueType(0); 4558 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4559 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4560 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4561 4562 EVT SelectVT = NewVT; 4563 if (NewVT.bitsLT(MVT::i32)) { 4564 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4565 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4566 SelectVT = MVT::i32; 4567 } 4568 4569 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4570 N->getOperand(0), LHS, RHS); 4571 4572 if (NewVT != SelectVT) 4573 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4574 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4575 return; 4576 } 4577 case ISD::FNEG: { 4578 if (N->getValueType(0) != MVT::v2f16) 4579 break; 4580 4581 SDLoc SL(N); 4582 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4583 4584 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4585 BC, 4586 DAG.getConstant(0x80008000, SL, MVT::i32)); 4587 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4588 return; 4589 } 4590 case ISD::FABS: { 4591 if (N->getValueType(0) != MVT::v2f16) 4592 break; 4593 4594 SDLoc SL(N); 4595 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4596 4597 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4598 BC, 4599 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4600 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4601 return; 4602 } 4603 default: 4604 break; 4605 } 4606 } 4607 4608 /// Helper function for LowerBRCOND 4609 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4610 4611 SDNode *Parent = Value.getNode(); 4612 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4613 I != E; ++I) { 4614 4615 if (I.getUse().get() != Value) 4616 continue; 4617 4618 if (I->getOpcode() == Opcode) 4619 return *I; 4620 } 4621 return nullptr; 4622 } 4623 4624 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4625 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4626 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4627 case Intrinsic::amdgcn_if: 4628 return AMDGPUISD::IF; 4629 case Intrinsic::amdgcn_else: 4630 return AMDGPUISD::ELSE; 4631 case Intrinsic::amdgcn_loop: 4632 return AMDGPUISD::LOOP; 4633 case Intrinsic::amdgcn_end_cf: 4634 llvm_unreachable("should not occur"); 4635 default: 4636 return 0; 4637 } 4638 } 4639 4640 // break, if_break, else_break are all only used as inputs to loop, not 4641 // directly as branch conditions. 4642 return 0; 4643 } 4644 4645 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4646 const Triple &TT = getTargetMachine().getTargetTriple(); 4647 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4648 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4649 AMDGPU::shouldEmitConstantsToTextSection(TT); 4650 } 4651 4652 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4653 // FIXME: Either avoid relying on address space here or change the default 4654 // address space for functions to avoid the explicit check. 4655 return (GV->getValueType()->isFunctionTy() || 4656 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4657 !shouldEmitFixup(GV) && 4658 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4659 } 4660 4661 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4662 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4663 } 4664 4665 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4666 if (!GV->hasExternalLinkage()) 4667 return true; 4668 4669 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4670 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4671 } 4672 4673 /// This transforms the control flow intrinsics to get the branch destination as 4674 /// last parameter, also switches branch target with BR if the need arise 4675 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4676 SelectionDAG &DAG) const { 4677 SDLoc DL(BRCOND); 4678 4679 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4680 SDValue Target = BRCOND.getOperand(2); 4681 SDNode *BR = nullptr; 4682 SDNode *SetCC = nullptr; 4683 4684 if (Intr->getOpcode() == ISD::SETCC) { 4685 // As long as we negate the condition everything is fine 4686 SetCC = Intr; 4687 Intr = SetCC->getOperand(0).getNode(); 4688 4689 } else { 4690 // Get the target from BR if we don't negate the condition 4691 BR = findUser(BRCOND, ISD::BR); 4692 Target = BR->getOperand(1); 4693 } 4694 4695 // FIXME: This changes the types of the intrinsics instead of introducing new 4696 // nodes with the correct types. 4697 // e.g. llvm.amdgcn.loop 4698 4699 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4700 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4701 4702 unsigned CFNode = isCFIntrinsic(Intr); 4703 if (CFNode == 0) { 4704 // This is a uniform branch so we don't need to legalize. 4705 return BRCOND; 4706 } 4707 4708 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4709 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4710 4711 assert(!SetCC || 4712 (SetCC->getConstantOperandVal(1) == 1 && 4713 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4714 ISD::SETNE)); 4715 4716 // operands of the new intrinsic call 4717 SmallVector<SDValue, 4> Ops; 4718 if (HaveChain) 4719 Ops.push_back(BRCOND.getOperand(0)); 4720 4721 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4722 Ops.push_back(Target); 4723 4724 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4725 4726 // build the new intrinsic call 4727 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4728 4729 if (!HaveChain) { 4730 SDValue Ops[] = { 4731 SDValue(Result, 0), 4732 BRCOND.getOperand(0) 4733 }; 4734 4735 Result = DAG.getMergeValues(Ops, DL).getNode(); 4736 } 4737 4738 if (BR) { 4739 // Give the branch instruction our target 4740 SDValue Ops[] = { 4741 BR->getOperand(0), 4742 BRCOND.getOperand(2) 4743 }; 4744 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4745 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4746 } 4747 4748 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4749 4750 // Copy the intrinsic results to registers 4751 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4752 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4753 if (!CopyToReg) 4754 continue; 4755 4756 Chain = DAG.getCopyToReg( 4757 Chain, DL, 4758 CopyToReg->getOperand(1), 4759 SDValue(Result, i - 1), 4760 SDValue()); 4761 4762 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4763 } 4764 4765 // Remove the old intrinsic from the chain 4766 DAG.ReplaceAllUsesOfValueWith( 4767 SDValue(Intr, Intr->getNumValues() - 1), 4768 Intr->getOperand(0)); 4769 4770 return Chain; 4771 } 4772 4773 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4774 SelectionDAG &DAG) const { 4775 MVT VT = Op.getSimpleValueType(); 4776 SDLoc DL(Op); 4777 // Checking the depth 4778 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4779 return DAG.getConstant(0, DL, VT); 4780 4781 MachineFunction &MF = DAG.getMachineFunction(); 4782 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4783 // Check for kernel and shader functions 4784 if (Info->isEntryFunction()) 4785 return DAG.getConstant(0, DL, VT); 4786 4787 MachineFrameInfo &MFI = MF.getFrameInfo(); 4788 // There is a call to @llvm.returnaddress in this function 4789 MFI.setReturnAddressIsTaken(true); 4790 4791 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4792 // Get the return address reg and mark it as an implicit live-in 4793 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4794 4795 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4796 } 4797 4798 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 4799 SDValue Op, 4800 const SDLoc &DL, 4801 EVT VT) const { 4802 return Op.getValueType().bitsLE(VT) ? 4803 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4804 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 4805 DAG.getTargetConstant(0, DL, MVT::i32)); 4806 } 4807 4808 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4809 assert(Op.getValueType() == MVT::f16 && 4810 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4811 4812 SDValue Src = Op.getOperand(0); 4813 EVT SrcVT = Src.getValueType(); 4814 if (SrcVT != MVT::f64) 4815 return Op; 4816 4817 SDLoc DL(Op); 4818 4819 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4820 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4821 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4822 } 4823 4824 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4825 SelectionDAG &DAG) const { 4826 EVT VT = Op.getValueType(); 4827 const MachineFunction &MF = DAG.getMachineFunction(); 4828 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4829 bool IsIEEEMode = Info->getMode().IEEE; 4830 4831 // FIXME: Assert during selection that this is only selected for 4832 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4833 // mode functions, but this happens to be OK since it's only done in cases 4834 // where there is known no sNaN. 4835 if (IsIEEEMode) 4836 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4837 4838 if (VT == MVT::v4f16) 4839 return splitBinaryVectorOp(Op, DAG); 4840 return Op; 4841 } 4842 4843 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4844 SDLoc SL(Op); 4845 SDValue Chain = Op.getOperand(0); 4846 4847 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4848 !Subtarget->isTrapHandlerEnabled()) 4849 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4850 4851 MachineFunction &MF = DAG.getMachineFunction(); 4852 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4853 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4854 assert(UserSGPR != AMDGPU::NoRegister); 4855 SDValue QueuePtr = CreateLiveInRegister( 4856 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4857 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4858 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4859 QueuePtr, SDValue()); 4860 SDValue Ops[] = { 4861 ToReg, 4862 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4863 SGPR01, 4864 ToReg.getValue(1) 4865 }; 4866 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4867 } 4868 4869 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4870 SDLoc SL(Op); 4871 SDValue Chain = Op.getOperand(0); 4872 MachineFunction &MF = DAG.getMachineFunction(); 4873 4874 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4875 !Subtarget->isTrapHandlerEnabled()) { 4876 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4877 "debugtrap handler not supported", 4878 Op.getDebugLoc(), 4879 DS_Warning); 4880 LLVMContext &Ctx = MF.getFunction().getContext(); 4881 Ctx.diagnose(NoTrap); 4882 return Chain; 4883 } 4884 4885 SDValue Ops[] = { 4886 Chain, 4887 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4888 }; 4889 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4890 } 4891 4892 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4893 SelectionDAG &DAG) const { 4894 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4895 if (Subtarget->hasApertureRegs()) { 4896 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4897 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4898 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4899 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4900 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4901 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4902 unsigned Encoding = 4903 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4904 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4905 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4906 4907 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4908 SDValue ApertureReg = SDValue( 4909 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4910 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4911 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4912 } 4913 4914 MachineFunction &MF = DAG.getMachineFunction(); 4915 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4916 Register UserSGPR = Info->getQueuePtrUserSGPR(); 4917 assert(UserSGPR != AMDGPU::NoRegister); 4918 4919 SDValue QueuePtr = CreateLiveInRegister( 4920 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4921 4922 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4923 // private_segment_aperture_base_hi. 4924 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4925 4926 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4927 4928 // TODO: Use custom target PseudoSourceValue. 4929 // TODO: We should use the value from the IR intrinsic call, but it might not 4930 // be available and how do we get it? 4931 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4932 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4933 MinAlign(64, StructOffset), 4934 MachineMemOperand::MODereferenceable | 4935 MachineMemOperand::MOInvariant); 4936 } 4937 4938 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4939 SelectionDAG &DAG) const { 4940 SDLoc SL(Op); 4941 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4942 4943 SDValue Src = ASC->getOperand(0); 4944 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4945 4946 const AMDGPUTargetMachine &TM = 4947 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4948 4949 // flat -> local/private 4950 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4951 unsigned DestAS = ASC->getDestAddressSpace(); 4952 4953 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4954 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4955 unsigned NullVal = TM.getNullPointerValue(DestAS); 4956 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4957 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4958 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4959 4960 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4961 NonNull, Ptr, SegmentNullPtr); 4962 } 4963 } 4964 4965 // local/private -> flat 4966 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4967 unsigned SrcAS = ASC->getSrcAddressSpace(); 4968 4969 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4970 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4971 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4972 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4973 4974 SDValue NonNull 4975 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4976 4977 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4978 SDValue CvtPtr 4979 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4980 4981 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4982 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4983 FlatNullPtr); 4984 } 4985 } 4986 4987 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 4988 Src.getValueType() == MVT::i64) 4989 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4990 4991 // global <-> flat are no-ops and never emitted. 4992 4993 const MachineFunction &MF = DAG.getMachineFunction(); 4994 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4995 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4996 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4997 4998 return DAG.getUNDEF(ASC->getValueType(0)); 4999 } 5000 5001 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5002 // the small vector and inserting them into the big vector. That is better than 5003 // the default expansion of doing it via a stack slot. Even though the use of 5004 // the stack slot would be optimized away afterwards, the stack slot itself 5005 // remains. 5006 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5007 SelectionDAG &DAG) const { 5008 SDValue Vec = Op.getOperand(0); 5009 SDValue Ins = Op.getOperand(1); 5010 SDValue Idx = Op.getOperand(2); 5011 EVT VecVT = Vec.getValueType(); 5012 EVT InsVT = Ins.getValueType(); 5013 EVT EltVT = VecVT.getVectorElementType(); 5014 unsigned InsNumElts = InsVT.getVectorNumElements(); 5015 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5016 SDLoc SL(Op); 5017 5018 for (unsigned I = 0; I != InsNumElts; ++I) { 5019 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5020 DAG.getConstant(I, SL, MVT::i32)); 5021 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5022 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5023 } 5024 return Vec; 5025 } 5026 5027 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5028 SelectionDAG &DAG) const { 5029 SDValue Vec = Op.getOperand(0); 5030 SDValue InsVal = Op.getOperand(1); 5031 SDValue Idx = Op.getOperand(2); 5032 EVT VecVT = Vec.getValueType(); 5033 EVT EltVT = VecVT.getVectorElementType(); 5034 unsigned VecSize = VecVT.getSizeInBits(); 5035 unsigned EltSize = EltVT.getSizeInBits(); 5036 5037 5038 assert(VecSize <= 64); 5039 5040 unsigned NumElts = VecVT.getVectorNumElements(); 5041 SDLoc SL(Op); 5042 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5043 5044 if (NumElts == 4 && EltSize == 16 && KIdx) { 5045 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5046 5047 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5048 DAG.getConstant(0, SL, MVT::i32)); 5049 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5050 DAG.getConstant(1, SL, MVT::i32)); 5051 5052 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5053 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5054 5055 unsigned Idx = KIdx->getZExtValue(); 5056 bool InsertLo = Idx < 2; 5057 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5058 InsertLo ? LoVec : HiVec, 5059 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5060 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5061 5062 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5063 5064 SDValue Concat = InsertLo ? 5065 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5066 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5067 5068 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5069 } 5070 5071 if (isa<ConstantSDNode>(Idx)) 5072 return SDValue(); 5073 5074 MVT IntVT = MVT::getIntegerVT(VecSize); 5075 5076 // Avoid stack access for dynamic indexing. 5077 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5078 5079 // Create a congruent vector with the target value in each element so that 5080 // the required element can be masked and ORed into the target vector. 5081 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5082 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5083 5084 assert(isPowerOf2_32(EltSize)); 5085 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5086 5087 // Convert vector index to bit-index. 5088 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5089 5090 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5091 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5092 DAG.getConstant(0xffff, SL, IntVT), 5093 ScaledIdx); 5094 5095 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5096 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5097 DAG.getNOT(SL, BFM, IntVT), BCVec); 5098 5099 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5100 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5101 } 5102 5103 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5104 SelectionDAG &DAG) const { 5105 SDLoc SL(Op); 5106 5107 EVT ResultVT = Op.getValueType(); 5108 SDValue Vec = Op.getOperand(0); 5109 SDValue Idx = Op.getOperand(1); 5110 EVT VecVT = Vec.getValueType(); 5111 unsigned VecSize = VecVT.getSizeInBits(); 5112 EVT EltVT = VecVT.getVectorElementType(); 5113 assert(VecSize <= 64); 5114 5115 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5116 5117 // Make sure we do any optimizations that will make it easier to fold 5118 // source modifiers before obscuring it with bit operations. 5119 5120 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5121 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5122 return Combined; 5123 5124 unsigned EltSize = EltVT.getSizeInBits(); 5125 assert(isPowerOf2_32(EltSize)); 5126 5127 MVT IntVT = MVT::getIntegerVT(VecSize); 5128 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5129 5130 // Convert vector index to bit-index (* EltSize) 5131 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5132 5133 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5134 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5135 5136 if (ResultVT == MVT::f16) { 5137 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5138 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5139 } 5140 5141 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5142 } 5143 5144 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5145 assert(Elt % 2 == 0); 5146 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5147 } 5148 5149 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5150 SelectionDAG &DAG) const { 5151 SDLoc SL(Op); 5152 EVT ResultVT = Op.getValueType(); 5153 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5154 5155 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5156 EVT EltVT = PackVT.getVectorElementType(); 5157 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5158 5159 // vector_shuffle <0,1,6,7> lhs, rhs 5160 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5161 // 5162 // vector_shuffle <6,7,2,3> lhs, rhs 5163 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5164 // 5165 // vector_shuffle <6,7,0,1> lhs, rhs 5166 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5167 5168 // Avoid scalarizing when both halves are reading from consecutive elements. 5169 SmallVector<SDValue, 4> Pieces; 5170 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5171 if (elementPairIsContiguous(SVN->getMask(), I)) { 5172 const int Idx = SVN->getMaskElt(I); 5173 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5174 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5175 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5176 PackVT, SVN->getOperand(VecIdx), 5177 DAG.getConstant(EltIdx, SL, MVT::i32)); 5178 Pieces.push_back(SubVec); 5179 } else { 5180 const int Idx0 = SVN->getMaskElt(I); 5181 const int Idx1 = SVN->getMaskElt(I + 1); 5182 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5183 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5184 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5185 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5186 5187 SDValue Vec0 = SVN->getOperand(VecIdx0); 5188 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5189 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5190 5191 SDValue Vec1 = SVN->getOperand(VecIdx1); 5192 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5193 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5194 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5195 } 5196 } 5197 5198 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5199 } 5200 5201 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5202 SelectionDAG &DAG) const { 5203 SDLoc SL(Op); 5204 EVT VT = Op.getValueType(); 5205 5206 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5207 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5208 5209 // Turn into pair of packed build_vectors. 5210 // TODO: Special case for constants that can be materialized with s_mov_b64. 5211 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5212 { Op.getOperand(0), Op.getOperand(1) }); 5213 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5214 { Op.getOperand(2), Op.getOperand(3) }); 5215 5216 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5217 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5218 5219 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5220 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5221 } 5222 5223 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5224 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5225 5226 SDValue Lo = Op.getOperand(0); 5227 SDValue Hi = Op.getOperand(1); 5228 5229 // Avoid adding defined bits with the zero_extend. 5230 if (Hi.isUndef()) { 5231 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5232 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5233 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5234 } 5235 5236 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5237 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5238 5239 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5240 DAG.getConstant(16, SL, MVT::i32)); 5241 if (Lo.isUndef()) 5242 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5243 5244 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5245 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5246 5247 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5248 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5249 } 5250 5251 bool 5252 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5253 // We can fold offsets for anything that doesn't require a GOT relocation. 5254 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5255 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5256 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5257 !shouldEmitGOTReloc(GA->getGlobal()); 5258 } 5259 5260 static SDValue 5261 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5262 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5263 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5264 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5265 // lowered to the following code sequence: 5266 // 5267 // For constant address space: 5268 // s_getpc_b64 s[0:1] 5269 // s_add_u32 s0, s0, $symbol 5270 // s_addc_u32 s1, s1, 0 5271 // 5272 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5273 // a fixup or relocation is emitted to replace $symbol with a literal 5274 // constant, which is a pc-relative offset from the encoding of the $symbol 5275 // operand to the global variable. 5276 // 5277 // For global address space: 5278 // s_getpc_b64 s[0:1] 5279 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5280 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5281 // 5282 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5283 // fixups or relocations are emitted to replace $symbol@*@lo and 5284 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5285 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5286 // operand to the global variable. 5287 // 5288 // What we want here is an offset from the value returned by s_getpc 5289 // (which is the address of the s_add_u32 instruction) to the global 5290 // variable, but since the encoding of $symbol starts 4 bytes after the start 5291 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5292 // small. This requires us to add 4 to the global variable offset in order to 5293 // compute the correct address. 5294 SDValue PtrLo = 5295 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5296 SDValue PtrHi; 5297 if (GAFlags == SIInstrInfo::MO_NONE) { 5298 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5299 } else { 5300 PtrHi = 5301 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5302 } 5303 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5304 } 5305 5306 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5307 SDValue Op, 5308 SelectionDAG &DAG) const { 5309 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5310 const GlobalValue *GV = GSD->getGlobal(); 5311 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5312 shouldUseLDSConstAddress(GV)) || 5313 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5314 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5315 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5316 5317 SDLoc DL(GSD); 5318 EVT PtrVT = Op.getValueType(); 5319 5320 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5321 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5322 SIInstrInfo::MO_ABS32_LO); 5323 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5324 } 5325 5326 if (shouldEmitFixup(GV)) 5327 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5328 else if (shouldEmitPCReloc(GV)) 5329 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5330 SIInstrInfo::MO_REL32); 5331 5332 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5333 SIInstrInfo::MO_GOTPCREL32); 5334 5335 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5336 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5337 const DataLayout &DataLayout = DAG.getDataLayout(); 5338 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5339 MachinePointerInfo PtrInfo 5340 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5341 5342 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5343 MachineMemOperand::MODereferenceable | 5344 MachineMemOperand::MOInvariant); 5345 } 5346 5347 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5348 const SDLoc &DL, SDValue V) const { 5349 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5350 // the destination register. 5351 // 5352 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5353 // so we will end up with redundant moves to m0. 5354 // 5355 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5356 5357 // A Null SDValue creates a glue result. 5358 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5359 V, Chain); 5360 return SDValue(M0, 0); 5361 } 5362 5363 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5364 SDValue Op, 5365 MVT VT, 5366 unsigned Offset) const { 5367 SDLoc SL(Op); 5368 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5369 DAG.getEntryNode(), Offset, 4, false); 5370 // The local size values will have the hi 16-bits as zero. 5371 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5372 DAG.getValueType(VT)); 5373 } 5374 5375 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5376 EVT VT) { 5377 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5378 "non-hsa intrinsic with hsa target", 5379 DL.getDebugLoc()); 5380 DAG.getContext()->diagnose(BadIntrin); 5381 return DAG.getUNDEF(VT); 5382 } 5383 5384 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5385 EVT VT) { 5386 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5387 "intrinsic not supported on subtarget", 5388 DL.getDebugLoc()); 5389 DAG.getContext()->diagnose(BadIntrin); 5390 return DAG.getUNDEF(VT); 5391 } 5392 5393 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5394 ArrayRef<SDValue> Elts) { 5395 assert(!Elts.empty()); 5396 MVT Type; 5397 unsigned NumElts; 5398 5399 if (Elts.size() == 1) { 5400 Type = MVT::f32; 5401 NumElts = 1; 5402 } else if (Elts.size() == 2) { 5403 Type = MVT::v2f32; 5404 NumElts = 2; 5405 } else if (Elts.size() == 3) { 5406 Type = MVT::v3f32; 5407 NumElts = 3; 5408 } else if (Elts.size() <= 4) { 5409 Type = MVT::v4f32; 5410 NumElts = 4; 5411 } else if (Elts.size() <= 8) { 5412 Type = MVT::v8f32; 5413 NumElts = 8; 5414 } else { 5415 assert(Elts.size() <= 16); 5416 Type = MVT::v16f32; 5417 NumElts = 16; 5418 } 5419 5420 SmallVector<SDValue, 16> VecElts(NumElts); 5421 for (unsigned i = 0; i < Elts.size(); ++i) { 5422 SDValue Elt = Elts[i]; 5423 if (Elt.getValueType() != MVT::f32) 5424 Elt = DAG.getBitcast(MVT::f32, Elt); 5425 VecElts[i] = Elt; 5426 } 5427 for (unsigned i = Elts.size(); i < NumElts; ++i) 5428 VecElts[i] = DAG.getUNDEF(MVT::f32); 5429 5430 if (NumElts == 1) 5431 return VecElts[0]; 5432 return DAG.getBuildVector(Type, DL, VecElts); 5433 } 5434 5435 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5436 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5437 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5438 5439 uint64_t Value = CachePolicyConst->getZExtValue(); 5440 SDLoc DL(CachePolicy); 5441 if (GLC) { 5442 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5443 Value &= ~(uint64_t)0x1; 5444 } 5445 if (SLC) { 5446 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5447 Value &= ~(uint64_t)0x2; 5448 } 5449 if (DLC) { 5450 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5451 Value &= ~(uint64_t)0x4; 5452 } 5453 5454 return Value == 0; 5455 } 5456 5457 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5458 SDValue Src, int ExtraElts) { 5459 EVT SrcVT = Src.getValueType(); 5460 5461 SmallVector<SDValue, 8> Elts; 5462 5463 if (SrcVT.isVector()) 5464 DAG.ExtractVectorElements(Src, Elts); 5465 else 5466 Elts.push_back(Src); 5467 5468 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5469 while (ExtraElts--) 5470 Elts.push_back(Undef); 5471 5472 return DAG.getBuildVector(CastVT, DL, Elts); 5473 } 5474 5475 // Re-construct the required return value for a image load intrinsic. 5476 // This is more complicated due to the optional use TexFailCtrl which means the required 5477 // return type is an aggregate 5478 static SDValue constructRetValue(SelectionDAG &DAG, 5479 MachineSDNode *Result, 5480 ArrayRef<EVT> ResultTypes, 5481 bool IsTexFail, bool Unpacked, bool IsD16, 5482 int DMaskPop, int NumVDataDwords, 5483 const SDLoc &DL, LLVMContext &Context) { 5484 // Determine the required return type. This is the same regardless of IsTexFail flag 5485 EVT ReqRetVT = ResultTypes[0]; 5486 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5487 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5488 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5489 5490 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5491 DMaskPop : (DMaskPop + 1) / 2; 5492 5493 MVT DataDwordVT = NumDataDwords == 1 ? 5494 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5495 5496 MVT MaskPopVT = MaskPopDwords == 1 ? 5497 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5498 5499 SDValue Data(Result, 0); 5500 SDValue TexFail; 5501 5502 if (IsTexFail) { 5503 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5504 if (MaskPopVT.isVector()) { 5505 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5506 SDValue(Result, 0), ZeroIdx); 5507 } else { 5508 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5509 SDValue(Result, 0), ZeroIdx); 5510 } 5511 5512 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5513 SDValue(Result, 0), 5514 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5515 } 5516 5517 if (DataDwordVT.isVector()) 5518 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5519 NumDataDwords - MaskPopDwords); 5520 5521 if (IsD16) 5522 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5523 5524 if (!ReqRetVT.isVector()) 5525 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5526 5527 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5528 5529 if (TexFail) 5530 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5531 5532 if (Result->getNumValues() == 1) 5533 return Data; 5534 5535 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5536 } 5537 5538 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5539 SDValue *LWE, bool &IsTexFail) { 5540 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5541 5542 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5543 if (Value) { 5544 IsTexFail = true; 5545 } 5546 5547 SDLoc DL(TexFailCtrlConst); 5548 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5549 Value &= ~(uint64_t)0x1; 5550 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5551 Value &= ~(uint64_t)0x2; 5552 5553 return Value == 0; 5554 } 5555 5556 SDValue SITargetLowering::lowerImage(SDValue Op, 5557 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5558 SelectionDAG &DAG) const { 5559 SDLoc DL(Op); 5560 MachineFunction &MF = DAG.getMachineFunction(); 5561 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5562 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5563 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5564 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5565 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5566 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5567 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5568 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5569 unsigned IntrOpcode = Intr->BaseOpcode; 5570 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5571 5572 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5573 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5574 bool IsD16 = false; 5575 bool IsA16 = false; 5576 SDValue VData; 5577 int NumVDataDwords; 5578 bool AdjustRetType = false; 5579 5580 unsigned AddrIdx; // Index of first address argument 5581 unsigned DMask; 5582 unsigned DMaskLanes = 0; 5583 5584 if (BaseOpcode->Atomic) { 5585 VData = Op.getOperand(2); 5586 5587 bool Is64Bit = VData.getValueType() == MVT::i64; 5588 if (BaseOpcode->AtomicX2) { 5589 SDValue VData2 = Op.getOperand(3); 5590 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5591 {VData, VData2}); 5592 if (Is64Bit) 5593 VData = DAG.getBitcast(MVT::v4i32, VData); 5594 5595 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5596 DMask = Is64Bit ? 0xf : 0x3; 5597 NumVDataDwords = Is64Bit ? 4 : 2; 5598 AddrIdx = 4; 5599 } else { 5600 DMask = Is64Bit ? 0x3 : 0x1; 5601 NumVDataDwords = Is64Bit ? 2 : 1; 5602 AddrIdx = 3; 5603 } 5604 } else { 5605 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5606 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5607 DMask = DMaskConst->getZExtValue(); 5608 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5609 5610 if (BaseOpcode->Store) { 5611 VData = Op.getOperand(2); 5612 5613 MVT StoreVT = VData.getSimpleValueType(); 5614 if (StoreVT.getScalarType() == MVT::f16) { 5615 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5616 return Op; // D16 is unsupported for this instruction 5617 5618 IsD16 = true; 5619 VData = handleD16VData(VData, DAG); 5620 } 5621 5622 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5623 } else { 5624 // Work out the num dwords based on the dmask popcount and underlying type 5625 // and whether packing is supported. 5626 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5627 if (LoadVT.getScalarType() == MVT::f16) { 5628 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5629 return Op; // D16 is unsupported for this instruction 5630 5631 IsD16 = true; 5632 } 5633 5634 // Confirm that the return type is large enough for the dmask specified 5635 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5636 (!LoadVT.isVector() && DMaskLanes > 1)) 5637 return Op; 5638 5639 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5640 NumVDataDwords = (DMaskLanes + 1) / 2; 5641 else 5642 NumVDataDwords = DMaskLanes; 5643 5644 AdjustRetType = true; 5645 } 5646 5647 AddrIdx = DMaskIdx + 1; 5648 } 5649 5650 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5651 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5652 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5653 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5654 NumCoords + NumLCM; 5655 unsigned NumMIVAddrs = NumVAddrs; 5656 5657 SmallVector<SDValue, 4> VAddrs; 5658 5659 // Optimize _L to _LZ when _L is zero 5660 if (LZMappingInfo) { 5661 if (auto ConstantLod = 5662 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5663 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5664 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5665 NumMIVAddrs--; // remove 'lod' 5666 } 5667 } 5668 } 5669 5670 // Optimize _mip away, when 'lod' is zero 5671 if (MIPMappingInfo) { 5672 if (auto ConstantLod = 5673 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5674 if (ConstantLod->isNullValue()) { 5675 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5676 NumMIVAddrs--; // remove 'lod' 5677 } 5678 } 5679 } 5680 5681 // Check for 16 bit addresses and pack if true. 5682 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5683 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5684 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5685 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5686 // Illegal to use a16 images 5687 if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16)) 5688 return Op; 5689 5690 IsA16 = true; 5691 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5692 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5693 SDValue AddrLo; 5694 // Push back extra arguments. 5695 if (i < DimIdx) { 5696 AddrLo = Op.getOperand(i); 5697 } else { 5698 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5699 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5700 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5701 ((NumGradients / 2) % 2 == 1 && 5702 (i == DimIdx + (NumGradients / 2) - 1 || 5703 i == DimIdx + NumGradients - 1))) { 5704 AddrLo = Op.getOperand(i); 5705 if (AddrLo.getValueType() != MVT::i16) 5706 AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i)); 5707 AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo); 5708 } else { 5709 AddrLo = DAG.getBuildVector(VectorVT, DL, 5710 {Op.getOperand(i), Op.getOperand(i + 1)}); 5711 i++; 5712 } 5713 AddrLo = DAG.getBitcast(MVT::f32, AddrLo); 5714 } 5715 VAddrs.push_back(AddrLo); 5716 } 5717 } else { 5718 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5719 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5720 } 5721 5722 // If the register allocator cannot place the address registers contiguously 5723 // without introducing moves, then using the non-sequential address encoding 5724 // is always preferable, since it saves VALU instructions and is usually a 5725 // wash in terms of code size or even better. 5726 // 5727 // However, we currently have no way of hinting to the register allocator that 5728 // MIMG addresses should be placed contiguously when it is possible to do so, 5729 // so force non-NSA for the common 2-address case as a heuristic. 5730 // 5731 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5732 // allocation when possible. 5733 bool UseNSA = 5734 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5735 SDValue VAddr; 5736 if (!UseNSA) 5737 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5738 5739 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5740 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5741 unsigned CtrlIdx; // Index of texfailctrl argument 5742 SDValue Unorm; 5743 if (!BaseOpcode->Sampler) { 5744 Unorm = True; 5745 CtrlIdx = AddrIdx + NumVAddrs + 1; 5746 } else { 5747 auto UnormConst = 5748 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5749 5750 Unorm = UnormConst->getZExtValue() ? True : False; 5751 CtrlIdx = AddrIdx + NumVAddrs + 3; 5752 } 5753 5754 SDValue TFE; 5755 SDValue LWE; 5756 SDValue TexFail = Op.getOperand(CtrlIdx); 5757 bool IsTexFail = false; 5758 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5759 return Op; 5760 5761 if (IsTexFail) { 5762 if (!DMaskLanes) { 5763 // Expecting to get an error flag since TFC is on - and dmask is 0 5764 // Force dmask to be at least 1 otherwise the instruction will fail 5765 DMask = 0x1; 5766 DMaskLanes = 1; 5767 NumVDataDwords = 1; 5768 } 5769 NumVDataDwords += 1; 5770 AdjustRetType = true; 5771 } 5772 5773 // Has something earlier tagged that the return type needs adjusting 5774 // This happens if the instruction is a load or has set TexFailCtrl flags 5775 if (AdjustRetType) { 5776 // NumVDataDwords reflects the true number of dwords required in the return type 5777 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5778 // This is a no-op load. This can be eliminated 5779 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5780 if (isa<MemSDNode>(Op)) 5781 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5782 return Undef; 5783 } 5784 5785 EVT NewVT = NumVDataDwords > 1 ? 5786 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5787 : MVT::i32; 5788 5789 ResultTypes[0] = NewVT; 5790 if (ResultTypes.size() == 3) { 5791 // Original result was aggregate type used for TexFailCtrl results 5792 // The actual instruction returns as a vector type which has now been 5793 // created. Remove the aggregate result. 5794 ResultTypes.erase(&ResultTypes[1]); 5795 } 5796 } 5797 5798 SDValue GLC; 5799 SDValue SLC; 5800 SDValue DLC; 5801 if (BaseOpcode->Atomic) { 5802 GLC = True; // TODO no-return optimization 5803 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5804 IsGFX10 ? &DLC : nullptr)) 5805 return Op; 5806 } else { 5807 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5808 IsGFX10 ? &DLC : nullptr)) 5809 return Op; 5810 } 5811 5812 SmallVector<SDValue, 26> Ops; 5813 if (BaseOpcode->Store || BaseOpcode->Atomic) 5814 Ops.push_back(VData); // vdata 5815 if (UseNSA) { 5816 for (const SDValue &Addr : VAddrs) 5817 Ops.push_back(Addr); 5818 } else { 5819 Ops.push_back(VAddr); 5820 } 5821 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5822 if (BaseOpcode->Sampler) 5823 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5824 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5825 if (IsGFX10) 5826 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5827 Ops.push_back(Unorm); 5828 if (IsGFX10) 5829 Ops.push_back(DLC); 5830 Ops.push_back(GLC); 5831 Ops.push_back(SLC); 5832 Ops.push_back(IsA16 && // r128, a16 for gfx9 5833 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5834 if (IsGFX10) 5835 Ops.push_back(IsA16 ? True : False); 5836 Ops.push_back(TFE); 5837 Ops.push_back(LWE); 5838 if (!IsGFX10) 5839 Ops.push_back(DimInfo->DA ? True : False); 5840 if (BaseOpcode->HasD16) 5841 Ops.push_back(IsD16 ? True : False); 5842 if (isa<MemSDNode>(Op)) 5843 Ops.push_back(Op.getOperand(0)); // chain 5844 5845 int NumVAddrDwords = 5846 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5847 int Opcode = -1; 5848 5849 if (IsGFX10) { 5850 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5851 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5852 : AMDGPU::MIMGEncGfx10Default, 5853 NumVDataDwords, NumVAddrDwords); 5854 } else { 5855 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5856 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5857 NumVDataDwords, NumVAddrDwords); 5858 if (Opcode == -1) 5859 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5860 NumVDataDwords, NumVAddrDwords); 5861 } 5862 assert(Opcode != -1); 5863 5864 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5865 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5866 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5867 DAG.setNodeMemRefs(NewNode, {MemRef}); 5868 } 5869 5870 if (BaseOpcode->AtomicX2) { 5871 SmallVector<SDValue, 1> Elt; 5872 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5873 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5874 } else if (!BaseOpcode->Store) { 5875 return constructRetValue(DAG, NewNode, 5876 OrigResultTypes, IsTexFail, 5877 Subtarget->hasUnpackedD16VMem(), IsD16, 5878 DMaskLanes, NumVDataDwords, DL, 5879 *DAG.getContext()); 5880 } 5881 5882 return SDValue(NewNode, 0); 5883 } 5884 5885 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5886 SDValue Offset, SDValue CachePolicy, 5887 SelectionDAG &DAG) const { 5888 MachineFunction &MF = DAG.getMachineFunction(); 5889 5890 const DataLayout &DataLayout = DAG.getDataLayout(); 5891 Align Alignment = 5892 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 5893 5894 MachineMemOperand *MMO = MF.getMachineMemOperand( 5895 MachinePointerInfo(), 5896 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5897 MachineMemOperand::MOInvariant, 5898 VT.getStoreSize(), Alignment); 5899 5900 if (!Offset->isDivergent()) { 5901 SDValue Ops[] = { 5902 Rsrc, 5903 Offset, // Offset 5904 CachePolicy 5905 }; 5906 5907 // Widen vec3 load to vec4. 5908 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5909 EVT WidenedVT = 5910 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5911 auto WidenedOp = DAG.getMemIntrinsicNode( 5912 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5913 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5914 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5915 DAG.getVectorIdxConstant(0, DL)); 5916 return Subvector; 5917 } 5918 5919 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5920 DAG.getVTList(VT), Ops, VT, MMO); 5921 } 5922 5923 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5924 // assume that the buffer is unswizzled. 5925 SmallVector<SDValue, 4> Loads; 5926 unsigned NumLoads = 1; 5927 MVT LoadVT = VT.getSimpleVT(); 5928 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5929 assert((LoadVT.getScalarType() == MVT::i32 || 5930 LoadVT.getScalarType() == MVT::f32)); 5931 5932 if (NumElts == 8 || NumElts == 16) { 5933 NumLoads = NumElts / 4; 5934 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5935 } 5936 5937 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5938 SDValue Ops[] = { 5939 DAG.getEntryNode(), // Chain 5940 Rsrc, // rsrc 5941 DAG.getConstant(0, DL, MVT::i32), // vindex 5942 {}, // voffset 5943 {}, // soffset 5944 {}, // offset 5945 CachePolicy, // cachepolicy 5946 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5947 }; 5948 5949 // Use the alignment to ensure that the required offsets will fit into the 5950 // immediate offsets. 5951 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5952 5953 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5954 for (unsigned i = 0; i < NumLoads; ++i) { 5955 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5956 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5957 LoadVT, MMO, DAG)); 5958 } 5959 5960 if (NumElts == 8 || NumElts == 16) 5961 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5962 5963 return Loads[0]; 5964 } 5965 5966 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5967 SelectionDAG &DAG) const { 5968 MachineFunction &MF = DAG.getMachineFunction(); 5969 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5970 5971 EVT VT = Op.getValueType(); 5972 SDLoc DL(Op); 5973 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5974 5975 // TODO: Should this propagate fast-math-flags? 5976 5977 switch (IntrinsicID) { 5978 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5979 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5980 return emitNonHSAIntrinsicError(DAG, DL, VT); 5981 return getPreloadedValue(DAG, *MFI, VT, 5982 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5983 } 5984 case Intrinsic::amdgcn_dispatch_ptr: 5985 case Intrinsic::amdgcn_queue_ptr: { 5986 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5987 DiagnosticInfoUnsupported BadIntrin( 5988 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5989 DL.getDebugLoc()); 5990 DAG.getContext()->diagnose(BadIntrin); 5991 return DAG.getUNDEF(VT); 5992 } 5993 5994 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5995 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5996 return getPreloadedValue(DAG, *MFI, VT, RegID); 5997 } 5998 case Intrinsic::amdgcn_implicitarg_ptr: { 5999 if (MFI->isEntryFunction()) 6000 return getImplicitArgPtr(DAG, DL); 6001 return getPreloadedValue(DAG, *MFI, VT, 6002 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6003 } 6004 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6005 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6006 // This only makes sense to call in a kernel, so just lower to null. 6007 return DAG.getConstant(0, DL, VT); 6008 } 6009 6010 return getPreloadedValue(DAG, *MFI, VT, 6011 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6012 } 6013 case Intrinsic::amdgcn_dispatch_id: { 6014 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6015 } 6016 case Intrinsic::amdgcn_rcp: 6017 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6018 case Intrinsic::amdgcn_rsq: 6019 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6020 case Intrinsic::amdgcn_rsq_legacy: 6021 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6022 return emitRemovedIntrinsicError(DAG, DL, VT); 6023 return SDValue(); 6024 case Intrinsic::amdgcn_rcp_legacy: 6025 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6026 return emitRemovedIntrinsicError(DAG, DL, VT); 6027 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6028 case Intrinsic::amdgcn_rsq_clamp: { 6029 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6030 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6031 6032 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6033 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6034 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6035 6036 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6037 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6038 DAG.getConstantFP(Max, DL, VT)); 6039 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6040 DAG.getConstantFP(Min, DL, VT)); 6041 } 6042 case Intrinsic::r600_read_ngroups_x: 6043 if (Subtarget->isAmdHsaOS()) 6044 return emitNonHSAIntrinsicError(DAG, DL, VT); 6045 6046 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6047 SI::KernelInputOffsets::NGROUPS_X, 4, false); 6048 case Intrinsic::r600_read_ngroups_y: 6049 if (Subtarget->isAmdHsaOS()) 6050 return emitNonHSAIntrinsicError(DAG, DL, VT); 6051 6052 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6053 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 6054 case Intrinsic::r600_read_ngroups_z: 6055 if (Subtarget->isAmdHsaOS()) 6056 return emitNonHSAIntrinsicError(DAG, DL, VT); 6057 6058 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6059 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 6060 case Intrinsic::r600_read_global_size_x: 6061 if (Subtarget->isAmdHsaOS()) 6062 return emitNonHSAIntrinsicError(DAG, DL, VT); 6063 6064 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6065 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 6066 case Intrinsic::r600_read_global_size_y: 6067 if (Subtarget->isAmdHsaOS()) 6068 return emitNonHSAIntrinsicError(DAG, DL, VT); 6069 6070 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6071 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 6072 case Intrinsic::r600_read_global_size_z: 6073 if (Subtarget->isAmdHsaOS()) 6074 return emitNonHSAIntrinsicError(DAG, DL, VT); 6075 6076 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6077 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 6078 case Intrinsic::r600_read_local_size_x: 6079 if (Subtarget->isAmdHsaOS()) 6080 return emitNonHSAIntrinsicError(DAG, DL, VT); 6081 6082 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6083 SI::KernelInputOffsets::LOCAL_SIZE_X); 6084 case Intrinsic::r600_read_local_size_y: 6085 if (Subtarget->isAmdHsaOS()) 6086 return emitNonHSAIntrinsicError(DAG, DL, VT); 6087 6088 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6089 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6090 case Intrinsic::r600_read_local_size_z: 6091 if (Subtarget->isAmdHsaOS()) 6092 return emitNonHSAIntrinsicError(DAG, DL, VT); 6093 6094 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6095 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6096 case Intrinsic::amdgcn_workgroup_id_x: 6097 return getPreloadedValue(DAG, *MFI, VT, 6098 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6099 case Intrinsic::amdgcn_workgroup_id_y: 6100 return getPreloadedValue(DAG, *MFI, VT, 6101 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6102 case Intrinsic::amdgcn_workgroup_id_z: 6103 return getPreloadedValue(DAG, *MFI, VT, 6104 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6105 case Intrinsic::amdgcn_workitem_id_x: 6106 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6107 SDLoc(DAG.getEntryNode()), 6108 MFI->getArgInfo().WorkItemIDX); 6109 case Intrinsic::amdgcn_workitem_id_y: 6110 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6111 SDLoc(DAG.getEntryNode()), 6112 MFI->getArgInfo().WorkItemIDY); 6113 case Intrinsic::amdgcn_workitem_id_z: 6114 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6115 SDLoc(DAG.getEntryNode()), 6116 MFI->getArgInfo().WorkItemIDZ); 6117 case Intrinsic::amdgcn_wavefrontsize: 6118 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6119 SDLoc(Op), MVT::i32); 6120 case Intrinsic::amdgcn_s_buffer_load: { 6121 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 6122 SDValue GLC; 6123 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 6124 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 6125 IsGFX10 ? &DLC : nullptr)) 6126 return Op; 6127 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6128 DAG); 6129 } 6130 case Intrinsic::amdgcn_fdiv_fast: 6131 return lowerFDIV_FAST(Op, DAG); 6132 case Intrinsic::amdgcn_sin: 6133 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6134 6135 case Intrinsic::amdgcn_cos: 6136 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6137 6138 case Intrinsic::amdgcn_mul_u24: 6139 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6140 case Intrinsic::amdgcn_mul_i24: 6141 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6142 6143 case Intrinsic::amdgcn_log_clamp: { 6144 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6145 return SDValue(); 6146 6147 DiagnosticInfoUnsupported BadIntrin( 6148 MF.getFunction(), "intrinsic not supported on subtarget", 6149 DL.getDebugLoc()); 6150 DAG.getContext()->diagnose(BadIntrin); 6151 return DAG.getUNDEF(VT); 6152 } 6153 case Intrinsic::amdgcn_ldexp: 6154 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6155 Op.getOperand(1), Op.getOperand(2)); 6156 6157 case Intrinsic::amdgcn_fract: 6158 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6159 6160 case Intrinsic::amdgcn_class: 6161 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6162 Op.getOperand(1), Op.getOperand(2)); 6163 case Intrinsic::amdgcn_div_fmas: 6164 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6165 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6166 Op.getOperand(4)); 6167 6168 case Intrinsic::amdgcn_div_fixup: 6169 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6170 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6171 6172 case Intrinsic::amdgcn_trig_preop: 6173 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 6174 Op.getOperand(1), Op.getOperand(2)); 6175 case Intrinsic::amdgcn_div_scale: { 6176 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6177 6178 // Translate to the operands expected by the machine instruction. The 6179 // first parameter must be the same as the first instruction. 6180 SDValue Numerator = Op.getOperand(1); 6181 SDValue Denominator = Op.getOperand(2); 6182 6183 // Note this order is opposite of the machine instruction's operations, 6184 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6185 // intrinsic has the numerator as the first operand to match a normal 6186 // division operation. 6187 6188 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6189 6190 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6191 Denominator, Numerator); 6192 } 6193 case Intrinsic::amdgcn_icmp: { 6194 // There is a Pat that handles this variant, so return it as-is. 6195 if (Op.getOperand(1).getValueType() == MVT::i1 && 6196 Op.getConstantOperandVal(2) == 0 && 6197 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6198 return Op; 6199 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6200 } 6201 case Intrinsic::amdgcn_fcmp: { 6202 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6203 } 6204 case Intrinsic::amdgcn_ballot: 6205 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6206 case Intrinsic::amdgcn_fmed3: 6207 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6208 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6209 case Intrinsic::amdgcn_fdot2: 6210 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6211 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6212 Op.getOperand(4)); 6213 case Intrinsic::amdgcn_fmul_legacy: 6214 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6215 Op.getOperand(1), Op.getOperand(2)); 6216 case Intrinsic::amdgcn_sffbh: 6217 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6218 case Intrinsic::amdgcn_sbfe: 6219 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6220 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6221 case Intrinsic::amdgcn_ubfe: 6222 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6223 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6224 case Intrinsic::amdgcn_cvt_pkrtz: 6225 case Intrinsic::amdgcn_cvt_pknorm_i16: 6226 case Intrinsic::amdgcn_cvt_pknorm_u16: 6227 case Intrinsic::amdgcn_cvt_pk_i16: 6228 case Intrinsic::amdgcn_cvt_pk_u16: { 6229 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6230 EVT VT = Op.getValueType(); 6231 unsigned Opcode; 6232 6233 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6234 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6235 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6236 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6237 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6238 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6239 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6240 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6241 else 6242 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6243 6244 if (isTypeLegal(VT)) 6245 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6246 6247 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6248 Op.getOperand(1), Op.getOperand(2)); 6249 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6250 } 6251 case Intrinsic::amdgcn_fmad_ftz: 6252 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6253 Op.getOperand(2), Op.getOperand(3)); 6254 6255 case Intrinsic::amdgcn_if_break: 6256 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6257 Op->getOperand(1), Op->getOperand(2)), 0); 6258 6259 case Intrinsic::amdgcn_groupstaticsize: { 6260 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6261 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6262 return Op; 6263 6264 const Module *M = MF.getFunction().getParent(); 6265 const GlobalValue *GV = 6266 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6267 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6268 SIInstrInfo::MO_ABS32_LO); 6269 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6270 } 6271 case Intrinsic::amdgcn_is_shared: 6272 case Intrinsic::amdgcn_is_private: { 6273 SDLoc SL(Op); 6274 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6275 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6276 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6277 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6278 Op.getOperand(1)); 6279 6280 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6281 DAG.getConstant(1, SL, MVT::i32)); 6282 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6283 } 6284 case Intrinsic::amdgcn_alignbit: 6285 return DAG.getNode(ISD::FSHR, DL, VT, 6286 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6287 case Intrinsic::amdgcn_reloc_constant: { 6288 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6289 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6290 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6291 auto RelocSymbol = cast<GlobalVariable>( 6292 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6293 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6294 SIInstrInfo::MO_ABS32_LO); 6295 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6296 } 6297 default: 6298 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6299 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6300 return lowerImage(Op, ImageDimIntr, DAG); 6301 6302 return Op; 6303 } 6304 } 6305 6306 // This function computes an appropriate offset to pass to 6307 // MachineMemOperand::setOffset() based on the offset inputs to 6308 // an intrinsic. If any of the offsets are non-contstant or 6309 // if VIndex is non-zero then this function returns 0. Otherwise, 6310 // it returns the sum of VOffset, SOffset, and Offset. 6311 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6312 SDValue SOffset, 6313 SDValue Offset, 6314 SDValue VIndex = SDValue()) { 6315 6316 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6317 !isa<ConstantSDNode>(Offset)) 6318 return 0; 6319 6320 if (VIndex) { 6321 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6322 return 0; 6323 } 6324 6325 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6326 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6327 cast<ConstantSDNode>(Offset)->getSExtValue(); 6328 } 6329 6330 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6331 switch (MF.getFunction().getCallingConv()) { 6332 case CallingConv::AMDGPU_PS: 6333 return 1; 6334 case CallingConv::AMDGPU_VS: 6335 return 2; 6336 case CallingConv::AMDGPU_GS: 6337 return 3; 6338 case CallingConv::AMDGPU_HS: 6339 case CallingConv::AMDGPU_LS: 6340 case CallingConv::AMDGPU_ES: 6341 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6342 case CallingConv::AMDGPU_CS: 6343 case CallingConv::AMDGPU_KERNEL: 6344 case CallingConv::C: 6345 case CallingConv::Fast: 6346 default: 6347 // Assume other calling conventions are various compute callable functions 6348 return 0; 6349 } 6350 } 6351 6352 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6353 SelectionDAG &DAG) const { 6354 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6355 SDLoc DL(Op); 6356 6357 switch (IntrID) { 6358 case Intrinsic::amdgcn_ds_ordered_add: 6359 case Intrinsic::amdgcn_ds_ordered_swap: { 6360 MemSDNode *M = cast<MemSDNode>(Op); 6361 SDValue Chain = M->getOperand(0); 6362 SDValue M0 = M->getOperand(2); 6363 SDValue Value = M->getOperand(3); 6364 unsigned IndexOperand = M->getConstantOperandVal(7); 6365 unsigned WaveRelease = M->getConstantOperandVal(8); 6366 unsigned WaveDone = M->getConstantOperandVal(9); 6367 6368 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6369 IndexOperand &= ~0x3f; 6370 unsigned CountDw = 0; 6371 6372 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6373 CountDw = (IndexOperand >> 24) & 0xf; 6374 IndexOperand &= ~(0xf << 24); 6375 6376 if (CountDw < 1 || CountDw > 4) { 6377 report_fatal_error( 6378 "ds_ordered_count: dword count must be between 1 and 4"); 6379 } 6380 } 6381 6382 if (IndexOperand) 6383 report_fatal_error("ds_ordered_count: bad index operand"); 6384 6385 if (WaveDone && !WaveRelease) 6386 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6387 6388 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6389 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6390 unsigned Offset0 = OrderedCountIndex << 2; 6391 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6392 (Instruction << 4); 6393 6394 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6395 Offset1 |= (CountDw - 1) << 6; 6396 6397 unsigned Offset = Offset0 | (Offset1 << 8); 6398 6399 SDValue Ops[] = { 6400 Chain, 6401 Value, 6402 DAG.getTargetConstant(Offset, DL, MVT::i16), 6403 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6404 }; 6405 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6406 M->getVTList(), Ops, M->getMemoryVT(), 6407 M->getMemOperand()); 6408 } 6409 case Intrinsic::amdgcn_ds_fadd: { 6410 MemSDNode *M = cast<MemSDNode>(Op); 6411 unsigned Opc; 6412 switch (IntrID) { 6413 case Intrinsic::amdgcn_ds_fadd: 6414 Opc = ISD::ATOMIC_LOAD_FADD; 6415 break; 6416 } 6417 6418 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6419 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6420 M->getMemOperand()); 6421 } 6422 case Intrinsic::amdgcn_atomic_inc: 6423 case Intrinsic::amdgcn_atomic_dec: 6424 case Intrinsic::amdgcn_ds_fmin: 6425 case Intrinsic::amdgcn_ds_fmax: { 6426 MemSDNode *M = cast<MemSDNode>(Op); 6427 unsigned Opc; 6428 switch (IntrID) { 6429 case Intrinsic::amdgcn_atomic_inc: 6430 Opc = AMDGPUISD::ATOMIC_INC; 6431 break; 6432 case Intrinsic::amdgcn_atomic_dec: 6433 Opc = AMDGPUISD::ATOMIC_DEC; 6434 break; 6435 case Intrinsic::amdgcn_ds_fmin: 6436 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6437 break; 6438 case Intrinsic::amdgcn_ds_fmax: 6439 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6440 break; 6441 default: 6442 llvm_unreachable("Unknown intrinsic!"); 6443 } 6444 SDValue Ops[] = { 6445 M->getOperand(0), // Chain 6446 M->getOperand(2), // Ptr 6447 M->getOperand(3) // Value 6448 }; 6449 6450 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6451 M->getMemoryVT(), M->getMemOperand()); 6452 } 6453 case Intrinsic::amdgcn_buffer_load: 6454 case Intrinsic::amdgcn_buffer_load_format: { 6455 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6456 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6457 unsigned IdxEn = 1; 6458 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6459 IdxEn = Idx->getZExtValue() != 0; 6460 SDValue Ops[] = { 6461 Op.getOperand(0), // Chain 6462 Op.getOperand(2), // rsrc 6463 Op.getOperand(3), // vindex 6464 SDValue(), // voffset -- will be set by setBufferOffsets 6465 SDValue(), // soffset -- will be set by setBufferOffsets 6466 SDValue(), // offset -- will be set by setBufferOffsets 6467 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6468 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6469 }; 6470 6471 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6472 // We don't know the offset if vindex is non-zero, so clear it. 6473 if (IdxEn) 6474 Offset = 0; 6475 6476 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6477 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6478 6479 EVT VT = Op.getValueType(); 6480 EVT IntVT = VT.changeTypeToInteger(); 6481 auto *M = cast<MemSDNode>(Op); 6482 M->getMemOperand()->setOffset(Offset); 6483 EVT LoadVT = Op.getValueType(); 6484 6485 if (LoadVT.getScalarType() == MVT::f16) 6486 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6487 M, DAG, Ops); 6488 6489 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6490 if (LoadVT.getScalarType() == MVT::i8 || 6491 LoadVT.getScalarType() == MVT::i16) 6492 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6493 6494 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6495 M->getMemOperand(), DAG); 6496 } 6497 case Intrinsic::amdgcn_raw_buffer_load: 6498 case Intrinsic::amdgcn_raw_buffer_load_format: { 6499 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6500 6501 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6502 SDValue Ops[] = { 6503 Op.getOperand(0), // Chain 6504 Op.getOperand(2), // rsrc 6505 DAG.getConstant(0, DL, MVT::i32), // vindex 6506 Offsets.first, // voffset 6507 Op.getOperand(4), // soffset 6508 Offsets.second, // offset 6509 Op.getOperand(5), // cachepolicy, swizzled buffer 6510 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6511 }; 6512 6513 auto *M = cast<MemSDNode>(Op); 6514 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6515 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6516 } 6517 case Intrinsic::amdgcn_struct_buffer_load: 6518 case Intrinsic::amdgcn_struct_buffer_load_format: { 6519 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6520 6521 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6522 SDValue Ops[] = { 6523 Op.getOperand(0), // Chain 6524 Op.getOperand(2), // rsrc 6525 Op.getOperand(3), // vindex 6526 Offsets.first, // voffset 6527 Op.getOperand(5), // soffset 6528 Offsets.second, // offset 6529 Op.getOperand(6), // cachepolicy, swizzled buffer 6530 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6531 }; 6532 6533 auto *M = cast<MemSDNode>(Op); 6534 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6535 Ops[2])); 6536 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6537 } 6538 case Intrinsic::amdgcn_tbuffer_load: { 6539 MemSDNode *M = cast<MemSDNode>(Op); 6540 EVT LoadVT = Op.getValueType(); 6541 6542 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6543 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6544 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6545 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6546 unsigned IdxEn = 1; 6547 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6548 IdxEn = Idx->getZExtValue() != 0; 6549 SDValue Ops[] = { 6550 Op.getOperand(0), // Chain 6551 Op.getOperand(2), // rsrc 6552 Op.getOperand(3), // vindex 6553 Op.getOperand(4), // voffset 6554 Op.getOperand(5), // soffset 6555 Op.getOperand(6), // offset 6556 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6557 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6558 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6559 }; 6560 6561 if (LoadVT.getScalarType() == MVT::f16) 6562 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6563 M, DAG, Ops); 6564 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6565 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6566 DAG); 6567 } 6568 case Intrinsic::amdgcn_raw_tbuffer_load: { 6569 MemSDNode *M = cast<MemSDNode>(Op); 6570 EVT LoadVT = Op.getValueType(); 6571 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6572 6573 SDValue Ops[] = { 6574 Op.getOperand(0), // Chain 6575 Op.getOperand(2), // rsrc 6576 DAG.getConstant(0, DL, MVT::i32), // vindex 6577 Offsets.first, // voffset 6578 Op.getOperand(4), // soffset 6579 Offsets.second, // offset 6580 Op.getOperand(5), // format 6581 Op.getOperand(6), // cachepolicy, swizzled buffer 6582 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6583 }; 6584 6585 if (LoadVT.getScalarType() == MVT::f16) 6586 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6587 M, DAG, Ops); 6588 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6589 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6590 DAG); 6591 } 6592 case Intrinsic::amdgcn_struct_tbuffer_load: { 6593 MemSDNode *M = cast<MemSDNode>(Op); 6594 EVT LoadVT = Op.getValueType(); 6595 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6596 6597 SDValue Ops[] = { 6598 Op.getOperand(0), // Chain 6599 Op.getOperand(2), // rsrc 6600 Op.getOperand(3), // vindex 6601 Offsets.first, // voffset 6602 Op.getOperand(5), // soffset 6603 Offsets.second, // offset 6604 Op.getOperand(6), // format 6605 Op.getOperand(7), // cachepolicy, swizzled buffer 6606 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6607 }; 6608 6609 if (LoadVT.getScalarType() == MVT::f16) 6610 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6611 M, DAG, Ops); 6612 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6613 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6614 DAG); 6615 } 6616 case Intrinsic::amdgcn_buffer_atomic_swap: 6617 case Intrinsic::amdgcn_buffer_atomic_add: 6618 case Intrinsic::amdgcn_buffer_atomic_sub: 6619 case Intrinsic::amdgcn_buffer_atomic_smin: 6620 case Intrinsic::amdgcn_buffer_atomic_umin: 6621 case Intrinsic::amdgcn_buffer_atomic_smax: 6622 case Intrinsic::amdgcn_buffer_atomic_umax: 6623 case Intrinsic::amdgcn_buffer_atomic_and: 6624 case Intrinsic::amdgcn_buffer_atomic_or: 6625 case Intrinsic::amdgcn_buffer_atomic_xor: { 6626 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6627 unsigned IdxEn = 1; 6628 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6629 IdxEn = Idx->getZExtValue() != 0; 6630 SDValue Ops[] = { 6631 Op.getOperand(0), // Chain 6632 Op.getOperand(2), // vdata 6633 Op.getOperand(3), // rsrc 6634 Op.getOperand(4), // vindex 6635 SDValue(), // voffset -- will be set by setBufferOffsets 6636 SDValue(), // soffset -- will be set by setBufferOffsets 6637 SDValue(), // offset -- will be set by setBufferOffsets 6638 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6639 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6640 }; 6641 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6642 // We don't know the offset if vindex is non-zero, so clear it. 6643 if (IdxEn) 6644 Offset = 0; 6645 EVT VT = Op.getValueType(); 6646 6647 auto *M = cast<MemSDNode>(Op); 6648 M->getMemOperand()->setOffset(Offset); 6649 unsigned Opcode = 0; 6650 6651 switch (IntrID) { 6652 case Intrinsic::amdgcn_buffer_atomic_swap: 6653 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6654 break; 6655 case Intrinsic::amdgcn_buffer_atomic_add: 6656 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6657 break; 6658 case Intrinsic::amdgcn_buffer_atomic_sub: 6659 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6660 break; 6661 case Intrinsic::amdgcn_buffer_atomic_smin: 6662 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6663 break; 6664 case Intrinsic::amdgcn_buffer_atomic_umin: 6665 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6666 break; 6667 case Intrinsic::amdgcn_buffer_atomic_smax: 6668 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6669 break; 6670 case Intrinsic::amdgcn_buffer_atomic_umax: 6671 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6672 break; 6673 case Intrinsic::amdgcn_buffer_atomic_and: 6674 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6675 break; 6676 case Intrinsic::amdgcn_buffer_atomic_or: 6677 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6678 break; 6679 case Intrinsic::amdgcn_buffer_atomic_xor: 6680 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6681 break; 6682 default: 6683 llvm_unreachable("unhandled atomic opcode"); 6684 } 6685 6686 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6687 M->getMemOperand()); 6688 } 6689 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6690 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6691 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6692 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6693 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6694 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6695 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6696 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6697 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6698 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6699 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6700 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6701 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6702 SDValue Ops[] = { 6703 Op.getOperand(0), // Chain 6704 Op.getOperand(2), // vdata 6705 Op.getOperand(3), // rsrc 6706 DAG.getConstant(0, DL, MVT::i32), // vindex 6707 Offsets.first, // voffset 6708 Op.getOperand(5), // soffset 6709 Offsets.second, // offset 6710 Op.getOperand(6), // cachepolicy 6711 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6712 }; 6713 EVT VT = Op.getValueType(); 6714 6715 auto *M = cast<MemSDNode>(Op); 6716 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6717 unsigned Opcode = 0; 6718 6719 switch (IntrID) { 6720 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6721 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6722 break; 6723 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6724 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6725 break; 6726 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6727 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6728 break; 6729 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6730 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6731 break; 6732 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6733 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6734 break; 6735 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6736 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6737 break; 6738 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6739 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6740 break; 6741 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6742 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6743 break; 6744 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6745 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6746 break; 6747 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6748 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6749 break; 6750 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6751 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6752 break; 6753 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6754 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6755 break; 6756 default: 6757 llvm_unreachable("unhandled atomic opcode"); 6758 } 6759 6760 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6761 M->getMemOperand()); 6762 } 6763 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6764 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6765 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6766 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6767 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6768 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6769 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6770 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6771 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6772 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6773 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6774 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6775 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6776 SDValue Ops[] = { 6777 Op.getOperand(0), // Chain 6778 Op.getOperand(2), // vdata 6779 Op.getOperand(3), // rsrc 6780 Op.getOperand(4), // vindex 6781 Offsets.first, // voffset 6782 Op.getOperand(6), // soffset 6783 Offsets.second, // offset 6784 Op.getOperand(7), // cachepolicy 6785 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6786 }; 6787 EVT VT = Op.getValueType(); 6788 6789 auto *M = cast<MemSDNode>(Op); 6790 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6791 Ops[3])); 6792 unsigned Opcode = 0; 6793 6794 switch (IntrID) { 6795 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6796 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6797 break; 6798 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6799 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6800 break; 6801 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6802 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6803 break; 6804 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6805 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6806 break; 6807 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6808 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6809 break; 6810 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6811 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6812 break; 6813 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6814 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6815 break; 6816 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6817 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6818 break; 6819 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6820 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6821 break; 6822 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6823 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6824 break; 6825 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6826 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6827 break; 6828 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6829 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6830 break; 6831 default: 6832 llvm_unreachable("unhandled atomic opcode"); 6833 } 6834 6835 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6836 M->getMemOperand()); 6837 } 6838 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6839 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6840 unsigned IdxEn = 1; 6841 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6842 IdxEn = Idx->getZExtValue() != 0; 6843 SDValue Ops[] = { 6844 Op.getOperand(0), // Chain 6845 Op.getOperand(2), // src 6846 Op.getOperand(3), // cmp 6847 Op.getOperand(4), // rsrc 6848 Op.getOperand(5), // vindex 6849 SDValue(), // voffset -- will be set by setBufferOffsets 6850 SDValue(), // soffset -- will be set by setBufferOffsets 6851 SDValue(), // offset -- will be set by setBufferOffsets 6852 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6853 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6854 }; 6855 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6856 // We don't know the offset if vindex is non-zero, so clear it. 6857 if (IdxEn) 6858 Offset = 0; 6859 EVT VT = Op.getValueType(); 6860 auto *M = cast<MemSDNode>(Op); 6861 M->getMemOperand()->setOffset(Offset); 6862 6863 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6864 Op->getVTList(), Ops, VT, M->getMemOperand()); 6865 } 6866 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6867 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6868 SDValue Ops[] = { 6869 Op.getOperand(0), // Chain 6870 Op.getOperand(2), // src 6871 Op.getOperand(3), // cmp 6872 Op.getOperand(4), // rsrc 6873 DAG.getConstant(0, DL, MVT::i32), // vindex 6874 Offsets.first, // voffset 6875 Op.getOperand(6), // soffset 6876 Offsets.second, // offset 6877 Op.getOperand(7), // cachepolicy 6878 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6879 }; 6880 EVT VT = Op.getValueType(); 6881 auto *M = cast<MemSDNode>(Op); 6882 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6883 6884 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6885 Op->getVTList(), Ops, VT, M->getMemOperand()); 6886 } 6887 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6888 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6889 SDValue Ops[] = { 6890 Op.getOperand(0), // Chain 6891 Op.getOperand(2), // src 6892 Op.getOperand(3), // cmp 6893 Op.getOperand(4), // rsrc 6894 Op.getOperand(5), // vindex 6895 Offsets.first, // voffset 6896 Op.getOperand(7), // soffset 6897 Offsets.second, // offset 6898 Op.getOperand(8), // cachepolicy 6899 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6900 }; 6901 EVT VT = Op.getValueType(); 6902 auto *M = cast<MemSDNode>(Op); 6903 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6904 Ops[4])); 6905 6906 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6907 Op->getVTList(), Ops, VT, M->getMemOperand()); 6908 } 6909 6910 default: 6911 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6912 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6913 return lowerImage(Op, ImageDimIntr, DAG); 6914 6915 return SDValue(); 6916 } 6917 } 6918 6919 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6920 // dwordx4 if on SI. 6921 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6922 SDVTList VTList, 6923 ArrayRef<SDValue> Ops, EVT MemVT, 6924 MachineMemOperand *MMO, 6925 SelectionDAG &DAG) const { 6926 EVT VT = VTList.VTs[0]; 6927 EVT WidenedVT = VT; 6928 EVT WidenedMemVT = MemVT; 6929 if (!Subtarget->hasDwordx3LoadStores() && 6930 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6931 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6932 WidenedVT.getVectorElementType(), 4); 6933 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6934 WidenedMemVT.getVectorElementType(), 4); 6935 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6936 } 6937 6938 assert(VTList.NumVTs == 2); 6939 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6940 6941 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6942 WidenedMemVT, MMO); 6943 if (WidenedVT != VT) { 6944 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6945 DAG.getVectorIdxConstant(0, DL)); 6946 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6947 } 6948 return NewOp; 6949 } 6950 6951 SDValue SITargetLowering::handleD16VData(SDValue VData, 6952 SelectionDAG &DAG) const { 6953 EVT StoreVT = VData.getValueType(); 6954 6955 // No change for f16 and legal vector D16 types. 6956 if (!StoreVT.isVector()) 6957 return VData; 6958 6959 SDLoc DL(VData); 6960 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6961 6962 if (Subtarget->hasUnpackedD16VMem()) { 6963 // We need to unpack the packed data to store. 6964 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6965 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6966 6967 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6968 StoreVT.getVectorNumElements()); 6969 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6970 return DAG.UnrollVectorOp(ZExt.getNode()); 6971 } 6972 6973 assert(isTypeLegal(StoreVT)); 6974 return VData; 6975 } 6976 6977 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6978 SelectionDAG &DAG) const { 6979 SDLoc DL(Op); 6980 SDValue Chain = Op.getOperand(0); 6981 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6982 MachineFunction &MF = DAG.getMachineFunction(); 6983 6984 switch (IntrinsicID) { 6985 case Intrinsic::amdgcn_exp_compr: { 6986 SDValue Src0 = Op.getOperand(4); 6987 SDValue Src1 = Op.getOperand(5); 6988 // Hack around illegal type on SI by directly selecting it. 6989 if (isTypeLegal(Src0.getValueType())) 6990 return SDValue(); 6991 6992 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6993 SDValue Undef = DAG.getUNDEF(MVT::f32); 6994 const SDValue Ops[] = { 6995 Op.getOperand(2), // tgt 6996 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6997 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6998 Undef, // src2 6999 Undef, // src3 7000 Op.getOperand(7), // vm 7001 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7002 Op.getOperand(3), // en 7003 Op.getOperand(0) // Chain 7004 }; 7005 7006 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7007 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7008 } 7009 case Intrinsic::amdgcn_s_barrier: { 7010 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7011 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7012 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7013 if (WGSize <= ST.getWavefrontSize()) 7014 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7015 Op.getOperand(0)), 0); 7016 } 7017 return SDValue(); 7018 }; 7019 case Intrinsic::amdgcn_tbuffer_store: { 7020 SDValue VData = Op.getOperand(2); 7021 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7022 if (IsD16) 7023 VData = handleD16VData(VData, DAG); 7024 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7025 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7026 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7027 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7028 unsigned IdxEn = 1; 7029 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7030 IdxEn = Idx->getZExtValue() != 0; 7031 SDValue Ops[] = { 7032 Chain, 7033 VData, // vdata 7034 Op.getOperand(3), // rsrc 7035 Op.getOperand(4), // vindex 7036 Op.getOperand(5), // voffset 7037 Op.getOperand(6), // soffset 7038 Op.getOperand(7), // offset 7039 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7040 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7041 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7042 }; 7043 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7044 AMDGPUISD::TBUFFER_STORE_FORMAT; 7045 MemSDNode *M = cast<MemSDNode>(Op); 7046 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7047 M->getMemoryVT(), M->getMemOperand()); 7048 } 7049 7050 case Intrinsic::amdgcn_struct_tbuffer_store: { 7051 SDValue VData = Op.getOperand(2); 7052 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7053 if (IsD16) 7054 VData = handleD16VData(VData, DAG); 7055 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7056 SDValue Ops[] = { 7057 Chain, 7058 VData, // vdata 7059 Op.getOperand(3), // rsrc 7060 Op.getOperand(4), // vindex 7061 Offsets.first, // voffset 7062 Op.getOperand(6), // soffset 7063 Offsets.second, // offset 7064 Op.getOperand(7), // format 7065 Op.getOperand(8), // cachepolicy, swizzled buffer 7066 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7067 }; 7068 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7069 AMDGPUISD::TBUFFER_STORE_FORMAT; 7070 MemSDNode *M = cast<MemSDNode>(Op); 7071 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7072 M->getMemoryVT(), M->getMemOperand()); 7073 } 7074 7075 case Intrinsic::amdgcn_raw_tbuffer_store: { 7076 SDValue VData = Op.getOperand(2); 7077 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7078 if (IsD16) 7079 VData = handleD16VData(VData, DAG); 7080 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7081 SDValue Ops[] = { 7082 Chain, 7083 VData, // vdata 7084 Op.getOperand(3), // rsrc 7085 DAG.getConstant(0, DL, MVT::i32), // vindex 7086 Offsets.first, // voffset 7087 Op.getOperand(5), // soffset 7088 Offsets.second, // offset 7089 Op.getOperand(6), // format 7090 Op.getOperand(7), // cachepolicy, swizzled buffer 7091 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7092 }; 7093 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7094 AMDGPUISD::TBUFFER_STORE_FORMAT; 7095 MemSDNode *M = cast<MemSDNode>(Op); 7096 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7097 M->getMemoryVT(), M->getMemOperand()); 7098 } 7099 7100 case Intrinsic::amdgcn_buffer_store: 7101 case Intrinsic::amdgcn_buffer_store_format: { 7102 SDValue VData = Op.getOperand(2); 7103 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7104 if (IsD16) 7105 VData = handleD16VData(VData, DAG); 7106 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7107 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7108 unsigned IdxEn = 1; 7109 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7110 IdxEn = Idx->getZExtValue() != 0; 7111 SDValue Ops[] = { 7112 Chain, 7113 VData, 7114 Op.getOperand(3), // rsrc 7115 Op.getOperand(4), // vindex 7116 SDValue(), // voffset -- will be set by setBufferOffsets 7117 SDValue(), // soffset -- will be set by setBufferOffsets 7118 SDValue(), // offset -- will be set by setBufferOffsets 7119 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7120 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7121 }; 7122 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7123 // We don't know the offset if vindex is non-zero, so clear it. 7124 if (IdxEn) 7125 Offset = 0; 7126 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7127 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7128 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7129 MemSDNode *M = cast<MemSDNode>(Op); 7130 M->getMemOperand()->setOffset(Offset); 7131 7132 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7133 EVT VDataType = VData.getValueType().getScalarType(); 7134 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7135 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7136 7137 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7138 M->getMemoryVT(), M->getMemOperand()); 7139 } 7140 7141 case Intrinsic::amdgcn_raw_buffer_store: 7142 case Intrinsic::amdgcn_raw_buffer_store_format: { 7143 const bool IsFormat = 7144 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7145 7146 SDValue VData = Op.getOperand(2); 7147 EVT VDataVT = VData.getValueType(); 7148 EVT EltType = VDataVT.getScalarType(); 7149 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7150 if (IsD16) 7151 VData = handleD16VData(VData, DAG); 7152 7153 if (!isTypeLegal(VDataVT)) { 7154 VData = 7155 DAG.getNode(ISD::BITCAST, DL, 7156 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7157 } 7158 7159 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7160 SDValue Ops[] = { 7161 Chain, 7162 VData, 7163 Op.getOperand(3), // rsrc 7164 DAG.getConstant(0, DL, MVT::i32), // vindex 7165 Offsets.first, // voffset 7166 Op.getOperand(5), // soffset 7167 Offsets.second, // offset 7168 Op.getOperand(6), // cachepolicy, swizzled buffer 7169 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7170 }; 7171 unsigned Opc = 7172 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7173 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7174 MemSDNode *M = cast<MemSDNode>(Op); 7175 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7176 7177 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7178 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7179 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7180 7181 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7182 M->getMemoryVT(), M->getMemOperand()); 7183 } 7184 7185 case Intrinsic::amdgcn_struct_buffer_store: 7186 case Intrinsic::amdgcn_struct_buffer_store_format: { 7187 const bool IsFormat = 7188 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7189 7190 SDValue VData = Op.getOperand(2); 7191 EVT VDataVT = VData.getValueType(); 7192 EVT EltType = VDataVT.getScalarType(); 7193 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7194 7195 if (IsD16) 7196 VData = handleD16VData(VData, DAG); 7197 7198 if (!isTypeLegal(VDataVT)) { 7199 VData = 7200 DAG.getNode(ISD::BITCAST, DL, 7201 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7202 } 7203 7204 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7205 SDValue Ops[] = { 7206 Chain, 7207 VData, 7208 Op.getOperand(3), // rsrc 7209 Op.getOperand(4), // vindex 7210 Offsets.first, // voffset 7211 Op.getOperand(6), // soffset 7212 Offsets.second, // offset 7213 Op.getOperand(7), // cachepolicy, swizzled buffer 7214 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7215 }; 7216 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7217 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7218 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7219 MemSDNode *M = cast<MemSDNode>(Op); 7220 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7221 Ops[3])); 7222 7223 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7224 EVT VDataType = VData.getValueType().getScalarType(); 7225 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7226 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7227 7228 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7229 M->getMemoryVT(), M->getMemOperand()); 7230 } 7231 7232 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7233 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7234 unsigned IdxEn = 1; 7235 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7236 IdxEn = Idx->getZExtValue() != 0; 7237 SDValue Ops[] = { 7238 Chain, 7239 Op.getOperand(2), // vdata 7240 Op.getOperand(3), // rsrc 7241 Op.getOperand(4), // vindex 7242 SDValue(), // voffset -- will be set by setBufferOffsets 7243 SDValue(), // soffset -- will be set by setBufferOffsets 7244 SDValue(), // offset -- will be set by setBufferOffsets 7245 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7246 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7247 }; 7248 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7249 // We don't know the offset if vindex is non-zero, so clear it. 7250 if (IdxEn) 7251 Offset = 0; 7252 EVT VT = Op.getOperand(2).getValueType(); 7253 7254 auto *M = cast<MemSDNode>(Op); 7255 M->getMemOperand()->setOffset(Offset); 7256 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7257 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7258 7259 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7260 M->getMemOperand()); 7261 } 7262 7263 case Intrinsic::amdgcn_global_atomic_fadd: { 7264 SDValue Ops[] = { 7265 Chain, 7266 Op.getOperand(2), // ptr 7267 Op.getOperand(3) // vdata 7268 }; 7269 EVT VT = Op.getOperand(3).getValueType(); 7270 7271 auto *M = cast<MemSDNode>(Op); 7272 if (VT.isVector()) { 7273 return DAG.getMemIntrinsicNode( 7274 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7275 M->getMemOperand()); 7276 } 7277 7278 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7279 DAG.getVTList(VT, MVT::Other), Ops, 7280 M->getMemOperand()).getValue(1); 7281 } 7282 case Intrinsic::amdgcn_end_cf: 7283 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7284 Op->getOperand(2), Chain), 0); 7285 7286 default: { 7287 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7288 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7289 return lowerImage(Op, ImageDimIntr, DAG); 7290 7291 return Op; 7292 } 7293 } 7294 } 7295 7296 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7297 // offset (the offset that is included in bounds checking and swizzling, to be 7298 // split between the instruction's voffset and immoffset fields) and soffset 7299 // (the offset that is excluded from bounds checking and swizzling, to go in 7300 // the instruction's soffset field). This function takes the first kind of 7301 // offset and figures out how to split it between voffset and immoffset. 7302 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7303 SDValue Offset, SelectionDAG &DAG) const { 7304 SDLoc DL(Offset); 7305 const unsigned MaxImm = 4095; 7306 SDValue N0 = Offset; 7307 ConstantSDNode *C1 = nullptr; 7308 7309 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7310 N0 = SDValue(); 7311 else if (DAG.isBaseWithConstantOffset(N0)) { 7312 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7313 N0 = N0.getOperand(0); 7314 } 7315 7316 if (C1) { 7317 unsigned ImmOffset = C1->getZExtValue(); 7318 // If the immediate value is too big for the immoffset field, put the value 7319 // and -4096 into the immoffset field so that the value that is copied/added 7320 // for the voffset field is a multiple of 4096, and it stands more chance 7321 // of being CSEd with the copy/add for another similar load/store. 7322 // However, do not do that rounding down to a multiple of 4096 if that is a 7323 // negative number, as it appears to be illegal to have a negative offset 7324 // in the vgpr, even if adding the immediate offset makes it positive. 7325 unsigned Overflow = ImmOffset & ~MaxImm; 7326 ImmOffset -= Overflow; 7327 if ((int32_t)Overflow < 0) { 7328 Overflow += ImmOffset; 7329 ImmOffset = 0; 7330 } 7331 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7332 if (Overflow) { 7333 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7334 if (!N0) 7335 N0 = OverflowVal; 7336 else { 7337 SDValue Ops[] = { N0, OverflowVal }; 7338 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7339 } 7340 } 7341 } 7342 if (!N0) 7343 N0 = DAG.getConstant(0, DL, MVT::i32); 7344 if (!C1) 7345 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7346 return {N0, SDValue(C1, 0)}; 7347 } 7348 7349 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7350 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7351 // pointed to by Offsets. 7352 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7353 SelectionDAG &DAG, SDValue *Offsets, 7354 unsigned Align) const { 7355 SDLoc DL(CombinedOffset); 7356 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7357 uint32_t Imm = C->getZExtValue(); 7358 uint32_t SOffset, ImmOffset; 7359 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7360 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7361 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7362 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7363 return SOffset + ImmOffset; 7364 } 7365 } 7366 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7367 SDValue N0 = CombinedOffset.getOperand(0); 7368 SDValue N1 = CombinedOffset.getOperand(1); 7369 uint32_t SOffset, ImmOffset; 7370 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7371 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7372 Subtarget, Align)) { 7373 Offsets[0] = N0; 7374 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7375 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7376 return 0; 7377 } 7378 } 7379 Offsets[0] = CombinedOffset; 7380 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7381 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7382 return 0; 7383 } 7384 7385 // Handle 8 bit and 16 bit buffer loads 7386 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7387 EVT LoadVT, SDLoc DL, 7388 ArrayRef<SDValue> Ops, 7389 MemSDNode *M) const { 7390 EVT IntVT = LoadVT.changeTypeToInteger(); 7391 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7392 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7393 7394 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7395 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7396 Ops, IntVT, 7397 M->getMemOperand()); 7398 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7399 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7400 7401 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7402 } 7403 7404 // Handle 8 bit and 16 bit buffer stores 7405 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7406 EVT VDataType, SDLoc DL, 7407 SDValue Ops[], 7408 MemSDNode *M) const { 7409 if (VDataType == MVT::f16) 7410 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7411 7412 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7413 Ops[1] = BufferStoreExt; 7414 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7415 AMDGPUISD::BUFFER_STORE_SHORT; 7416 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7417 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7418 M->getMemOperand()); 7419 } 7420 7421 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7422 ISD::LoadExtType ExtType, SDValue Op, 7423 const SDLoc &SL, EVT VT) { 7424 if (VT.bitsLT(Op.getValueType())) 7425 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7426 7427 switch (ExtType) { 7428 case ISD::SEXTLOAD: 7429 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7430 case ISD::ZEXTLOAD: 7431 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7432 case ISD::EXTLOAD: 7433 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7434 case ISD::NON_EXTLOAD: 7435 return Op; 7436 } 7437 7438 llvm_unreachable("invalid ext type"); 7439 } 7440 7441 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7442 SelectionDAG &DAG = DCI.DAG; 7443 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7444 return SDValue(); 7445 7446 // FIXME: Constant loads should all be marked invariant. 7447 unsigned AS = Ld->getAddressSpace(); 7448 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7449 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7450 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7451 return SDValue(); 7452 7453 // Don't do this early, since it may interfere with adjacent load merging for 7454 // illegal types. We can avoid losing alignment information for exotic types 7455 // pre-legalize. 7456 EVT MemVT = Ld->getMemoryVT(); 7457 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7458 MemVT.getSizeInBits() >= 32) 7459 return SDValue(); 7460 7461 SDLoc SL(Ld); 7462 7463 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7464 "unexpected vector extload"); 7465 7466 // TODO: Drop only high part of range. 7467 SDValue Ptr = Ld->getBasePtr(); 7468 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7469 MVT::i32, SL, Ld->getChain(), Ptr, 7470 Ld->getOffset(), 7471 Ld->getPointerInfo(), MVT::i32, 7472 Ld->getAlignment(), 7473 Ld->getMemOperand()->getFlags(), 7474 Ld->getAAInfo(), 7475 nullptr); // Drop ranges 7476 7477 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7478 if (MemVT.isFloatingPoint()) { 7479 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7480 "unexpected fp extload"); 7481 TruncVT = MemVT.changeTypeToInteger(); 7482 } 7483 7484 SDValue Cvt = NewLoad; 7485 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7486 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7487 DAG.getValueType(TruncVT)); 7488 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7489 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7490 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7491 } else { 7492 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7493 } 7494 7495 EVT VT = Ld->getValueType(0); 7496 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7497 7498 DCI.AddToWorklist(Cvt.getNode()); 7499 7500 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7501 // the appropriate extension from the 32-bit load. 7502 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7503 DCI.AddToWorklist(Cvt.getNode()); 7504 7505 // Handle conversion back to floating point if necessary. 7506 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7507 7508 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7509 } 7510 7511 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7512 SDLoc DL(Op); 7513 LoadSDNode *Load = cast<LoadSDNode>(Op); 7514 ISD::LoadExtType ExtType = Load->getExtensionType(); 7515 EVT MemVT = Load->getMemoryVT(); 7516 7517 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7518 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7519 return SDValue(); 7520 7521 // FIXME: Copied from PPC 7522 // First, load into 32 bits, then truncate to 1 bit. 7523 7524 SDValue Chain = Load->getChain(); 7525 SDValue BasePtr = Load->getBasePtr(); 7526 MachineMemOperand *MMO = Load->getMemOperand(); 7527 7528 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7529 7530 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7531 BasePtr, RealMemVT, MMO); 7532 7533 if (!MemVT.isVector()) { 7534 SDValue Ops[] = { 7535 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7536 NewLD.getValue(1) 7537 }; 7538 7539 return DAG.getMergeValues(Ops, DL); 7540 } 7541 7542 SmallVector<SDValue, 3> Elts; 7543 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7544 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7545 DAG.getConstant(I, DL, MVT::i32)); 7546 7547 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7548 } 7549 7550 SDValue Ops[] = { 7551 DAG.getBuildVector(MemVT, DL, Elts), 7552 NewLD.getValue(1) 7553 }; 7554 7555 return DAG.getMergeValues(Ops, DL); 7556 } 7557 7558 if (!MemVT.isVector()) 7559 return SDValue(); 7560 7561 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7562 "Custom lowering for non-i32 vectors hasn't been implemented."); 7563 7564 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7565 MemVT, *Load->getMemOperand())) { 7566 SDValue Ops[2]; 7567 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7568 return DAG.getMergeValues(Ops, DL); 7569 } 7570 7571 unsigned Alignment = Load->getAlignment(); 7572 unsigned AS = Load->getAddressSpace(); 7573 if (Subtarget->hasLDSMisalignedBug() && 7574 AS == AMDGPUAS::FLAT_ADDRESS && 7575 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7576 return SplitVectorLoad(Op, DAG); 7577 } 7578 7579 MachineFunction &MF = DAG.getMachineFunction(); 7580 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7581 // If there is a possibilty that flat instruction access scratch memory 7582 // then we need to use the same legalization rules we use for private. 7583 if (AS == AMDGPUAS::FLAT_ADDRESS && 7584 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7585 AS = MFI->hasFlatScratchInit() ? 7586 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7587 7588 unsigned NumElements = MemVT.getVectorNumElements(); 7589 7590 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7591 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7592 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7593 if (MemVT.isPow2VectorType()) 7594 return SDValue(); 7595 if (NumElements == 3) 7596 return WidenVectorLoad(Op, DAG); 7597 return SplitVectorLoad(Op, DAG); 7598 } 7599 // Non-uniform loads will be selected to MUBUF instructions, so they 7600 // have the same legalization requirements as global and private 7601 // loads. 7602 // 7603 } 7604 7605 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7606 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7607 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7608 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7609 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7610 Alignment >= 4 && NumElements < 32) { 7611 if (MemVT.isPow2VectorType()) 7612 return SDValue(); 7613 if (NumElements == 3) 7614 return WidenVectorLoad(Op, DAG); 7615 return SplitVectorLoad(Op, DAG); 7616 } 7617 // Non-uniform loads will be selected to MUBUF instructions, so they 7618 // have the same legalization requirements as global and private 7619 // loads. 7620 // 7621 } 7622 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7623 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7624 AS == AMDGPUAS::GLOBAL_ADDRESS || 7625 AS == AMDGPUAS::FLAT_ADDRESS) { 7626 if (NumElements > 4) 7627 return SplitVectorLoad(Op, DAG); 7628 // v3 loads not supported on SI. 7629 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7630 return WidenVectorLoad(Op, DAG); 7631 // v3 and v4 loads are supported for private and global memory. 7632 return SDValue(); 7633 } 7634 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7635 // Depending on the setting of the private_element_size field in the 7636 // resource descriptor, we can only make private accesses up to a certain 7637 // size. 7638 switch (Subtarget->getMaxPrivateElementSize()) { 7639 case 4: { 7640 SDValue Ops[2]; 7641 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7642 return DAG.getMergeValues(Ops, DL); 7643 } 7644 case 8: 7645 if (NumElements > 2) 7646 return SplitVectorLoad(Op, DAG); 7647 return SDValue(); 7648 case 16: 7649 // Same as global/flat 7650 if (NumElements > 4) 7651 return SplitVectorLoad(Op, DAG); 7652 // v3 loads not supported on SI. 7653 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7654 return WidenVectorLoad(Op, DAG); 7655 return SDValue(); 7656 default: 7657 llvm_unreachable("unsupported private_element_size"); 7658 } 7659 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7660 // Use ds_read_b128 if possible. 7661 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7662 MemVT.getStoreSize() == 16) 7663 return SDValue(); 7664 7665 if (NumElements > 2) 7666 return SplitVectorLoad(Op, DAG); 7667 7668 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7669 // address is negative, then the instruction is incorrectly treated as 7670 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7671 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7672 // load later in the SILoadStoreOptimizer. 7673 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7674 NumElements == 2 && MemVT.getStoreSize() == 8 && 7675 Load->getAlignment() < 8) { 7676 return SplitVectorLoad(Op, DAG); 7677 } 7678 } 7679 return SDValue(); 7680 } 7681 7682 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7683 EVT VT = Op.getValueType(); 7684 assert(VT.getSizeInBits() == 64); 7685 7686 SDLoc DL(Op); 7687 SDValue Cond = Op.getOperand(0); 7688 7689 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7690 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7691 7692 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7693 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7694 7695 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7696 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7697 7698 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7699 7700 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7701 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7702 7703 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7704 7705 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7706 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7707 } 7708 7709 // Catch division cases where we can use shortcuts with rcp and rsq 7710 // instructions. 7711 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7712 SelectionDAG &DAG) const { 7713 SDLoc SL(Op); 7714 SDValue LHS = Op.getOperand(0); 7715 SDValue RHS = Op.getOperand(1); 7716 EVT VT = Op.getValueType(); 7717 const SDNodeFlags Flags = Op->getFlags(); 7718 7719 bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath || 7720 Flags.hasApproximateFuncs(); 7721 7722 // Without !fpmath accuracy information, we can't do more because we don't 7723 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 7724 if (!AllowInaccurateRcp) 7725 return SDValue(); 7726 7727 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7728 if (CLHS->isExactlyValue(1.0)) { 7729 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7730 // the CI documentation has a worst case error of 1 ulp. 7731 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7732 // use it as long as we aren't trying to use denormals. 7733 // 7734 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7735 7736 // 1.0 / sqrt(x) -> rsq(x) 7737 7738 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7739 // error seems really high at 2^29 ULP. 7740 if (RHS.getOpcode() == ISD::FSQRT) 7741 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7742 7743 // 1.0 / x -> rcp(x) 7744 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7745 } 7746 7747 // Same as for 1.0, but expand the sign out of the constant. 7748 if (CLHS->isExactlyValue(-1.0)) { 7749 // -1.0 / x -> rcp (fneg x) 7750 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7751 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7752 } 7753 } 7754 7755 // Turn into multiply by the reciprocal. 7756 // x / y -> x * (1.0 / y) 7757 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7758 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7759 } 7760 7761 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7762 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7763 if (GlueChain->getNumValues() <= 1) { 7764 return DAG.getNode(Opcode, SL, VT, A, B); 7765 } 7766 7767 assert(GlueChain->getNumValues() == 3); 7768 7769 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7770 switch (Opcode) { 7771 default: llvm_unreachable("no chain equivalent for opcode"); 7772 case ISD::FMUL: 7773 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7774 break; 7775 } 7776 7777 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7778 GlueChain.getValue(2)); 7779 } 7780 7781 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7782 EVT VT, SDValue A, SDValue B, SDValue C, 7783 SDValue GlueChain) { 7784 if (GlueChain->getNumValues() <= 1) { 7785 return DAG.getNode(Opcode, SL, VT, A, B, C); 7786 } 7787 7788 assert(GlueChain->getNumValues() == 3); 7789 7790 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7791 switch (Opcode) { 7792 default: llvm_unreachable("no chain equivalent for opcode"); 7793 case ISD::FMA: 7794 Opcode = AMDGPUISD::FMA_W_CHAIN; 7795 break; 7796 } 7797 7798 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7799 GlueChain.getValue(2)); 7800 } 7801 7802 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7803 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7804 return FastLowered; 7805 7806 SDLoc SL(Op); 7807 SDValue Src0 = Op.getOperand(0); 7808 SDValue Src1 = Op.getOperand(1); 7809 7810 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7811 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7812 7813 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7814 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7815 7816 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7817 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7818 7819 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7820 } 7821 7822 // Faster 2.5 ULP division that does not support denormals. 7823 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7824 SDLoc SL(Op); 7825 SDValue LHS = Op.getOperand(1); 7826 SDValue RHS = Op.getOperand(2); 7827 7828 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7829 7830 const APFloat K0Val(BitsToFloat(0x6f800000)); 7831 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7832 7833 const APFloat K1Val(BitsToFloat(0x2f800000)); 7834 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7835 7836 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7837 7838 EVT SetCCVT = 7839 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7840 7841 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7842 7843 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7844 7845 // TODO: Should this propagate fast-math-flags? 7846 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7847 7848 // rcp does not support denormals. 7849 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7850 7851 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7852 7853 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7854 } 7855 7856 // Returns immediate value for setting the F32 denorm mode when using the 7857 // S_DENORM_MODE instruction. 7858 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7859 const SDLoc &SL, const GCNSubtarget *ST) { 7860 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7861 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7862 ? FP_DENORM_FLUSH_NONE 7863 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7864 7865 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7866 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7867 } 7868 7869 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7870 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7871 return FastLowered; 7872 7873 SDLoc SL(Op); 7874 SDValue LHS = Op.getOperand(0); 7875 SDValue RHS = Op.getOperand(1); 7876 7877 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7878 7879 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7880 7881 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7882 RHS, RHS, LHS); 7883 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7884 LHS, RHS, LHS); 7885 7886 // Denominator is scaled to not be denormal, so using rcp is ok. 7887 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7888 DenominatorScaled); 7889 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7890 DenominatorScaled); 7891 7892 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7893 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7894 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7895 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7896 7897 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7898 7899 if (!HasFP32Denormals) { 7900 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7901 7902 SDValue EnableDenorm; 7903 if (Subtarget->hasDenormModeInst()) { 7904 const SDValue EnableDenormValue = 7905 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7906 7907 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7908 DAG.getEntryNode(), EnableDenormValue); 7909 } else { 7910 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7911 SL, MVT::i32); 7912 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7913 DAG.getEntryNode(), EnableDenormValue, 7914 BitField); 7915 } 7916 7917 SDValue Ops[3] = { 7918 NegDivScale0, 7919 EnableDenorm.getValue(0), 7920 EnableDenorm.getValue(1) 7921 }; 7922 7923 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7924 } 7925 7926 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7927 ApproxRcp, One, NegDivScale0); 7928 7929 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7930 ApproxRcp, Fma0); 7931 7932 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7933 Fma1, Fma1); 7934 7935 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7936 NumeratorScaled, Mul); 7937 7938 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7939 7940 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7941 NumeratorScaled, Fma3); 7942 7943 if (!HasFP32Denormals) { 7944 SDValue DisableDenorm; 7945 if (Subtarget->hasDenormModeInst()) { 7946 const SDValue DisableDenormValue = 7947 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7948 7949 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7950 Fma4.getValue(1), DisableDenormValue, 7951 Fma4.getValue(2)); 7952 } else { 7953 const SDValue DisableDenormValue = 7954 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7955 7956 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7957 Fma4.getValue(1), DisableDenormValue, 7958 BitField, Fma4.getValue(2)); 7959 } 7960 7961 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7962 DisableDenorm, DAG.getRoot()); 7963 DAG.setRoot(OutputChain); 7964 } 7965 7966 SDValue Scale = NumeratorScaled.getValue(1); 7967 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7968 Fma4, Fma1, Fma3, Scale); 7969 7970 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7971 } 7972 7973 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7974 if (DAG.getTarget().Options.UnsafeFPMath) 7975 return lowerFastUnsafeFDIV(Op, DAG); 7976 7977 SDLoc SL(Op); 7978 SDValue X = Op.getOperand(0); 7979 SDValue Y = Op.getOperand(1); 7980 7981 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7982 7983 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7984 7985 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7986 7987 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7988 7989 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7990 7991 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7992 7993 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7994 7995 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7996 7997 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7998 7999 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8000 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8001 8002 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8003 NegDivScale0, Mul, DivScale1); 8004 8005 SDValue Scale; 8006 8007 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8008 // Workaround a hardware bug on SI where the condition output from div_scale 8009 // is not usable. 8010 8011 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8012 8013 // Figure out if the scale to use for div_fmas. 8014 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8015 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8016 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8017 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8018 8019 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8020 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8021 8022 SDValue Scale0Hi 8023 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8024 SDValue Scale1Hi 8025 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8026 8027 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8028 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8029 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8030 } else { 8031 Scale = DivScale1.getValue(1); 8032 } 8033 8034 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8035 Fma4, Fma3, Mul, Scale); 8036 8037 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8038 } 8039 8040 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8041 EVT VT = Op.getValueType(); 8042 8043 if (VT == MVT::f32) 8044 return LowerFDIV32(Op, DAG); 8045 8046 if (VT == MVT::f64) 8047 return LowerFDIV64(Op, DAG); 8048 8049 if (VT == MVT::f16) 8050 return LowerFDIV16(Op, DAG); 8051 8052 llvm_unreachable("Unexpected type for fdiv"); 8053 } 8054 8055 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8056 SDLoc DL(Op); 8057 StoreSDNode *Store = cast<StoreSDNode>(Op); 8058 EVT VT = Store->getMemoryVT(); 8059 8060 if (VT == MVT::i1) { 8061 return DAG.getTruncStore(Store->getChain(), DL, 8062 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8063 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8064 } 8065 8066 assert(VT.isVector() && 8067 Store->getValue().getValueType().getScalarType() == MVT::i32); 8068 8069 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8070 VT, *Store->getMemOperand())) { 8071 return expandUnalignedStore(Store, DAG); 8072 } 8073 8074 unsigned AS = Store->getAddressSpace(); 8075 if (Subtarget->hasLDSMisalignedBug() && 8076 AS == AMDGPUAS::FLAT_ADDRESS && 8077 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8078 return SplitVectorStore(Op, DAG); 8079 } 8080 8081 MachineFunction &MF = DAG.getMachineFunction(); 8082 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8083 // If there is a possibilty that flat instruction access scratch memory 8084 // then we need to use the same legalization rules we use for private. 8085 if (AS == AMDGPUAS::FLAT_ADDRESS && 8086 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8087 AS = MFI->hasFlatScratchInit() ? 8088 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8089 8090 unsigned NumElements = VT.getVectorNumElements(); 8091 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8092 AS == AMDGPUAS::FLAT_ADDRESS) { 8093 if (NumElements > 4) 8094 return SplitVectorStore(Op, DAG); 8095 // v3 stores not supported on SI. 8096 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8097 return SplitVectorStore(Op, DAG); 8098 return SDValue(); 8099 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8100 switch (Subtarget->getMaxPrivateElementSize()) { 8101 case 4: 8102 return scalarizeVectorStore(Store, DAG); 8103 case 8: 8104 if (NumElements > 2) 8105 return SplitVectorStore(Op, DAG); 8106 return SDValue(); 8107 case 16: 8108 if (NumElements > 4 || NumElements == 3) 8109 return SplitVectorStore(Op, DAG); 8110 return SDValue(); 8111 default: 8112 llvm_unreachable("unsupported private_element_size"); 8113 } 8114 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8115 // Use ds_write_b128 if possible. 8116 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 8117 VT.getStoreSize() == 16 && NumElements != 3) 8118 return SDValue(); 8119 8120 if (NumElements > 2) 8121 return SplitVectorStore(Op, DAG); 8122 8123 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8124 // address is negative, then the instruction is incorrectly treated as 8125 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8126 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8127 // store later in the SILoadStoreOptimizer. 8128 if (!Subtarget->hasUsableDSOffset() && 8129 NumElements == 2 && VT.getStoreSize() == 8 && 8130 Store->getAlignment() < 8) { 8131 return SplitVectorStore(Op, DAG); 8132 } 8133 8134 return SDValue(); 8135 } else { 8136 llvm_unreachable("unhandled address space"); 8137 } 8138 } 8139 8140 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8141 SDLoc DL(Op); 8142 EVT VT = Op.getValueType(); 8143 SDValue Arg = Op.getOperand(0); 8144 SDValue TrigVal; 8145 8146 // TODO: Should this propagate fast-math-flags? 8147 8148 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 8149 8150 if (Subtarget->hasTrigReducedRange()) { 8151 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8152 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 8153 } else { 8154 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8155 } 8156 8157 switch (Op.getOpcode()) { 8158 case ISD::FCOS: 8159 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 8160 case ISD::FSIN: 8161 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 8162 default: 8163 llvm_unreachable("Wrong trig opcode"); 8164 } 8165 } 8166 8167 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8168 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8169 assert(AtomicNode->isCompareAndSwap()); 8170 unsigned AS = AtomicNode->getAddressSpace(); 8171 8172 // No custom lowering required for local address space 8173 if (!isFlatGlobalAddrSpace(AS)) 8174 return Op; 8175 8176 // Non-local address space requires custom lowering for atomic compare 8177 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8178 SDLoc DL(Op); 8179 SDValue ChainIn = Op.getOperand(0); 8180 SDValue Addr = Op.getOperand(1); 8181 SDValue Old = Op.getOperand(2); 8182 SDValue New = Op.getOperand(3); 8183 EVT VT = Op.getValueType(); 8184 MVT SimpleVT = VT.getSimpleVT(); 8185 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8186 8187 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8188 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8189 8190 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8191 Ops, VT, AtomicNode->getMemOperand()); 8192 } 8193 8194 //===----------------------------------------------------------------------===// 8195 // Custom DAG optimizations 8196 //===----------------------------------------------------------------------===// 8197 8198 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8199 DAGCombinerInfo &DCI) const { 8200 EVT VT = N->getValueType(0); 8201 EVT ScalarVT = VT.getScalarType(); 8202 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8203 return SDValue(); 8204 8205 SelectionDAG &DAG = DCI.DAG; 8206 SDLoc DL(N); 8207 8208 SDValue Src = N->getOperand(0); 8209 EVT SrcVT = Src.getValueType(); 8210 8211 // TODO: We could try to match extracting the higher bytes, which would be 8212 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8213 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8214 // about in practice. 8215 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8216 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8217 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8218 DCI.AddToWorklist(Cvt.getNode()); 8219 8220 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8221 if (ScalarVT != MVT::f32) { 8222 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8223 DAG.getTargetConstant(0, DL, MVT::i32)); 8224 } 8225 return Cvt; 8226 } 8227 } 8228 8229 return SDValue(); 8230 } 8231 8232 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8233 8234 // This is a variant of 8235 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8236 // 8237 // The normal DAG combiner will do this, but only if the add has one use since 8238 // that would increase the number of instructions. 8239 // 8240 // This prevents us from seeing a constant offset that can be folded into a 8241 // memory instruction's addressing mode. If we know the resulting add offset of 8242 // a pointer can be folded into an addressing offset, we can replace the pointer 8243 // operand with the add of new constant offset. This eliminates one of the uses, 8244 // and may allow the remaining use to also be simplified. 8245 // 8246 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8247 unsigned AddrSpace, 8248 EVT MemVT, 8249 DAGCombinerInfo &DCI) const { 8250 SDValue N0 = N->getOperand(0); 8251 SDValue N1 = N->getOperand(1); 8252 8253 // We only do this to handle cases where it's profitable when there are 8254 // multiple uses of the add, so defer to the standard combine. 8255 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8256 N0->hasOneUse()) 8257 return SDValue(); 8258 8259 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8260 if (!CN1) 8261 return SDValue(); 8262 8263 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8264 if (!CAdd) 8265 return SDValue(); 8266 8267 // If the resulting offset is too large, we can't fold it into the addressing 8268 // mode offset. 8269 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8270 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8271 8272 AddrMode AM; 8273 AM.HasBaseReg = true; 8274 AM.BaseOffs = Offset.getSExtValue(); 8275 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8276 return SDValue(); 8277 8278 SelectionDAG &DAG = DCI.DAG; 8279 SDLoc SL(N); 8280 EVT VT = N->getValueType(0); 8281 8282 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8283 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8284 8285 SDNodeFlags Flags; 8286 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8287 (N0.getOpcode() == ISD::OR || 8288 N0->getFlags().hasNoUnsignedWrap())); 8289 8290 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8291 } 8292 8293 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8294 DAGCombinerInfo &DCI) const { 8295 SDValue Ptr = N->getBasePtr(); 8296 SelectionDAG &DAG = DCI.DAG; 8297 SDLoc SL(N); 8298 8299 // TODO: We could also do this for multiplies. 8300 if (Ptr.getOpcode() == ISD::SHL) { 8301 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8302 N->getMemoryVT(), DCI); 8303 if (NewPtr) { 8304 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8305 8306 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8307 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8308 } 8309 } 8310 8311 return SDValue(); 8312 } 8313 8314 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8315 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8316 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8317 (Opc == ISD::XOR && Val == 0); 8318 } 8319 8320 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8321 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8322 // integer combine opportunities since most 64-bit operations are decomposed 8323 // this way. TODO: We won't want this for SALU especially if it is an inline 8324 // immediate. 8325 SDValue SITargetLowering::splitBinaryBitConstantOp( 8326 DAGCombinerInfo &DCI, 8327 const SDLoc &SL, 8328 unsigned Opc, SDValue LHS, 8329 const ConstantSDNode *CRHS) const { 8330 uint64_t Val = CRHS->getZExtValue(); 8331 uint32_t ValLo = Lo_32(Val); 8332 uint32_t ValHi = Hi_32(Val); 8333 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8334 8335 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8336 bitOpWithConstantIsReducible(Opc, ValHi)) || 8337 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8338 // If we need to materialize a 64-bit immediate, it will be split up later 8339 // anyway. Avoid creating the harder to understand 64-bit immediate 8340 // materialization. 8341 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8342 } 8343 8344 return SDValue(); 8345 } 8346 8347 // Returns true if argument is a boolean value which is not serialized into 8348 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8349 static bool isBoolSGPR(SDValue V) { 8350 if (V.getValueType() != MVT::i1) 8351 return false; 8352 switch (V.getOpcode()) { 8353 default: break; 8354 case ISD::SETCC: 8355 case ISD::AND: 8356 case ISD::OR: 8357 case ISD::XOR: 8358 case AMDGPUISD::FP_CLASS: 8359 return true; 8360 } 8361 return false; 8362 } 8363 8364 // If a constant has all zeroes or all ones within each byte return it. 8365 // Otherwise return 0. 8366 static uint32_t getConstantPermuteMask(uint32_t C) { 8367 // 0xff for any zero byte in the mask 8368 uint32_t ZeroByteMask = 0; 8369 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8370 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8371 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8372 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8373 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8374 if ((NonZeroByteMask & C) != NonZeroByteMask) 8375 return 0; // Partial bytes selected. 8376 return C; 8377 } 8378 8379 // Check if a node selects whole bytes from its operand 0 starting at a byte 8380 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8381 // or -1 if not succeeded. 8382 // Note byte select encoding: 8383 // value 0-3 selects corresponding source byte; 8384 // value 0xc selects zero; 8385 // value 0xff selects 0xff. 8386 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8387 assert(V.getValueSizeInBits() == 32); 8388 8389 if (V.getNumOperands() != 2) 8390 return ~0; 8391 8392 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8393 if (!N1) 8394 return ~0; 8395 8396 uint32_t C = N1->getZExtValue(); 8397 8398 switch (V.getOpcode()) { 8399 default: 8400 break; 8401 case ISD::AND: 8402 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8403 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8404 } 8405 break; 8406 8407 case ISD::OR: 8408 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8409 return (0x03020100 & ~ConstMask) | ConstMask; 8410 } 8411 break; 8412 8413 case ISD::SHL: 8414 if (C % 8) 8415 return ~0; 8416 8417 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8418 8419 case ISD::SRL: 8420 if (C % 8) 8421 return ~0; 8422 8423 return uint32_t(0x0c0c0c0c03020100ull >> C); 8424 } 8425 8426 return ~0; 8427 } 8428 8429 SDValue SITargetLowering::performAndCombine(SDNode *N, 8430 DAGCombinerInfo &DCI) const { 8431 if (DCI.isBeforeLegalize()) 8432 return SDValue(); 8433 8434 SelectionDAG &DAG = DCI.DAG; 8435 EVT VT = N->getValueType(0); 8436 SDValue LHS = N->getOperand(0); 8437 SDValue RHS = N->getOperand(1); 8438 8439 8440 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8441 if (VT == MVT::i64 && CRHS) { 8442 if (SDValue Split 8443 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8444 return Split; 8445 } 8446 8447 if (CRHS && VT == MVT::i32) { 8448 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8449 // nb = number of trailing zeroes in mask 8450 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8451 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8452 uint64_t Mask = CRHS->getZExtValue(); 8453 unsigned Bits = countPopulation(Mask); 8454 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8455 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8456 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8457 unsigned Shift = CShift->getZExtValue(); 8458 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8459 unsigned Offset = NB + Shift; 8460 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8461 SDLoc SL(N); 8462 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8463 LHS->getOperand(0), 8464 DAG.getConstant(Offset, SL, MVT::i32), 8465 DAG.getConstant(Bits, SL, MVT::i32)); 8466 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8467 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8468 DAG.getValueType(NarrowVT)); 8469 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8470 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8471 return Shl; 8472 } 8473 } 8474 } 8475 8476 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8477 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8478 isa<ConstantSDNode>(LHS.getOperand(2))) { 8479 uint32_t Sel = getConstantPermuteMask(Mask); 8480 if (!Sel) 8481 return SDValue(); 8482 8483 // Select 0xc for all zero bytes 8484 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8485 SDLoc DL(N); 8486 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8487 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8488 } 8489 } 8490 8491 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8492 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8493 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8494 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8495 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8496 8497 SDValue X = LHS.getOperand(0); 8498 SDValue Y = RHS.getOperand(0); 8499 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8500 return SDValue(); 8501 8502 if (LCC == ISD::SETO) { 8503 if (X != LHS.getOperand(1)) 8504 return SDValue(); 8505 8506 if (RCC == ISD::SETUNE) { 8507 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8508 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8509 return SDValue(); 8510 8511 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8512 SIInstrFlags::N_SUBNORMAL | 8513 SIInstrFlags::N_ZERO | 8514 SIInstrFlags::P_ZERO | 8515 SIInstrFlags::P_SUBNORMAL | 8516 SIInstrFlags::P_NORMAL; 8517 8518 static_assert(((~(SIInstrFlags::S_NAN | 8519 SIInstrFlags::Q_NAN | 8520 SIInstrFlags::N_INFINITY | 8521 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8522 "mask not equal"); 8523 8524 SDLoc DL(N); 8525 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8526 X, DAG.getConstant(Mask, DL, MVT::i32)); 8527 } 8528 } 8529 } 8530 8531 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8532 std::swap(LHS, RHS); 8533 8534 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8535 RHS.hasOneUse()) { 8536 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8537 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8538 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8539 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8540 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8541 (RHS.getOperand(0) == LHS.getOperand(0) && 8542 LHS.getOperand(0) == LHS.getOperand(1))) { 8543 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8544 unsigned NewMask = LCC == ISD::SETO ? 8545 Mask->getZExtValue() & ~OrdMask : 8546 Mask->getZExtValue() & OrdMask; 8547 8548 SDLoc DL(N); 8549 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8550 DAG.getConstant(NewMask, DL, MVT::i32)); 8551 } 8552 } 8553 8554 if (VT == MVT::i32 && 8555 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8556 // and x, (sext cc from i1) => select cc, x, 0 8557 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8558 std::swap(LHS, RHS); 8559 if (isBoolSGPR(RHS.getOperand(0))) 8560 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8561 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8562 } 8563 8564 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8565 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8566 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8567 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8568 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8569 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8570 if (LHSMask != ~0u && RHSMask != ~0u) { 8571 // Canonicalize the expression in an attempt to have fewer unique masks 8572 // and therefore fewer registers used to hold the masks. 8573 if (LHSMask > RHSMask) { 8574 std::swap(LHSMask, RHSMask); 8575 std::swap(LHS, RHS); 8576 } 8577 8578 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8579 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8580 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8581 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8582 8583 // Check of we need to combine values from two sources within a byte. 8584 if (!(LHSUsedLanes & RHSUsedLanes) && 8585 // If we select high and lower word keep it for SDWA. 8586 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8587 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8588 // Each byte in each mask is either selector mask 0-3, or has higher 8589 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8590 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8591 // mask which is not 0xff wins. By anding both masks we have a correct 8592 // result except that 0x0c shall be corrected to give 0x0c only. 8593 uint32_t Mask = LHSMask & RHSMask; 8594 for (unsigned I = 0; I < 32; I += 8) { 8595 uint32_t ByteSel = 0xff << I; 8596 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8597 Mask &= (0x0c << I) & 0xffffffff; 8598 } 8599 8600 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8601 // or 0x0c. 8602 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8603 SDLoc DL(N); 8604 8605 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8606 LHS.getOperand(0), RHS.getOperand(0), 8607 DAG.getConstant(Sel, DL, MVT::i32)); 8608 } 8609 } 8610 } 8611 8612 return SDValue(); 8613 } 8614 8615 SDValue SITargetLowering::performOrCombine(SDNode *N, 8616 DAGCombinerInfo &DCI) const { 8617 SelectionDAG &DAG = DCI.DAG; 8618 SDValue LHS = N->getOperand(0); 8619 SDValue RHS = N->getOperand(1); 8620 8621 EVT VT = N->getValueType(0); 8622 if (VT == MVT::i1) { 8623 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8624 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8625 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8626 SDValue Src = LHS.getOperand(0); 8627 if (Src != RHS.getOperand(0)) 8628 return SDValue(); 8629 8630 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8631 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8632 if (!CLHS || !CRHS) 8633 return SDValue(); 8634 8635 // Only 10 bits are used. 8636 static const uint32_t MaxMask = 0x3ff; 8637 8638 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8639 SDLoc DL(N); 8640 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8641 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8642 } 8643 8644 return SDValue(); 8645 } 8646 8647 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8648 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8649 LHS.getOpcode() == AMDGPUISD::PERM && 8650 isa<ConstantSDNode>(LHS.getOperand(2))) { 8651 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8652 if (!Sel) 8653 return SDValue(); 8654 8655 Sel |= LHS.getConstantOperandVal(2); 8656 SDLoc DL(N); 8657 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8658 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8659 } 8660 8661 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8662 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8663 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8664 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8665 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8666 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8667 if (LHSMask != ~0u && RHSMask != ~0u) { 8668 // Canonicalize the expression in an attempt to have fewer unique masks 8669 // and therefore fewer registers used to hold the masks. 8670 if (LHSMask > RHSMask) { 8671 std::swap(LHSMask, RHSMask); 8672 std::swap(LHS, RHS); 8673 } 8674 8675 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8676 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8677 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8678 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8679 8680 // Check of we need to combine values from two sources within a byte. 8681 if (!(LHSUsedLanes & RHSUsedLanes) && 8682 // If we select high and lower word keep it for SDWA. 8683 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8684 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8685 // Kill zero bytes selected by other mask. Zero value is 0xc. 8686 LHSMask &= ~RHSUsedLanes; 8687 RHSMask &= ~LHSUsedLanes; 8688 // Add 4 to each active LHS lane 8689 LHSMask |= LHSUsedLanes & 0x04040404; 8690 // Combine masks 8691 uint32_t Sel = LHSMask | RHSMask; 8692 SDLoc DL(N); 8693 8694 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8695 LHS.getOperand(0), RHS.getOperand(0), 8696 DAG.getConstant(Sel, DL, MVT::i32)); 8697 } 8698 } 8699 } 8700 8701 if (VT != MVT::i64) 8702 return SDValue(); 8703 8704 // TODO: This could be a generic combine with a predicate for extracting the 8705 // high half of an integer being free. 8706 8707 // (or i64:x, (zero_extend i32:y)) -> 8708 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8709 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8710 RHS.getOpcode() != ISD::ZERO_EXTEND) 8711 std::swap(LHS, RHS); 8712 8713 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8714 SDValue ExtSrc = RHS.getOperand(0); 8715 EVT SrcVT = ExtSrc.getValueType(); 8716 if (SrcVT == MVT::i32) { 8717 SDLoc SL(N); 8718 SDValue LowLHS, HiBits; 8719 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8720 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8721 8722 DCI.AddToWorklist(LowOr.getNode()); 8723 DCI.AddToWorklist(HiBits.getNode()); 8724 8725 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8726 LowOr, HiBits); 8727 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8728 } 8729 } 8730 8731 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8732 if (CRHS) { 8733 if (SDValue Split 8734 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8735 return Split; 8736 } 8737 8738 return SDValue(); 8739 } 8740 8741 SDValue SITargetLowering::performXorCombine(SDNode *N, 8742 DAGCombinerInfo &DCI) const { 8743 EVT VT = N->getValueType(0); 8744 if (VT != MVT::i64) 8745 return SDValue(); 8746 8747 SDValue LHS = N->getOperand(0); 8748 SDValue RHS = N->getOperand(1); 8749 8750 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8751 if (CRHS) { 8752 if (SDValue Split 8753 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8754 return Split; 8755 } 8756 8757 return SDValue(); 8758 } 8759 8760 // Instructions that will be lowered with a final instruction that zeros the 8761 // high result bits. 8762 // XXX - probably only need to list legal operations. 8763 static bool fp16SrcZerosHighBits(unsigned Opc) { 8764 switch (Opc) { 8765 case ISD::FADD: 8766 case ISD::FSUB: 8767 case ISD::FMUL: 8768 case ISD::FDIV: 8769 case ISD::FREM: 8770 case ISD::FMA: 8771 case ISD::FMAD: 8772 case ISD::FCANONICALIZE: 8773 case ISD::FP_ROUND: 8774 case ISD::UINT_TO_FP: 8775 case ISD::SINT_TO_FP: 8776 case ISD::FABS: 8777 // Fabs is lowered to a bit operation, but it's an and which will clear the 8778 // high bits anyway. 8779 case ISD::FSQRT: 8780 case ISD::FSIN: 8781 case ISD::FCOS: 8782 case ISD::FPOWI: 8783 case ISD::FPOW: 8784 case ISD::FLOG: 8785 case ISD::FLOG2: 8786 case ISD::FLOG10: 8787 case ISD::FEXP: 8788 case ISD::FEXP2: 8789 case ISD::FCEIL: 8790 case ISD::FTRUNC: 8791 case ISD::FRINT: 8792 case ISD::FNEARBYINT: 8793 case ISD::FROUND: 8794 case ISD::FFLOOR: 8795 case ISD::FMINNUM: 8796 case ISD::FMAXNUM: 8797 case AMDGPUISD::FRACT: 8798 case AMDGPUISD::CLAMP: 8799 case AMDGPUISD::COS_HW: 8800 case AMDGPUISD::SIN_HW: 8801 case AMDGPUISD::FMIN3: 8802 case AMDGPUISD::FMAX3: 8803 case AMDGPUISD::FMED3: 8804 case AMDGPUISD::FMAD_FTZ: 8805 case AMDGPUISD::RCP: 8806 case AMDGPUISD::RSQ: 8807 case AMDGPUISD::RCP_IFLAG: 8808 case AMDGPUISD::LDEXP: 8809 return true; 8810 default: 8811 // fcopysign, select and others may be lowered to 32-bit bit operations 8812 // which don't zero the high bits. 8813 return false; 8814 } 8815 } 8816 8817 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8818 DAGCombinerInfo &DCI) const { 8819 if (!Subtarget->has16BitInsts() || 8820 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8821 return SDValue(); 8822 8823 EVT VT = N->getValueType(0); 8824 if (VT != MVT::i32) 8825 return SDValue(); 8826 8827 SDValue Src = N->getOperand(0); 8828 if (Src.getValueType() != MVT::i16) 8829 return SDValue(); 8830 8831 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8832 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8833 if (Src.getOpcode() == ISD::BITCAST) { 8834 SDValue BCSrc = Src.getOperand(0); 8835 if (BCSrc.getValueType() == MVT::f16 && 8836 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8837 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8838 } 8839 8840 return SDValue(); 8841 } 8842 8843 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8844 DAGCombinerInfo &DCI) 8845 const { 8846 SDValue Src = N->getOperand(0); 8847 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8848 8849 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8850 VTSign->getVT() == MVT::i8) || 8851 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8852 VTSign->getVT() == MVT::i16)) && 8853 Src.hasOneUse()) { 8854 auto *M = cast<MemSDNode>(Src); 8855 SDValue Ops[] = { 8856 Src.getOperand(0), // Chain 8857 Src.getOperand(1), // rsrc 8858 Src.getOperand(2), // vindex 8859 Src.getOperand(3), // voffset 8860 Src.getOperand(4), // soffset 8861 Src.getOperand(5), // offset 8862 Src.getOperand(6), 8863 Src.getOperand(7) 8864 }; 8865 // replace with BUFFER_LOAD_BYTE/SHORT 8866 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8867 Src.getOperand(0).getValueType()); 8868 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8869 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8870 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8871 ResList, 8872 Ops, M->getMemoryVT(), 8873 M->getMemOperand()); 8874 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8875 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8876 } 8877 return SDValue(); 8878 } 8879 8880 SDValue SITargetLowering::performClassCombine(SDNode *N, 8881 DAGCombinerInfo &DCI) const { 8882 SelectionDAG &DAG = DCI.DAG; 8883 SDValue Mask = N->getOperand(1); 8884 8885 // fp_class x, 0 -> false 8886 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8887 if (CMask->isNullValue()) 8888 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8889 } 8890 8891 if (N->getOperand(0).isUndef()) 8892 return DAG.getUNDEF(MVT::i1); 8893 8894 return SDValue(); 8895 } 8896 8897 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8898 DAGCombinerInfo &DCI) const { 8899 EVT VT = N->getValueType(0); 8900 SDValue N0 = N->getOperand(0); 8901 8902 if (N0.isUndef()) 8903 return N0; 8904 8905 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8906 N0.getOpcode() == ISD::SINT_TO_FP)) { 8907 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8908 N->getFlags()); 8909 } 8910 8911 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8912 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8913 N0.getOperand(0), N->getFlags()); 8914 } 8915 8916 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8917 } 8918 8919 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8920 unsigned MaxDepth) const { 8921 unsigned Opcode = Op.getOpcode(); 8922 if (Opcode == ISD::FCANONICALIZE) 8923 return true; 8924 8925 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8926 auto F = CFP->getValueAPF(); 8927 if (F.isNaN() && F.isSignaling()) 8928 return false; 8929 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8930 } 8931 8932 // If source is a result of another standard FP operation it is already in 8933 // canonical form. 8934 if (MaxDepth == 0) 8935 return false; 8936 8937 switch (Opcode) { 8938 // These will flush denorms if required. 8939 case ISD::FADD: 8940 case ISD::FSUB: 8941 case ISD::FMUL: 8942 case ISD::FCEIL: 8943 case ISD::FFLOOR: 8944 case ISD::FMA: 8945 case ISD::FMAD: 8946 case ISD::FSQRT: 8947 case ISD::FDIV: 8948 case ISD::FREM: 8949 case ISD::FP_ROUND: 8950 case ISD::FP_EXTEND: 8951 case AMDGPUISD::FMUL_LEGACY: 8952 case AMDGPUISD::FMAD_FTZ: 8953 case AMDGPUISD::RCP: 8954 case AMDGPUISD::RSQ: 8955 case AMDGPUISD::RSQ_CLAMP: 8956 case AMDGPUISD::RCP_LEGACY: 8957 case AMDGPUISD::RCP_IFLAG: 8958 case AMDGPUISD::TRIG_PREOP: 8959 case AMDGPUISD::DIV_SCALE: 8960 case AMDGPUISD::DIV_FMAS: 8961 case AMDGPUISD::DIV_FIXUP: 8962 case AMDGPUISD::FRACT: 8963 case AMDGPUISD::LDEXP: 8964 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8965 case AMDGPUISD::CVT_F32_UBYTE0: 8966 case AMDGPUISD::CVT_F32_UBYTE1: 8967 case AMDGPUISD::CVT_F32_UBYTE2: 8968 case AMDGPUISD::CVT_F32_UBYTE3: 8969 return true; 8970 8971 // It can/will be lowered or combined as a bit operation. 8972 // Need to check their input recursively to handle. 8973 case ISD::FNEG: 8974 case ISD::FABS: 8975 case ISD::FCOPYSIGN: 8976 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8977 8978 case ISD::FSIN: 8979 case ISD::FCOS: 8980 case ISD::FSINCOS: 8981 return Op.getValueType().getScalarType() != MVT::f16; 8982 8983 case ISD::FMINNUM: 8984 case ISD::FMAXNUM: 8985 case ISD::FMINNUM_IEEE: 8986 case ISD::FMAXNUM_IEEE: 8987 case AMDGPUISD::CLAMP: 8988 case AMDGPUISD::FMED3: 8989 case AMDGPUISD::FMAX3: 8990 case AMDGPUISD::FMIN3: { 8991 // FIXME: Shouldn't treat the generic operations different based these. 8992 // However, we aren't really required to flush the result from 8993 // minnum/maxnum.. 8994 8995 // snans will be quieted, so we only need to worry about denormals. 8996 if (Subtarget->supportsMinMaxDenormModes() || 8997 denormalsEnabledForType(DAG, Op.getValueType())) 8998 return true; 8999 9000 // Flushing may be required. 9001 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9002 // targets need to check their input recursively. 9003 9004 // FIXME: Does this apply with clamp? It's implemented with max. 9005 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9006 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9007 return false; 9008 } 9009 9010 return true; 9011 } 9012 case ISD::SELECT: { 9013 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9014 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9015 } 9016 case ISD::BUILD_VECTOR: { 9017 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9018 SDValue SrcOp = Op.getOperand(i); 9019 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9020 return false; 9021 } 9022 9023 return true; 9024 } 9025 case ISD::EXTRACT_VECTOR_ELT: 9026 case ISD::EXTRACT_SUBVECTOR: { 9027 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9028 } 9029 case ISD::INSERT_VECTOR_ELT: { 9030 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9031 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9032 } 9033 case ISD::UNDEF: 9034 // Could be anything. 9035 return false; 9036 9037 case ISD::BITCAST: { 9038 // Hack round the mess we make when legalizing extract_vector_elt 9039 SDValue Src = Op.getOperand(0); 9040 if (Src.getValueType() == MVT::i16 && 9041 Src.getOpcode() == ISD::TRUNCATE) { 9042 SDValue TruncSrc = Src.getOperand(0); 9043 if (TruncSrc.getValueType() == MVT::i32 && 9044 TruncSrc.getOpcode() == ISD::BITCAST && 9045 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9046 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9047 } 9048 } 9049 9050 return false; 9051 } 9052 case ISD::INTRINSIC_WO_CHAIN: { 9053 unsigned IntrinsicID 9054 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9055 // TODO: Handle more intrinsics 9056 switch (IntrinsicID) { 9057 case Intrinsic::amdgcn_cvt_pkrtz: 9058 case Intrinsic::amdgcn_cubeid: 9059 case Intrinsic::amdgcn_frexp_mant: 9060 case Intrinsic::amdgcn_fdot2: 9061 case Intrinsic::amdgcn_rcp: 9062 case Intrinsic::amdgcn_rsq: 9063 case Intrinsic::amdgcn_rsq_clamp: 9064 case Intrinsic::amdgcn_rcp_legacy: 9065 case Intrinsic::amdgcn_rsq_legacy: 9066 return true; 9067 default: 9068 break; 9069 } 9070 9071 LLVM_FALLTHROUGH; 9072 } 9073 default: 9074 return denormalsEnabledForType(DAG, Op.getValueType()) && 9075 DAG.isKnownNeverSNaN(Op); 9076 } 9077 9078 llvm_unreachable("invalid operation"); 9079 } 9080 9081 // Constant fold canonicalize. 9082 SDValue SITargetLowering::getCanonicalConstantFP( 9083 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9084 // Flush denormals to 0 if not enabled. 9085 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9086 return DAG.getConstantFP(0.0, SL, VT); 9087 9088 if (C.isNaN()) { 9089 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9090 if (C.isSignaling()) { 9091 // Quiet a signaling NaN. 9092 // FIXME: Is this supposed to preserve payload bits? 9093 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9094 } 9095 9096 // Make sure it is the canonical NaN bitpattern. 9097 // 9098 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9099 // immediate? 9100 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9101 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9102 } 9103 9104 // Already canonical. 9105 return DAG.getConstantFP(C, SL, VT); 9106 } 9107 9108 static bool vectorEltWillFoldAway(SDValue Op) { 9109 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9110 } 9111 9112 SDValue SITargetLowering::performFCanonicalizeCombine( 9113 SDNode *N, 9114 DAGCombinerInfo &DCI) const { 9115 SelectionDAG &DAG = DCI.DAG; 9116 SDValue N0 = N->getOperand(0); 9117 EVT VT = N->getValueType(0); 9118 9119 // fcanonicalize undef -> qnan 9120 if (N0.isUndef()) { 9121 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9122 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9123 } 9124 9125 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9126 EVT VT = N->getValueType(0); 9127 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9128 } 9129 9130 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9131 // (fcanonicalize k) 9132 // 9133 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9134 9135 // TODO: This could be better with wider vectors that will be split to v2f16, 9136 // and to consider uses since there aren't that many packed operations. 9137 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9138 isTypeLegal(MVT::v2f16)) { 9139 SDLoc SL(N); 9140 SDValue NewElts[2]; 9141 SDValue Lo = N0.getOperand(0); 9142 SDValue Hi = N0.getOperand(1); 9143 EVT EltVT = Lo.getValueType(); 9144 9145 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9146 for (unsigned I = 0; I != 2; ++I) { 9147 SDValue Op = N0.getOperand(I); 9148 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9149 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9150 CFP->getValueAPF()); 9151 } else if (Op.isUndef()) { 9152 // Handled below based on what the other operand is. 9153 NewElts[I] = Op; 9154 } else { 9155 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9156 } 9157 } 9158 9159 // If one half is undef, and one is constant, perfer a splat vector rather 9160 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9161 // cheaper to use and may be free with a packed operation. 9162 if (NewElts[0].isUndef()) { 9163 if (isa<ConstantFPSDNode>(NewElts[1])) 9164 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9165 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9166 } 9167 9168 if (NewElts[1].isUndef()) { 9169 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9170 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9171 } 9172 9173 return DAG.getBuildVector(VT, SL, NewElts); 9174 } 9175 } 9176 9177 unsigned SrcOpc = N0.getOpcode(); 9178 9179 // If it's free to do so, push canonicalizes further up the source, which may 9180 // find a canonical source. 9181 // 9182 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9183 // sNaNs. 9184 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9185 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9186 if (CRHS && N0.hasOneUse()) { 9187 SDLoc SL(N); 9188 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9189 N0.getOperand(0)); 9190 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9191 DCI.AddToWorklist(Canon0.getNode()); 9192 9193 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9194 } 9195 } 9196 9197 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9198 } 9199 9200 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9201 switch (Opc) { 9202 case ISD::FMAXNUM: 9203 case ISD::FMAXNUM_IEEE: 9204 return AMDGPUISD::FMAX3; 9205 case ISD::SMAX: 9206 return AMDGPUISD::SMAX3; 9207 case ISD::UMAX: 9208 return AMDGPUISD::UMAX3; 9209 case ISD::FMINNUM: 9210 case ISD::FMINNUM_IEEE: 9211 return AMDGPUISD::FMIN3; 9212 case ISD::SMIN: 9213 return AMDGPUISD::SMIN3; 9214 case ISD::UMIN: 9215 return AMDGPUISD::UMIN3; 9216 default: 9217 llvm_unreachable("Not a min/max opcode"); 9218 } 9219 } 9220 9221 SDValue SITargetLowering::performIntMed3ImmCombine( 9222 SelectionDAG &DAG, const SDLoc &SL, 9223 SDValue Op0, SDValue Op1, bool Signed) const { 9224 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9225 if (!K1) 9226 return SDValue(); 9227 9228 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9229 if (!K0) 9230 return SDValue(); 9231 9232 if (Signed) { 9233 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9234 return SDValue(); 9235 } else { 9236 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9237 return SDValue(); 9238 } 9239 9240 EVT VT = K0->getValueType(0); 9241 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9242 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9243 return DAG.getNode(Med3Opc, SL, VT, 9244 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9245 } 9246 9247 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9248 MVT NVT = MVT::i32; 9249 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9250 9251 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9252 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9253 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9254 9255 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9256 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9257 } 9258 9259 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9260 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9261 return C; 9262 9263 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9264 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9265 return C; 9266 } 9267 9268 return nullptr; 9269 } 9270 9271 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9272 const SDLoc &SL, 9273 SDValue Op0, 9274 SDValue Op1) const { 9275 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9276 if (!K1) 9277 return SDValue(); 9278 9279 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9280 if (!K0) 9281 return SDValue(); 9282 9283 // Ordered >= (although NaN inputs should have folded away by now). 9284 if (K0->getValueAPF() > K1->getValueAPF()) 9285 return SDValue(); 9286 9287 const MachineFunction &MF = DAG.getMachineFunction(); 9288 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9289 9290 // TODO: Check IEEE bit enabled? 9291 EVT VT = Op0.getValueType(); 9292 if (Info->getMode().DX10Clamp) { 9293 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9294 // hardware fmed3 behavior converting to a min. 9295 // FIXME: Should this be allowing -0.0? 9296 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9297 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9298 } 9299 9300 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9301 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9302 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9303 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9304 // then give the other result, which is different from med3 with a NaN 9305 // input. 9306 SDValue Var = Op0.getOperand(0); 9307 if (!DAG.isKnownNeverSNaN(Var)) 9308 return SDValue(); 9309 9310 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9311 9312 if ((!K0->hasOneUse() || 9313 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9314 (!K1->hasOneUse() || 9315 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9316 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9317 Var, SDValue(K0, 0), SDValue(K1, 0)); 9318 } 9319 } 9320 9321 return SDValue(); 9322 } 9323 9324 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9325 DAGCombinerInfo &DCI) const { 9326 SelectionDAG &DAG = DCI.DAG; 9327 9328 EVT VT = N->getValueType(0); 9329 unsigned Opc = N->getOpcode(); 9330 SDValue Op0 = N->getOperand(0); 9331 SDValue Op1 = N->getOperand(1); 9332 9333 // Only do this if the inner op has one use since this will just increases 9334 // register pressure for no benefit. 9335 9336 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9337 !VT.isVector() && 9338 (VT == MVT::i32 || VT == MVT::f32 || 9339 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9340 // max(max(a, b), c) -> max3(a, b, c) 9341 // min(min(a, b), c) -> min3(a, b, c) 9342 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9343 SDLoc DL(N); 9344 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9345 DL, 9346 N->getValueType(0), 9347 Op0.getOperand(0), 9348 Op0.getOperand(1), 9349 Op1); 9350 } 9351 9352 // Try commuted. 9353 // max(a, max(b, c)) -> max3(a, b, c) 9354 // min(a, min(b, c)) -> min3(a, b, c) 9355 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9356 SDLoc DL(N); 9357 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9358 DL, 9359 N->getValueType(0), 9360 Op0, 9361 Op1.getOperand(0), 9362 Op1.getOperand(1)); 9363 } 9364 } 9365 9366 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9367 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9368 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9369 return Med3; 9370 } 9371 9372 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9373 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9374 return Med3; 9375 } 9376 9377 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9378 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9379 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9380 (Opc == AMDGPUISD::FMIN_LEGACY && 9381 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9382 (VT == MVT::f32 || VT == MVT::f64 || 9383 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9384 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9385 Op0.hasOneUse()) { 9386 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9387 return Res; 9388 } 9389 9390 return SDValue(); 9391 } 9392 9393 static bool isClampZeroToOne(SDValue A, SDValue B) { 9394 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9395 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9396 // FIXME: Should this be allowing -0.0? 9397 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9398 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9399 } 9400 } 9401 9402 return false; 9403 } 9404 9405 // FIXME: Should only worry about snans for version with chain. 9406 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9407 DAGCombinerInfo &DCI) const { 9408 EVT VT = N->getValueType(0); 9409 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9410 // NaNs. With a NaN input, the order of the operands may change the result. 9411 9412 SelectionDAG &DAG = DCI.DAG; 9413 SDLoc SL(N); 9414 9415 SDValue Src0 = N->getOperand(0); 9416 SDValue Src1 = N->getOperand(1); 9417 SDValue Src2 = N->getOperand(2); 9418 9419 if (isClampZeroToOne(Src0, Src1)) { 9420 // const_a, const_b, x -> clamp is safe in all cases including signaling 9421 // nans. 9422 // FIXME: Should this be allowing -0.0? 9423 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9424 } 9425 9426 const MachineFunction &MF = DAG.getMachineFunction(); 9427 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9428 9429 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9430 // handling no dx10-clamp? 9431 if (Info->getMode().DX10Clamp) { 9432 // If NaNs is clamped to 0, we are free to reorder the inputs. 9433 9434 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9435 std::swap(Src0, Src1); 9436 9437 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9438 std::swap(Src1, Src2); 9439 9440 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9441 std::swap(Src0, Src1); 9442 9443 if (isClampZeroToOne(Src1, Src2)) 9444 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9445 } 9446 9447 return SDValue(); 9448 } 9449 9450 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9451 DAGCombinerInfo &DCI) const { 9452 SDValue Src0 = N->getOperand(0); 9453 SDValue Src1 = N->getOperand(1); 9454 if (Src0.isUndef() && Src1.isUndef()) 9455 return DCI.DAG.getUNDEF(N->getValueType(0)); 9456 return SDValue(); 9457 } 9458 9459 SDValue SITargetLowering::performExtractVectorEltCombine( 9460 SDNode *N, DAGCombinerInfo &DCI) const { 9461 SDValue Vec = N->getOperand(0); 9462 SelectionDAG &DAG = DCI.DAG; 9463 9464 EVT VecVT = Vec.getValueType(); 9465 EVT EltVT = VecVT.getVectorElementType(); 9466 9467 if ((Vec.getOpcode() == ISD::FNEG || 9468 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9469 SDLoc SL(N); 9470 EVT EltVT = N->getValueType(0); 9471 SDValue Idx = N->getOperand(1); 9472 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9473 Vec.getOperand(0), Idx); 9474 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9475 } 9476 9477 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9478 // => 9479 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9480 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9481 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9482 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9483 SDLoc SL(N); 9484 EVT EltVT = N->getValueType(0); 9485 SDValue Idx = N->getOperand(1); 9486 unsigned Opc = Vec.getOpcode(); 9487 9488 switch(Opc) { 9489 default: 9490 break; 9491 // TODO: Support other binary operations. 9492 case ISD::FADD: 9493 case ISD::FSUB: 9494 case ISD::FMUL: 9495 case ISD::ADD: 9496 case ISD::UMIN: 9497 case ISD::UMAX: 9498 case ISD::SMIN: 9499 case ISD::SMAX: 9500 case ISD::FMAXNUM: 9501 case ISD::FMINNUM: 9502 case ISD::FMAXNUM_IEEE: 9503 case ISD::FMINNUM_IEEE: { 9504 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9505 Vec.getOperand(0), Idx); 9506 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9507 Vec.getOperand(1), Idx); 9508 9509 DCI.AddToWorklist(Elt0.getNode()); 9510 DCI.AddToWorklist(Elt1.getNode()); 9511 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9512 } 9513 } 9514 } 9515 9516 unsigned VecSize = VecVT.getSizeInBits(); 9517 unsigned EltSize = EltVT.getSizeInBits(); 9518 9519 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9520 // This elminates non-constant index and subsequent movrel or scratch access. 9521 // Sub-dword vectors of size 2 dword or less have better implementation. 9522 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9523 // instructions. 9524 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9525 !isa<ConstantSDNode>(N->getOperand(1))) { 9526 SDLoc SL(N); 9527 SDValue Idx = N->getOperand(1); 9528 SDValue V; 9529 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9530 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9531 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9532 if (I == 0) 9533 V = Elt; 9534 else 9535 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9536 } 9537 return V; 9538 } 9539 9540 if (!DCI.isBeforeLegalize()) 9541 return SDValue(); 9542 9543 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9544 // elements. This exposes more load reduction opportunities by replacing 9545 // multiple small extract_vector_elements with a single 32-bit extract. 9546 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9547 if (isa<MemSDNode>(Vec) && 9548 EltSize <= 16 && 9549 EltVT.isByteSized() && 9550 VecSize > 32 && 9551 VecSize % 32 == 0 && 9552 Idx) { 9553 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9554 9555 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9556 unsigned EltIdx = BitIndex / 32; 9557 unsigned LeftoverBitIdx = BitIndex % 32; 9558 SDLoc SL(N); 9559 9560 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9561 DCI.AddToWorklist(Cast.getNode()); 9562 9563 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9564 DAG.getConstant(EltIdx, SL, MVT::i32)); 9565 DCI.AddToWorklist(Elt.getNode()); 9566 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9567 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9568 DCI.AddToWorklist(Srl.getNode()); 9569 9570 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9571 DCI.AddToWorklist(Trunc.getNode()); 9572 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9573 } 9574 9575 return SDValue(); 9576 } 9577 9578 SDValue 9579 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9580 DAGCombinerInfo &DCI) const { 9581 SDValue Vec = N->getOperand(0); 9582 SDValue Idx = N->getOperand(2); 9583 EVT VecVT = Vec.getValueType(); 9584 EVT EltVT = VecVT.getVectorElementType(); 9585 unsigned VecSize = VecVT.getSizeInBits(); 9586 unsigned EltSize = EltVT.getSizeInBits(); 9587 9588 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9589 // => BUILD_VECTOR n x select (e, const-idx) 9590 // This elminates non-constant index and subsequent movrel or scratch access. 9591 // Sub-dword vectors of size 2 dword or less have better implementation. 9592 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9593 // instructions. 9594 if (isa<ConstantSDNode>(Idx) || 9595 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9596 return SDValue(); 9597 9598 SelectionDAG &DAG = DCI.DAG; 9599 SDLoc SL(N); 9600 SDValue Ins = N->getOperand(1); 9601 EVT IdxVT = Idx.getValueType(); 9602 9603 SmallVector<SDValue, 16> Ops; 9604 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9605 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9606 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9607 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9608 Ops.push_back(V); 9609 } 9610 9611 return DAG.getBuildVector(VecVT, SL, Ops); 9612 } 9613 9614 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9615 const SDNode *N0, 9616 const SDNode *N1) const { 9617 EVT VT = N0->getValueType(0); 9618 9619 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9620 // support denormals ever. 9621 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9622 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9623 getSubtarget()->hasMadF16())) && 9624 isOperationLegal(ISD::FMAD, VT)) 9625 return ISD::FMAD; 9626 9627 const TargetOptions &Options = DAG.getTarget().Options; 9628 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9629 (N0->getFlags().hasAllowContract() && 9630 N1->getFlags().hasAllowContract())) && 9631 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9632 return ISD::FMA; 9633 } 9634 9635 return 0; 9636 } 9637 9638 // For a reassociatable opcode perform: 9639 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9640 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9641 SelectionDAG &DAG) const { 9642 EVT VT = N->getValueType(0); 9643 if (VT != MVT::i32 && VT != MVT::i64) 9644 return SDValue(); 9645 9646 unsigned Opc = N->getOpcode(); 9647 SDValue Op0 = N->getOperand(0); 9648 SDValue Op1 = N->getOperand(1); 9649 9650 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9651 return SDValue(); 9652 9653 if (Op0->isDivergent()) 9654 std::swap(Op0, Op1); 9655 9656 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9657 return SDValue(); 9658 9659 SDValue Op2 = Op1.getOperand(1); 9660 Op1 = Op1.getOperand(0); 9661 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9662 return SDValue(); 9663 9664 if (Op1->isDivergent()) 9665 std::swap(Op1, Op2); 9666 9667 // If either operand is constant this will conflict with 9668 // DAGCombiner::ReassociateOps(). 9669 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9670 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9671 return SDValue(); 9672 9673 SDLoc SL(N); 9674 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9675 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9676 } 9677 9678 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9679 EVT VT, 9680 SDValue N0, SDValue N1, SDValue N2, 9681 bool Signed) { 9682 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9683 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9684 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9685 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9686 } 9687 9688 SDValue SITargetLowering::performAddCombine(SDNode *N, 9689 DAGCombinerInfo &DCI) const { 9690 SelectionDAG &DAG = DCI.DAG; 9691 EVT VT = N->getValueType(0); 9692 SDLoc SL(N); 9693 SDValue LHS = N->getOperand(0); 9694 SDValue RHS = N->getOperand(1); 9695 9696 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9697 && Subtarget->hasMad64_32() && 9698 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9699 VT.getScalarSizeInBits() <= 64) { 9700 if (LHS.getOpcode() != ISD::MUL) 9701 std::swap(LHS, RHS); 9702 9703 SDValue MulLHS = LHS.getOperand(0); 9704 SDValue MulRHS = LHS.getOperand(1); 9705 SDValue AddRHS = RHS; 9706 9707 // TODO: Maybe restrict if SGPR inputs. 9708 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9709 numBitsUnsigned(MulRHS, DAG) <= 32) { 9710 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9711 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9712 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9713 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9714 } 9715 9716 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9717 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9718 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9719 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9720 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9721 } 9722 9723 return SDValue(); 9724 } 9725 9726 if (SDValue V = reassociateScalarOps(N, DAG)) { 9727 return V; 9728 } 9729 9730 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9731 return SDValue(); 9732 9733 // add x, zext (setcc) => addcarry x, 0, setcc 9734 // add x, sext (setcc) => subcarry x, 0, setcc 9735 unsigned Opc = LHS.getOpcode(); 9736 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9737 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9738 std::swap(RHS, LHS); 9739 9740 Opc = RHS.getOpcode(); 9741 switch (Opc) { 9742 default: break; 9743 case ISD::ZERO_EXTEND: 9744 case ISD::SIGN_EXTEND: 9745 case ISD::ANY_EXTEND: { 9746 auto Cond = RHS.getOperand(0); 9747 // If this won't be a real VOPC output, we would still need to insert an 9748 // extra instruction anyway. 9749 if (!isBoolSGPR(Cond)) 9750 break; 9751 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9752 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9753 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9754 return DAG.getNode(Opc, SL, VTList, Args); 9755 } 9756 case ISD::ADDCARRY: { 9757 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9758 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9759 if (!C || C->getZExtValue() != 0) break; 9760 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9761 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9762 } 9763 } 9764 return SDValue(); 9765 } 9766 9767 SDValue SITargetLowering::performSubCombine(SDNode *N, 9768 DAGCombinerInfo &DCI) const { 9769 SelectionDAG &DAG = DCI.DAG; 9770 EVT VT = N->getValueType(0); 9771 9772 if (VT != MVT::i32) 9773 return SDValue(); 9774 9775 SDLoc SL(N); 9776 SDValue LHS = N->getOperand(0); 9777 SDValue RHS = N->getOperand(1); 9778 9779 // sub x, zext (setcc) => subcarry x, 0, setcc 9780 // sub x, sext (setcc) => addcarry x, 0, setcc 9781 unsigned Opc = RHS.getOpcode(); 9782 switch (Opc) { 9783 default: break; 9784 case ISD::ZERO_EXTEND: 9785 case ISD::SIGN_EXTEND: 9786 case ISD::ANY_EXTEND: { 9787 auto Cond = RHS.getOperand(0); 9788 // If this won't be a real VOPC output, we would still need to insert an 9789 // extra instruction anyway. 9790 if (!isBoolSGPR(Cond)) 9791 break; 9792 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9793 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9794 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9795 return DAG.getNode(Opc, SL, VTList, Args); 9796 } 9797 } 9798 9799 if (LHS.getOpcode() == ISD::SUBCARRY) { 9800 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9801 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9802 if (!C || !C->isNullValue()) 9803 return SDValue(); 9804 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9805 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9806 } 9807 return SDValue(); 9808 } 9809 9810 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9811 DAGCombinerInfo &DCI) const { 9812 9813 if (N->getValueType(0) != MVT::i32) 9814 return SDValue(); 9815 9816 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9817 if (!C || C->getZExtValue() != 0) 9818 return SDValue(); 9819 9820 SelectionDAG &DAG = DCI.DAG; 9821 SDValue LHS = N->getOperand(0); 9822 9823 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9824 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9825 unsigned LHSOpc = LHS.getOpcode(); 9826 unsigned Opc = N->getOpcode(); 9827 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9828 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9829 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9830 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9831 } 9832 return SDValue(); 9833 } 9834 9835 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9836 DAGCombinerInfo &DCI) const { 9837 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9838 return SDValue(); 9839 9840 SelectionDAG &DAG = DCI.DAG; 9841 EVT VT = N->getValueType(0); 9842 9843 SDLoc SL(N); 9844 SDValue LHS = N->getOperand(0); 9845 SDValue RHS = N->getOperand(1); 9846 9847 // These should really be instruction patterns, but writing patterns with 9848 // source modiifiers is a pain. 9849 9850 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9851 if (LHS.getOpcode() == ISD::FADD) { 9852 SDValue A = LHS.getOperand(0); 9853 if (A == LHS.getOperand(1)) { 9854 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9855 if (FusedOp != 0) { 9856 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9857 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9858 } 9859 } 9860 } 9861 9862 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9863 if (RHS.getOpcode() == ISD::FADD) { 9864 SDValue A = RHS.getOperand(0); 9865 if (A == RHS.getOperand(1)) { 9866 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9867 if (FusedOp != 0) { 9868 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9869 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9870 } 9871 } 9872 } 9873 9874 return SDValue(); 9875 } 9876 9877 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9878 DAGCombinerInfo &DCI) const { 9879 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9880 return SDValue(); 9881 9882 SelectionDAG &DAG = DCI.DAG; 9883 SDLoc SL(N); 9884 EVT VT = N->getValueType(0); 9885 assert(!VT.isVector()); 9886 9887 // Try to get the fneg to fold into the source modifier. This undoes generic 9888 // DAG combines and folds them into the mad. 9889 // 9890 // Only do this if we are not trying to support denormals. v_mad_f32 does 9891 // not support denormals ever. 9892 SDValue LHS = N->getOperand(0); 9893 SDValue RHS = N->getOperand(1); 9894 if (LHS.getOpcode() == ISD::FADD) { 9895 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9896 SDValue A = LHS.getOperand(0); 9897 if (A == LHS.getOperand(1)) { 9898 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9899 if (FusedOp != 0){ 9900 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9901 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9902 9903 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9904 } 9905 } 9906 } 9907 9908 if (RHS.getOpcode() == ISD::FADD) { 9909 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9910 9911 SDValue A = RHS.getOperand(0); 9912 if (A == RHS.getOperand(1)) { 9913 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9914 if (FusedOp != 0){ 9915 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9916 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9917 } 9918 } 9919 } 9920 9921 return SDValue(); 9922 } 9923 9924 SDValue SITargetLowering::performFMACombine(SDNode *N, 9925 DAGCombinerInfo &DCI) const { 9926 SelectionDAG &DAG = DCI.DAG; 9927 EVT VT = N->getValueType(0); 9928 SDLoc SL(N); 9929 9930 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9931 return SDValue(); 9932 9933 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9934 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9935 SDValue Op1 = N->getOperand(0); 9936 SDValue Op2 = N->getOperand(1); 9937 SDValue FMA = N->getOperand(2); 9938 9939 if (FMA.getOpcode() != ISD::FMA || 9940 Op1.getOpcode() != ISD::FP_EXTEND || 9941 Op2.getOpcode() != ISD::FP_EXTEND) 9942 return SDValue(); 9943 9944 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9945 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9946 // is sufficient to allow generaing fdot2. 9947 const TargetOptions &Options = DAG.getTarget().Options; 9948 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9949 (N->getFlags().hasAllowContract() && 9950 FMA->getFlags().hasAllowContract())) { 9951 Op1 = Op1.getOperand(0); 9952 Op2 = Op2.getOperand(0); 9953 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9954 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9955 return SDValue(); 9956 9957 SDValue Vec1 = Op1.getOperand(0); 9958 SDValue Idx1 = Op1.getOperand(1); 9959 SDValue Vec2 = Op2.getOperand(0); 9960 9961 SDValue FMAOp1 = FMA.getOperand(0); 9962 SDValue FMAOp2 = FMA.getOperand(1); 9963 SDValue FMAAcc = FMA.getOperand(2); 9964 9965 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9966 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9967 return SDValue(); 9968 9969 FMAOp1 = FMAOp1.getOperand(0); 9970 FMAOp2 = FMAOp2.getOperand(0); 9971 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9972 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9973 return SDValue(); 9974 9975 SDValue Vec3 = FMAOp1.getOperand(0); 9976 SDValue Vec4 = FMAOp2.getOperand(0); 9977 SDValue Idx2 = FMAOp1.getOperand(1); 9978 9979 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9980 // Idx1 and Idx2 cannot be the same. 9981 Idx1 == Idx2) 9982 return SDValue(); 9983 9984 if (Vec1 == Vec2 || Vec3 == Vec4) 9985 return SDValue(); 9986 9987 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9988 return SDValue(); 9989 9990 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9991 (Vec1 == Vec4 && Vec2 == Vec3)) { 9992 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9993 DAG.getTargetConstant(0, SL, MVT::i1)); 9994 } 9995 } 9996 return SDValue(); 9997 } 9998 9999 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10000 DAGCombinerInfo &DCI) const { 10001 SelectionDAG &DAG = DCI.DAG; 10002 SDLoc SL(N); 10003 10004 SDValue LHS = N->getOperand(0); 10005 SDValue RHS = N->getOperand(1); 10006 EVT VT = LHS.getValueType(); 10007 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10008 10009 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10010 if (!CRHS) { 10011 CRHS = dyn_cast<ConstantSDNode>(LHS); 10012 if (CRHS) { 10013 std::swap(LHS, RHS); 10014 CC = getSetCCSwappedOperands(CC); 10015 } 10016 } 10017 10018 if (CRHS) { 10019 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10020 isBoolSGPR(LHS.getOperand(0))) { 10021 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10022 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10023 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10024 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10025 if ((CRHS->isAllOnesValue() && 10026 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10027 (CRHS->isNullValue() && 10028 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10029 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10030 DAG.getConstant(-1, SL, MVT::i1)); 10031 if ((CRHS->isAllOnesValue() && 10032 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10033 (CRHS->isNullValue() && 10034 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10035 return LHS.getOperand(0); 10036 } 10037 10038 uint64_t CRHSVal = CRHS->getZExtValue(); 10039 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10040 LHS.getOpcode() == ISD::SELECT && 10041 isa<ConstantSDNode>(LHS.getOperand(1)) && 10042 isa<ConstantSDNode>(LHS.getOperand(2)) && 10043 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10044 isBoolSGPR(LHS.getOperand(0))) { 10045 // Given CT != FT: 10046 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10047 // setcc (select cc, CT, CF), CF, ne => cc 10048 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10049 // setcc (select cc, CT, CF), CT, eq => cc 10050 uint64_t CT = LHS.getConstantOperandVal(1); 10051 uint64_t CF = LHS.getConstantOperandVal(2); 10052 10053 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10054 (CT == CRHSVal && CC == ISD::SETNE)) 10055 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10056 DAG.getConstant(-1, SL, MVT::i1)); 10057 if ((CF == CRHSVal && CC == ISD::SETNE) || 10058 (CT == CRHSVal && CC == ISD::SETEQ)) 10059 return LHS.getOperand(0); 10060 } 10061 } 10062 10063 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10064 VT != MVT::f16)) 10065 return SDValue(); 10066 10067 // Match isinf/isfinite pattern 10068 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10069 // (fcmp one (fabs x), inf) -> (fp_class x, 10070 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10071 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10072 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10073 if (!CRHS) 10074 return SDValue(); 10075 10076 const APFloat &APF = CRHS->getValueAPF(); 10077 if (APF.isInfinity() && !APF.isNegative()) { 10078 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10079 SIInstrFlags::N_INFINITY; 10080 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10081 SIInstrFlags::P_ZERO | 10082 SIInstrFlags::N_NORMAL | 10083 SIInstrFlags::P_NORMAL | 10084 SIInstrFlags::N_SUBNORMAL | 10085 SIInstrFlags::P_SUBNORMAL; 10086 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10087 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10088 DAG.getConstant(Mask, SL, MVT::i32)); 10089 } 10090 } 10091 10092 return SDValue(); 10093 } 10094 10095 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10096 DAGCombinerInfo &DCI) const { 10097 SelectionDAG &DAG = DCI.DAG; 10098 SDLoc SL(N); 10099 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10100 10101 SDValue Src = N->getOperand(0); 10102 SDValue Shift = N->getOperand(0); 10103 10104 // TODO: Extend type shouldn't matter (assuming legal types). 10105 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10106 Shift = Shift.getOperand(0); 10107 10108 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10109 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10110 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10111 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10112 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10113 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10114 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10115 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10116 SDLoc(Shift.getOperand(0)), MVT::i32); 10117 10118 unsigned ShiftOffset = 8 * Offset; 10119 if (Shift.getOpcode() == ISD::SHL) 10120 ShiftOffset -= C->getZExtValue(); 10121 else 10122 ShiftOffset += C->getZExtValue(); 10123 10124 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10125 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10126 MVT::f32, Shift); 10127 } 10128 } 10129 } 10130 10131 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10132 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10133 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10134 // We simplified Src. If this node is not dead, visit it again so it is 10135 // folded properly. 10136 if (N->getOpcode() != ISD::DELETED_NODE) 10137 DCI.AddToWorklist(N); 10138 return SDValue(N, 0); 10139 } 10140 10141 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10142 if (SDValue DemandedSrc = 10143 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10144 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10145 10146 return SDValue(); 10147 } 10148 10149 SDValue SITargetLowering::performClampCombine(SDNode *N, 10150 DAGCombinerInfo &DCI) const { 10151 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10152 if (!CSrc) 10153 return SDValue(); 10154 10155 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10156 const APFloat &F = CSrc->getValueAPF(); 10157 APFloat Zero = APFloat::getZero(F.getSemantics()); 10158 if (F < Zero || 10159 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10160 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10161 } 10162 10163 APFloat One(F.getSemantics(), "1.0"); 10164 if (F > One) 10165 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10166 10167 return SDValue(CSrc, 0); 10168 } 10169 10170 10171 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10172 DAGCombinerInfo &DCI) const { 10173 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10174 return SDValue(); 10175 switch (N->getOpcode()) { 10176 default: 10177 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10178 case ISD::ADD: 10179 return performAddCombine(N, DCI); 10180 case ISD::SUB: 10181 return performSubCombine(N, DCI); 10182 case ISD::ADDCARRY: 10183 case ISD::SUBCARRY: 10184 return performAddCarrySubCarryCombine(N, DCI); 10185 case ISD::FADD: 10186 return performFAddCombine(N, DCI); 10187 case ISD::FSUB: 10188 return performFSubCombine(N, DCI); 10189 case ISD::SETCC: 10190 return performSetCCCombine(N, DCI); 10191 case ISD::FMAXNUM: 10192 case ISD::FMINNUM: 10193 case ISD::FMAXNUM_IEEE: 10194 case ISD::FMINNUM_IEEE: 10195 case ISD::SMAX: 10196 case ISD::SMIN: 10197 case ISD::UMAX: 10198 case ISD::UMIN: 10199 case AMDGPUISD::FMIN_LEGACY: 10200 case AMDGPUISD::FMAX_LEGACY: 10201 return performMinMaxCombine(N, DCI); 10202 case ISD::FMA: 10203 return performFMACombine(N, DCI); 10204 case ISD::LOAD: { 10205 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10206 return Widended; 10207 LLVM_FALLTHROUGH; 10208 } 10209 case ISD::STORE: 10210 case ISD::ATOMIC_LOAD: 10211 case ISD::ATOMIC_STORE: 10212 case ISD::ATOMIC_CMP_SWAP: 10213 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10214 case ISD::ATOMIC_SWAP: 10215 case ISD::ATOMIC_LOAD_ADD: 10216 case ISD::ATOMIC_LOAD_SUB: 10217 case ISD::ATOMIC_LOAD_AND: 10218 case ISD::ATOMIC_LOAD_OR: 10219 case ISD::ATOMIC_LOAD_XOR: 10220 case ISD::ATOMIC_LOAD_NAND: 10221 case ISD::ATOMIC_LOAD_MIN: 10222 case ISD::ATOMIC_LOAD_MAX: 10223 case ISD::ATOMIC_LOAD_UMIN: 10224 case ISD::ATOMIC_LOAD_UMAX: 10225 case ISD::ATOMIC_LOAD_FADD: 10226 case AMDGPUISD::ATOMIC_INC: 10227 case AMDGPUISD::ATOMIC_DEC: 10228 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10229 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10230 if (DCI.isBeforeLegalize()) 10231 break; 10232 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10233 case ISD::AND: 10234 return performAndCombine(N, DCI); 10235 case ISD::OR: 10236 return performOrCombine(N, DCI); 10237 case ISD::XOR: 10238 return performXorCombine(N, DCI); 10239 case ISD::ZERO_EXTEND: 10240 return performZeroExtendCombine(N, DCI); 10241 case ISD::SIGN_EXTEND_INREG: 10242 return performSignExtendInRegCombine(N , DCI); 10243 case AMDGPUISD::FP_CLASS: 10244 return performClassCombine(N, DCI); 10245 case ISD::FCANONICALIZE: 10246 return performFCanonicalizeCombine(N, DCI); 10247 case AMDGPUISD::RCP: 10248 return performRcpCombine(N, DCI); 10249 case AMDGPUISD::FRACT: 10250 case AMDGPUISD::RSQ: 10251 case AMDGPUISD::RCP_LEGACY: 10252 case AMDGPUISD::RCP_IFLAG: 10253 case AMDGPUISD::RSQ_CLAMP: 10254 case AMDGPUISD::LDEXP: { 10255 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10256 SDValue Src = N->getOperand(0); 10257 if (Src.isUndef()) 10258 return Src; 10259 break; 10260 } 10261 case ISD::SINT_TO_FP: 10262 case ISD::UINT_TO_FP: 10263 return performUCharToFloatCombine(N, DCI); 10264 case AMDGPUISD::CVT_F32_UBYTE0: 10265 case AMDGPUISD::CVT_F32_UBYTE1: 10266 case AMDGPUISD::CVT_F32_UBYTE2: 10267 case AMDGPUISD::CVT_F32_UBYTE3: 10268 return performCvtF32UByteNCombine(N, DCI); 10269 case AMDGPUISD::FMED3: 10270 return performFMed3Combine(N, DCI); 10271 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10272 return performCvtPkRTZCombine(N, DCI); 10273 case AMDGPUISD::CLAMP: 10274 return performClampCombine(N, DCI); 10275 case ISD::SCALAR_TO_VECTOR: { 10276 SelectionDAG &DAG = DCI.DAG; 10277 EVT VT = N->getValueType(0); 10278 10279 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10280 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10281 SDLoc SL(N); 10282 SDValue Src = N->getOperand(0); 10283 EVT EltVT = Src.getValueType(); 10284 if (EltVT == MVT::f16) 10285 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10286 10287 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10288 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10289 } 10290 10291 break; 10292 } 10293 case ISD::EXTRACT_VECTOR_ELT: 10294 return performExtractVectorEltCombine(N, DCI); 10295 case ISD::INSERT_VECTOR_ELT: 10296 return performInsertVectorEltCombine(N, DCI); 10297 } 10298 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10299 } 10300 10301 /// Helper function for adjustWritemask 10302 static unsigned SubIdx2Lane(unsigned Idx) { 10303 switch (Idx) { 10304 default: return 0; 10305 case AMDGPU::sub0: return 0; 10306 case AMDGPU::sub1: return 1; 10307 case AMDGPU::sub2: return 2; 10308 case AMDGPU::sub3: return 3; 10309 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10310 } 10311 } 10312 10313 /// Adjust the writemask of MIMG instructions 10314 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10315 SelectionDAG &DAG) const { 10316 unsigned Opcode = Node->getMachineOpcode(); 10317 10318 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10319 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10320 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10321 return Node; // not implemented for D16 10322 10323 SDNode *Users[5] = { nullptr }; 10324 unsigned Lane = 0; 10325 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10326 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10327 unsigned NewDmask = 0; 10328 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10329 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10330 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10331 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10332 unsigned TFCLane = 0; 10333 bool HasChain = Node->getNumValues() > 1; 10334 10335 if (OldDmask == 0) { 10336 // These are folded out, but on the chance it happens don't assert. 10337 return Node; 10338 } 10339 10340 unsigned OldBitsSet = countPopulation(OldDmask); 10341 // Work out which is the TFE/LWE lane if that is enabled. 10342 if (UsesTFC) { 10343 TFCLane = OldBitsSet; 10344 } 10345 10346 // Try to figure out the used register components 10347 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10348 I != E; ++I) { 10349 10350 // Don't look at users of the chain. 10351 if (I.getUse().getResNo() != 0) 10352 continue; 10353 10354 // Abort if we can't understand the usage 10355 if (!I->isMachineOpcode() || 10356 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10357 return Node; 10358 10359 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10360 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10361 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10362 // set, etc. 10363 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10364 10365 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10366 if (UsesTFC && Lane == TFCLane) { 10367 Users[Lane] = *I; 10368 } else { 10369 // Set which texture component corresponds to the lane. 10370 unsigned Comp; 10371 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10372 Comp = countTrailingZeros(Dmask); 10373 Dmask &= ~(1 << Comp); 10374 } 10375 10376 // Abort if we have more than one user per component. 10377 if (Users[Lane]) 10378 return Node; 10379 10380 Users[Lane] = *I; 10381 NewDmask |= 1 << Comp; 10382 } 10383 } 10384 10385 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10386 bool NoChannels = !NewDmask; 10387 if (NoChannels) { 10388 if (!UsesTFC) { 10389 // No uses of the result and not using TFC. Then do nothing. 10390 return Node; 10391 } 10392 // If the original dmask has one channel - then nothing to do 10393 if (OldBitsSet == 1) 10394 return Node; 10395 // Use an arbitrary dmask - required for the instruction to work 10396 NewDmask = 1; 10397 } 10398 // Abort if there's no change 10399 if (NewDmask == OldDmask) 10400 return Node; 10401 10402 unsigned BitsSet = countPopulation(NewDmask); 10403 10404 // Check for TFE or LWE - increase the number of channels by one to account 10405 // for the extra return value 10406 // This will need adjustment for D16 if this is also included in 10407 // adjustWriteMask (this function) but at present D16 are excluded. 10408 unsigned NewChannels = BitsSet + UsesTFC; 10409 10410 int NewOpcode = 10411 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10412 assert(NewOpcode != -1 && 10413 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10414 "failed to find equivalent MIMG op"); 10415 10416 // Adjust the writemask in the node 10417 SmallVector<SDValue, 12> Ops; 10418 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10419 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10420 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10421 10422 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10423 10424 MVT ResultVT = NewChannels == 1 ? 10425 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10426 NewChannels == 5 ? 8 : NewChannels); 10427 SDVTList NewVTList = HasChain ? 10428 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10429 10430 10431 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10432 NewVTList, Ops); 10433 10434 if (HasChain) { 10435 // Update chain. 10436 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10437 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10438 } 10439 10440 if (NewChannels == 1) { 10441 assert(Node->hasNUsesOfValue(1, 0)); 10442 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10443 SDLoc(Node), Users[Lane]->getValueType(0), 10444 SDValue(NewNode, 0)); 10445 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10446 return nullptr; 10447 } 10448 10449 // Update the users of the node with the new indices 10450 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10451 SDNode *User = Users[i]; 10452 if (!User) { 10453 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10454 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10455 if (i || !NoChannels) 10456 continue; 10457 } else { 10458 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10459 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10460 } 10461 10462 switch (Idx) { 10463 default: break; 10464 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10465 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10466 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10467 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10468 } 10469 } 10470 10471 DAG.RemoveDeadNode(Node); 10472 return nullptr; 10473 } 10474 10475 static bool isFrameIndexOp(SDValue Op) { 10476 if (Op.getOpcode() == ISD::AssertZext) 10477 Op = Op.getOperand(0); 10478 10479 return isa<FrameIndexSDNode>(Op); 10480 } 10481 10482 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10483 /// with frame index operands. 10484 /// LLVM assumes that inputs are to these instructions are registers. 10485 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10486 SelectionDAG &DAG) const { 10487 if (Node->getOpcode() == ISD::CopyToReg) { 10488 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10489 SDValue SrcVal = Node->getOperand(2); 10490 10491 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10492 // to try understanding copies to physical registers. 10493 if (SrcVal.getValueType() == MVT::i1 && 10494 Register::isPhysicalRegister(DestReg->getReg())) { 10495 SDLoc SL(Node); 10496 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10497 SDValue VReg = DAG.getRegister( 10498 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10499 10500 SDNode *Glued = Node->getGluedNode(); 10501 SDValue ToVReg 10502 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10503 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10504 SDValue ToResultReg 10505 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10506 VReg, ToVReg.getValue(1)); 10507 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10508 DAG.RemoveDeadNode(Node); 10509 return ToResultReg.getNode(); 10510 } 10511 } 10512 10513 SmallVector<SDValue, 8> Ops; 10514 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10515 if (!isFrameIndexOp(Node->getOperand(i))) { 10516 Ops.push_back(Node->getOperand(i)); 10517 continue; 10518 } 10519 10520 SDLoc DL(Node); 10521 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10522 Node->getOperand(i).getValueType(), 10523 Node->getOperand(i)), 0)); 10524 } 10525 10526 return DAG.UpdateNodeOperands(Node, Ops); 10527 } 10528 10529 /// Fold the instructions after selecting them. 10530 /// Returns null if users were already updated. 10531 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10532 SelectionDAG &DAG) const { 10533 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10534 unsigned Opcode = Node->getMachineOpcode(); 10535 10536 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10537 !TII->isGather4(Opcode)) { 10538 return adjustWritemask(Node, DAG); 10539 } 10540 10541 if (Opcode == AMDGPU::INSERT_SUBREG || 10542 Opcode == AMDGPU::REG_SEQUENCE) { 10543 legalizeTargetIndependentNode(Node, DAG); 10544 return Node; 10545 } 10546 10547 switch (Opcode) { 10548 case AMDGPU::V_DIV_SCALE_F32: 10549 case AMDGPU::V_DIV_SCALE_F64: { 10550 // Satisfy the operand register constraint when one of the inputs is 10551 // undefined. Ordinarily each undef value will have its own implicit_def of 10552 // a vreg, so force these to use a single register. 10553 SDValue Src0 = Node->getOperand(0); 10554 SDValue Src1 = Node->getOperand(1); 10555 SDValue Src2 = Node->getOperand(2); 10556 10557 if ((Src0.isMachineOpcode() && 10558 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10559 (Src0 == Src1 || Src0 == Src2)) 10560 break; 10561 10562 MVT VT = Src0.getValueType().getSimpleVT(); 10563 const TargetRegisterClass *RC = 10564 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10565 10566 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10567 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10568 10569 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10570 UndefReg, Src0, SDValue()); 10571 10572 // src0 must be the same register as src1 or src2, even if the value is 10573 // undefined, so make sure we don't violate this constraint. 10574 if (Src0.isMachineOpcode() && 10575 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10576 if (Src1.isMachineOpcode() && 10577 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10578 Src0 = Src1; 10579 else if (Src2.isMachineOpcode() && 10580 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10581 Src0 = Src2; 10582 else { 10583 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10584 Src0 = UndefReg; 10585 Src1 = UndefReg; 10586 } 10587 } else 10588 break; 10589 10590 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10591 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10592 Ops.push_back(Node->getOperand(I)); 10593 10594 Ops.push_back(ImpDef.getValue(1)); 10595 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10596 } 10597 default: 10598 break; 10599 } 10600 10601 return Node; 10602 } 10603 10604 /// Assign the register class depending on the number of 10605 /// bits set in the writemask 10606 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10607 SDNode *Node) const { 10608 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10609 10610 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10611 10612 if (TII->isVOP3(MI.getOpcode())) { 10613 // Make sure constant bus requirements are respected. 10614 TII->legalizeOperandsVOP3(MRI, MI); 10615 10616 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10617 // This saves a chain-copy of registers and better ballance register 10618 // use between vgpr and agpr as agpr tuples tend to be big. 10619 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10620 unsigned Opc = MI.getOpcode(); 10621 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10622 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10623 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10624 if (I == -1) 10625 break; 10626 MachineOperand &Op = MI.getOperand(I); 10627 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10628 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10629 !Register::isVirtualRegister(Op.getReg()) || 10630 !TRI->isAGPR(MRI, Op.getReg())) 10631 continue; 10632 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10633 if (!Src || !Src->isCopy() || 10634 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10635 continue; 10636 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10637 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10638 // All uses of agpr64 and agpr32 can also accept vgpr except for 10639 // v_accvgpr_read, but we do not produce agpr reads during selection, 10640 // so no use checks are needed. 10641 MRI.setRegClass(Op.getReg(), NewRC); 10642 } 10643 } 10644 10645 return; 10646 } 10647 10648 // Replace unused atomics with the no return version. 10649 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10650 if (NoRetAtomicOp != -1) { 10651 if (!Node->hasAnyUseOfValue(0)) { 10652 MI.setDesc(TII->get(NoRetAtomicOp)); 10653 MI.RemoveOperand(0); 10654 return; 10655 } 10656 10657 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10658 // instruction, because the return type of these instructions is a vec2 of 10659 // the memory type, so it can be tied to the input operand. 10660 // This means these instructions always have a use, so we need to add a 10661 // special case to check if the atomic has only one extract_subreg use, 10662 // which itself has no uses. 10663 if ((Node->hasNUsesOfValue(1, 0) && 10664 Node->use_begin()->isMachineOpcode() && 10665 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10666 !Node->use_begin()->hasAnyUseOfValue(0))) { 10667 Register Def = MI.getOperand(0).getReg(); 10668 10669 // Change this into a noret atomic. 10670 MI.setDesc(TII->get(NoRetAtomicOp)); 10671 MI.RemoveOperand(0); 10672 10673 // If we only remove the def operand from the atomic instruction, the 10674 // extract_subreg will be left with a use of a vreg without a def. 10675 // So we need to insert an implicit_def to avoid machine verifier 10676 // errors. 10677 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10678 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10679 } 10680 return; 10681 } 10682 } 10683 10684 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10685 uint64_t Val) { 10686 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10687 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10688 } 10689 10690 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10691 const SDLoc &DL, 10692 SDValue Ptr) const { 10693 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10694 10695 // Build the half of the subregister with the constants before building the 10696 // full 128-bit register. If we are building multiple resource descriptors, 10697 // this will allow CSEing of the 2-component register. 10698 const SDValue Ops0[] = { 10699 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10700 buildSMovImm32(DAG, DL, 0), 10701 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10702 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10703 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10704 }; 10705 10706 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10707 MVT::v2i32, Ops0), 0); 10708 10709 // Combine the constants and the pointer. 10710 const SDValue Ops1[] = { 10711 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10712 Ptr, 10713 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10714 SubRegHi, 10715 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10716 }; 10717 10718 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10719 } 10720 10721 /// Return a resource descriptor with the 'Add TID' bit enabled 10722 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10723 /// of the resource descriptor) to create an offset, which is added to 10724 /// the resource pointer. 10725 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10726 SDValue Ptr, uint32_t RsrcDword1, 10727 uint64_t RsrcDword2And3) const { 10728 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10729 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10730 if (RsrcDword1) { 10731 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10732 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10733 0); 10734 } 10735 10736 SDValue DataLo = buildSMovImm32(DAG, DL, 10737 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10738 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10739 10740 const SDValue Ops[] = { 10741 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10742 PtrLo, 10743 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10744 PtrHi, 10745 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10746 DataLo, 10747 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10748 DataHi, 10749 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10750 }; 10751 10752 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10753 } 10754 10755 //===----------------------------------------------------------------------===// 10756 // SI Inline Assembly Support 10757 //===----------------------------------------------------------------------===// 10758 10759 std::pair<unsigned, const TargetRegisterClass *> 10760 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10761 StringRef Constraint, 10762 MVT VT) const { 10763 const TargetRegisterClass *RC = nullptr; 10764 if (Constraint.size() == 1) { 10765 const unsigned BitWidth = VT.getSizeInBits(); 10766 switch (Constraint[0]) { 10767 default: 10768 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10769 case 's': 10770 case 'r': 10771 switch (BitWidth) { 10772 case 16: 10773 RC = &AMDGPU::SReg_32RegClass; 10774 break; 10775 case 64: 10776 RC = &AMDGPU::SGPR_64RegClass; 10777 break; 10778 default: 10779 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 10780 if (!RC) 10781 return std::make_pair(0U, nullptr); 10782 break; 10783 } 10784 break; 10785 case 'v': 10786 switch (BitWidth) { 10787 case 16: 10788 RC = &AMDGPU::VGPR_32RegClass; 10789 break; 10790 default: 10791 RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth); 10792 if (!RC) 10793 return std::make_pair(0U, nullptr); 10794 break; 10795 } 10796 break; 10797 case 'a': 10798 if (!Subtarget->hasMAIInsts()) 10799 break; 10800 switch (BitWidth) { 10801 case 16: 10802 RC = &AMDGPU::AGPR_32RegClass; 10803 break; 10804 default: 10805 RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth); 10806 if (!RC) 10807 return std::make_pair(0U, nullptr); 10808 break; 10809 } 10810 break; 10811 } 10812 // We actually support i128, i16 and f16 as inline parameters 10813 // even if they are not reported as legal 10814 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10815 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10816 return std::make_pair(0U, RC); 10817 } 10818 10819 if (Constraint.size() > 1) { 10820 if (Constraint[1] == 'v') { 10821 RC = &AMDGPU::VGPR_32RegClass; 10822 } else if (Constraint[1] == 's') { 10823 RC = &AMDGPU::SGPR_32RegClass; 10824 } else if (Constraint[1] == 'a') { 10825 RC = &AMDGPU::AGPR_32RegClass; 10826 } 10827 10828 if (RC) { 10829 uint32_t Idx; 10830 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10831 if (!Failed && Idx < RC->getNumRegs()) 10832 return std::make_pair(RC->getRegister(Idx), RC); 10833 } 10834 } 10835 10836 // FIXME: Returns VS_32 for physical SGPR constraints 10837 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10838 } 10839 10840 SITargetLowering::ConstraintType 10841 SITargetLowering::getConstraintType(StringRef Constraint) const { 10842 if (Constraint.size() == 1) { 10843 switch (Constraint[0]) { 10844 default: break; 10845 case 's': 10846 case 'v': 10847 case 'a': 10848 return C_RegisterClass; 10849 } 10850 } 10851 return TargetLowering::getConstraintType(Constraint); 10852 } 10853 10854 // Figure out which registers should be reserved for stack access. Only after 10855 // the function is legalized do we know all of the non-spill stack objects or if 10856 // calls are present. 10857 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10858 MachineRegisterInfo &MRI = MF.getRegInfo(); 10859 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10860 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10861 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10862 10863 if (Info->isEntryFunction()) { 10864 // Callable functions have fixed registers used for stack access. 10865 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10866 } 10867 10868 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10869 Info->getStackPtrOffsetReg())); 10870 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10871 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10872 10873 // We need to worry about replacing the default register with itself in case 10874 // of MIR testcases missing the MFI. 10875 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10876 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10877 10878 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10879 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10880 10881 Info->limitOccupancy(MF); 10882 10883 if (ST.isWave32() && !MF.empty()) { 10884 // Add VCC_HI def because many instructions marked as imp-use VCC where 10885 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10886 // having a use of undef. 10887 10888 const SIInstrInfo *TII = ST.getInstrInfo(); 10889 DebugLoc DL; 10890 10891 MachineBasicBlock &MBB = MF.front(); 10892 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10893 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10894 10895 for (auto &MBB : MF) { 10896 for (auto &MI : MBB) { 10897 TII->fixImplicitOperands(MI); 10898 } 10899 } 10900 } 10901 10902 TargetLoweringBase::finalizeLowering(MF); 10903 10904 // Allocate a VGPR for future SGPR Spill if 10905 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 10906 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 10907 if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill && 10908 !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects()) 10909 Info->reserveVGPRforSGPRSpills(MF); 10910 } 10911 10912 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10913 KnownBits &Known, 10914 const APInt &DemandedElts, 10915 const SelectionDAG &DAG, 10916 unsigned Depth) const { 10917 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10918 DAG, Depth); 10919 10920 // Set the high bits to zero based on the maximum allowed scratch size per 10921 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10922 // calculation won't overflow, so assume the sign bit is never set. 10923 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10924 } 10925 10926 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10927 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10928 const Align CacheLineAlign = Align(64); 10929 10930 // Pre-GFX10 target did not benefit from loop alignment 10931 if (!ML || DisableLoopAlignment || 10932 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10933 getSubtarget()->hasInstFwdPrefetchBug()) 10934 return PrefAlign; 10935 10936 // On GFX10 I$ is 4 x 64 bytes cache lines. 10937 // By default prefetcher keeps one cache line behind and reads two ahead. 10938 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10939 // behind and one ahead. 10940 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10941 // If loop fits 64 bytes it always spans no more than two cache lines and 10942 // does not need an alignment. 10943 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10944 // Else if loop is less or equal 192 bytes we need two lines behind. 10945 10946 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10947 const MachineBasicBlock *Header = ML->getHeader(); 10948 if (Header->getAlignment() != PrefAlign) 10949 return Header->getAlignment(); // Already processed. 10950 10951 unsigned LoopSize = 0; 10952 for (const MachineBasicBlock *MBB : ML->blocks()) { 10953 // If inner loop block is aligned assume in average half of the alignment 10954 // size to be added as nops. 10955 if (MBB != Header) 10956 LoopSize += MBB->getAlignment().value() / 2; 10957 10958 for (const MachineInstr &MI : *MBB) { 10959 LoopSize += TII->getInstSizeInBytes(MI); 10960 if (LoopSize > 192) 10961 return PrefAlign; 10962 } 10963 } 10964 10965 if (LoopSize <= 64) 10966 return PrefAlign; 10967 10968 if (LoopSize <= 128) 10969 return CacheLineAlign; 10970 10971 // If any of parent loops is surrounded by prefetch instructions do not 10972 // insert new for inner loop, which would reset parent's settings. 10973 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10974 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10975 auto I = Exit->getFirstNonDebugInstr(); 10976 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10977 return CacheLineAlign; 10978 } 10979 } 10980 10981 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10982 MachineBasicBlock *Exit = ML->getExitBlock(); 10983 10984 if (Pre && Exit) { 10985 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10986 TII->get(AMDGPU::S_INST_PREFETCH)) 10987 .addImm(1); // prefetch 2 lines behind PC 10988 10989 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10990 TII->get(AMDGPU::S_INST_PREFETCH)) 10991 .addImm(2); // prefetch 1 line behind PC 10992 } 10993 10994 return CacheLineAlign; 10995 } 10996 10997 LLVM_ATTRIBUTE_UNUSED 10998 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10999 assert(N->getOpcode() == ISD::CopyFromReg); 11000 do { 11001 // Follow the chain until we find an INLINEASM node. 11002 N = N->getOperand(0).getNode(); 11003 if (N->getOpcode() == ISD::INLINEASM || 11004 N->getOpcode() == ISD::INLINEASM_BR) 11005 return true; 11006 } while (N->getOpcode() == ISD::CopyFromReg); 11007 return false; 11008 } 11009 11010 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 11011 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 11012 { 11013 switch (N->getOpcode()) { 11014 case ISD::CopyFromReg: 11015 { 11016 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11017 const MachineFunction * MF = FLI->MF; 11018 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 11019 const MachineRegisterInfo &MRI = MF->getRegInfo(); 11020 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 11021 Register Reg = R->getReg(); 11022 if (Reg.isPhysical()) 11023 return !TRI.isSGPRReg(MRI, Reg); 11024 11025 if (MRI.isLiveIn(Reg)) { 11026 // workitem.id.x workitem.id.y workitem.id.z 11027 // Any VGPR formal argument is also considered divergent 11028 if (!TRI.isSGPRReg(MRI, Reg)) 11029 return true; 11030 // Formal arguments of non-entry functions 11031 // are conservatively considered divergent 11032 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 11033 return true; 11034 return false; 11035 } 11036 const Value *V = FLI->getValueFromVirtualReg(Reg); 11037 if (V) 11038 return KDA->isDivergent(V); 11039 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11040 return !TRI.isSGPRReg(MRI, Reg); 11041 } 11042 break; 11043 case ISD::LOAD: { 11044 const LoadSDNode *L = cast<LoadSDNode>(N); 11045 unsigned AS = L->getAddressSpace(); 11046 // A flat load may access private memory. 11047 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11048 } break; 11049 case ISD::CALLSEQ_END: 11050 return true; 11051 break; 11052 case ISD::INTRINSIC_WO_CHAIN: 11053 { 11054 11055 } 11056 return AMDGPU::isIntrinsicSourceOfDivergence( 11057 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11058 case ISD::INTRINSIC_W_CHAIN: 11059 return AMDGPU::isIntrinsicSourceOfDivergence( 11060 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11061 } 11062 return false; 11063 } 11064 11065 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11066 EVT VT) const { 11067 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11068 case MVT::f32: 11069 return hasFP32Denormals(DAG.getMachineFunction()); 11070 case MVT::f64: 11071 case MVT::f16: 11072 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11073 default: 11074 return false; 11075 } 11076 } 11077 11078 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11079 const SelectionDAG &DAG, 11080 bool SNaN, 11081 unsigned Depth) const { 11082 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11083 const MachineFunction &MF = DAG.getMachineFunction(); 11084 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11085 11086 if (Info->getMode().DX10Clamp) 11087 return true; // Clamped to 0. 11088 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11089 } 11090 11091 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11092 SNaN, Depth); 11093 } 11094 11095 TargetLowering::AtomicExpansionKind 11096 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11097 switch (RMW->getOperation()) { 11098 case AtomicRMWInst::FAdd: { 11099 Type *Ty = RMW->getType(); 11100 11101 // We don't have a way to support 16-bit atomics now, so just leave them 11102 // as-is. 11103 if (Ty->isHalfTy()) 11104 return AtomicExpansionKind::None; 11105 11106 if (!Ty->isFloatTy()) 11107 return AtomicExpansionKind::CmpXChg; 11108 11109 // TODO: Do have these for flat. Older targets also had them for buffers. 11110 unsigned AS = RMW->getPointerAddressSpace(); 11111 11112 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11113 return RMW->use_empty() ? AtomicExpansionKind::None : 11114 AtomicExpansionKind::CmpXChg; 11115 } 11116 11117 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11118 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11119 } 11120 default: 11121 break; 11122 } 11123 11124 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11125 } 11126 11127 const TargetRegisterClass * 11128 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11129 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11130 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11131 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11132 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11133 : &AMDGPU::SReg_32RegClass; 11134 if (!TRI->isSGPRClass(RC) && !isDivergent) 11135 return TRI->getEquivalentSGPRClass(RC); 11136 else if (TRI->isSGPRClass(RC) && isDivergent) 11137 return TRI->getEquivalentVGPRClass(RC); 11138 11139 return RC; 11140 } 11141 11142 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11143 // uniform values (as produced by the mask results of control flow intrinsics) 11144 // used outside of divergent blocks. The phi users need to also be treated as 11145 // always uniform. 11146 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11147 unsigned WaveSize) { 11148 // FIXME: We asssume we never cast the mask results of a control flow 11149 // intrinsic. 11150 // Early exit if the type won't be consistent as a compile time hack. 11151 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11152 if (!IT || IT->getBitWidth() != WaveSize) 11153 return false; 11154 11155 if (!isa<Instruction>(V)) 11156 return false; 11157 if (!Visited.insert(V).second) 11158 return false; 11159 bool Result = false; 11160 for (auto U : V->users()) { 11161 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11162 if (V == U->getOperand(1)) { 11163 switch (Intrinsic->getIntrinsicID()) { 11164 default: 11165 Result = false; 11166 break; 11167 case Intrinsic::amdgcn_if_break: 11168 case Intrinsic::amdgcn_if: 11169 case Intrinsic::amdgcn_else: 11170 Result = true; 11171 break; 11172 } 11173 } 11174 if (V == U->getOperand(0)) { 11175 switch (Intrinsic->getIntrinsicID()) { 11176 default: 11177 Result = false; 11178 break; 11179 case Intrinsic::amdgcn_end_cf: 11180 case Intrinsic::amdgcn_loop: 11181 Result = true; 11182 break; 11183 } 11184 } 11185 } else { 11186 Result = hasCFUser(U, Visited, WaveSize); 11187 } 11188 if (Result) 11189 break; 11190 } 11191 return Result; 11192 } 11193 11194 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11195 const Value *V) const { 11196 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11197 if (CI->isInlineAsm()) { 11198 // FIXME: This cannot give a correct answer. This should only trigger in 11199 // the case where inline asm returns mixed SGPR and VGPR results, used 11200 // outside the defining block. We don't have a specific result to 11201 // consider, so this assumes if any value is SGPR, the overall register 11202 // also needs to be SGPR. 11203 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11204 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11205 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 11206 for (auto &TC : TargetConstraints) { 11207 if (TC.Type == InlineAsm::isOutput) { 11208 ComputeConstraintToUse(TC, SDValue()); 11209 unsigned AssignedReg; 11210 const TargetRegisterClass *RC; 11211 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11212 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11213 if (RC) { 11214 MachineRegisterInfo &MRI = MF.getRegInfo(); 11215 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11216 return true; 11217 else if (SIRI->isSGPRClass(RC)) 11218 return true; 11219 } 11220 } 11221 } 11222 } 11223 } 11224 SmallPtrSet<const Value *, 16> Visited; 11225 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 11226 } 11227