1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #if defined(_MSC_VER) || defined(__MINGW32__) 15 // Provide M_PI. 16 #define _USE_MATH_DEFINES 17 #endif 18 19 #include "SIISelLowering.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "SIDefines.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.h" 28 #include "Utils/AMDGPUBaseInfo.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/BitVector.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> DisableLoopAlignment( 94 "amdgpu-disable-loop-alignment", 95 cl::desc("Do not align and prefetch loops"), 96 cl::init(false)); 97 98 static bool hasFP32Denormals(const MachineFunction &MF) { 99 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 100 return Info->getMode().FP32Denormals; 101 } 102 103 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().FP64FP16Denormals; 106 } 107 108 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 109 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 110 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 111 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 112 return AMDGPU::SGPR0 + Reg; 113 } 114 } 115 llvm_unreachable("Cannot allocate sgpr"); 116 } 117 118 SITargetLowering::SITargetLowering(const TargetMachine &TM, 119 const GCNSubtarget &STI) 120 : AMDGPUTargetLowering(TM, STI), 121 Subtarget(&STI) { 122 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 123 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 124 125 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 126 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 127 128 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 129 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 130 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 131 132 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 133 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 134 135 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 136 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 137 138 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 139 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 140 141 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 142 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 143 144 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 145 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 146 147 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 148 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 149 150 if (Subtarget->has16BitInsts()) { 151 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 152 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 153 154 // Unless there are also VOP3P operations, not operations are really legal. 155 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 156 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 157 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 158 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 159 } 160 161 if (Subtarget->hasMAIInsts()) { 162 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 163 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 164 } 165 166 computeRegisterProperties(Subtarget->getRegisterInfo()); 167 168 // The boolean content concept here is too inflexible. Compares only ever 169 // really produce a 1-bit result. Any copy/extend from these will turn into a 170 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 171 // it's what most targets use. 172 setBooleanContents(ZeroOrOneBooleanContent); 173 setBooleanVectorContents(ZeroOrOneBooleanContent); 174 175 // We need to custom lower vector stores from local memory 176 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 177 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 178 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 179 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 180 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 181 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 182 setOperationAction(ISD::LOAD, MVT::i1, Custom); 183 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 184 185 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 186 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 187 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 188 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 189 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 190 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 191 setOperationAction(ISD::STORE, MVT::i1, Custom); 192 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 193 194 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 195 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 197 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 198 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 199 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 200 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 201 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 202 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 203 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 204 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 205 206 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 208 209 setOperationAction(ISD::SELECT, MVT::i1, Promote); 210 setOperationAction(ISD::SELECT, MVT::i64, Custom); 211 setOperationAction(ISD::SELECT, MVT::f64, Promote); 212 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 213 214 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 216 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 217 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 218 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 219 220 setOperationAction(ISD::SETCC, MVT::i1, Promote); 221 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 222 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 224 225 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 227 228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 236 237 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 238 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 239 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 240 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 241 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 242 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 243 244 setOperationAction(ISD::UADDO, MVT::i32, Legal); 245 setOperationAction(ISD::USUBO, MVT::i32, Legal); 246 247 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 248 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 249 250 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 251 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 252 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 253 254 #if 0 255 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 256 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 257 #endif 258 259 // We only support LOAD/STORE and vector manipulation ops for vectors 260 // with > 4 elements. 261 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 262 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 263 MVT::v32i32, MVT::v32f32 }) { 264 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 265 switch (Op) { 266 case ISD::LOAD: 267 case ISD::STORE: 268 case ISD::BUILD_VECTOR: 269 case ISD::BITCAST: 270 case ISD::EXTRACT_VECTOR_ELT: 271 case ISD::INSERT_VECTOR_ELT: 272 case ISD::INSERT_SUBVECTOR: 273 case ISD::EXTRACT_SUBVECTOR: 274 case ISD::SCALAR_TO_VECTOR: 275 break; 276 case ISD::CONCAT_VECTORS: 277 setOperationAction(Op, VT, Custom); 278 break; 279 default: 280 setOperationAction(Op, VT, Expand); 281 break; 282 } 283 } 284 } 285 286 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 287 288 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 289 // is expanded to avoid having two separate loops in case the index is a VGPR. 290 291 // Most operations are naturally 32-bit vector operations. We only support 292 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 293 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 294 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 295 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 296 297 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 298 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 299 300 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 301 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 302 303 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 305 } 306 307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 311 312 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 314 315 // Avoid stack access for these. 316 // TODO: Generalize to more vector types. 317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 321 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 331 332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 336 337 // Deal with vec3 vector operations when widened to vec4. 338 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 342 343 // Deal with vec5 vector operations when widened to vec8. 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 348 349 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 350 // and output demarshalling 351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 353 354 // We can't return success/failure, only the old value, 355 // let LLVM add the comparison 356 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 358 359 if (Subtarget->hasFlatAddressSpace()) { 360 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 361 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 362 } 363 364 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 365 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 366 367 // On SI this is s_memtime and s_memrealtime on VI. 368 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 369 setOperationAction(ISD::TRAP, MVT::Other, Custom); 370 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 371 372 if (Subtarget->has16BitInsts()) { 373 setOperationAction(ISD::FPOW, MVT::f16, Promote); 374 setOperationAction(ISD::FLOG, MVT::f16, Custom); 375 setOperationAction(ISD::FEXP, MVT::f16, Custom); 376 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 377 } 378 379 // v_mad_f32 does not support denormals. We report it as unconditionally 380 // legal, and the context where it is formed will disallow it when fp32 381 // denormals are enabled. 382 setOperationAction(ISD::FMAD, MVT::f32, Legal); 383 384 if (!Subtarget->hasBFI()) { 385 // fcopysign can be done in a single instruction with BFI. 386 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 387 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 388 } 389 390 if (!Subtarget->hasBCNT(32)) 391 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 392 393 if (!Subtarget->hasBCNT(64)) 394 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 395 396 if (Subtarget->hasFFBH()) 397 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 398 399 if (Subtarget->hasFFBL()) 400 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 401 402 // We only really have 32-bit BFE instructions (and 16-bit on VI). 403 // 404 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 405 // effort to match them now. We want this to be false for i64 cases when the 406 // extraction isn't restricted to the upper or lower half. Ideally we would 407 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 408 // span the midpoint are probably relatively rare, so don't worry about them 409 // for now. 410 if (Subtarget->hasBFE()) 411 setHasExtractBitsInsn(true); 412 413 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 414 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 415 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 416 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 417 418 419 // These are really only legal for ieee_mode functions. We should be avoiding 420 // them for functions that don't have ieee_mode enabled, so just say they are 421 // legal. 422 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 423 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 424 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 425 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 426 427 428 if (Subtarget->haveRoundOpsF64()) { 429 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 430 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 431 setOperationAction(ISD::FRINT, MVT::f64, Legal); 432 } else { 433 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 434 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 435 setOperationAction(ISD::FRINT, MVT::f64, Custom); 436 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 437 } 438 439 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 440 441 setOperationAction(ISD::FSIN, MVT::f32, Custom); 442 setOperationAction(ISD::FCOS, MVT::f32, Custom); 443 setOperationAction(ISD::FDIV, MVT::f32, Custom); 444 setOperationAction(ISD::FDIV, MVT::f64, Custom); 445 446 if (Subtarget->has16BitInsts()) { 447 setOperationAction(ISD::Constant, MVT::i16, Legal); 448 449 setOperationAction(ISD::SMIN, MVT::i16, Legal); 450 setOperationAction(ISD::SMAX, MVT::i16, Legal); 451 452 setOperationAction(ISD::UMIN, MVT::i16, Legal); 453 setOperationAction(ISD::UMAX, MVT::i16, Legal); 454 455 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 456 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 457 458 setOperationAction(ISD::ROTR, MVT::i16, Promote); 459 setOperationAction(ISD::ROTL, MVT::i16, Promote); 460 461 setOperationAction(ISD::SDIV, MVT::i16, Promote); 462 setOperationAction(ISD::UDIV, MVT::i16, Promote); 463 setOperationAction(ISD::SREM, MVT::i16, Promote); 464 setOperationAction(ISD::UREM, MVT::i16, Promote); 465 466 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 467 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 468 469 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 470 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 471 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 473 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 474 475 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 476 477 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 478 479 setOperationAction(ISD::LOAD, MVT::i16, Custom); 480 481 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 482 483 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 484 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 485 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 486 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 487 488 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 489 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 490 491 // F16 - Constant Actions. 492 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 493 494 // F16 - Load/Store Actions. 495 setOperationAction(ISD::LOAD, MVT::f16, Promote); 496 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 497 setOperationAction(ISD::STORE, MVT::f16, Promote); 498 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 499 500 // F16 - VOP1 Actions. 501 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 502 setOperationAction(ISD::FCOS, MVT::f16, Promote); 503 setOperationAction(ISD::FSIN, MVT::f16, Promote); 504 505 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 506 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 507 508 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 509 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 510 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 511 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 512 setOperationAction(ISD::FROUND, MVT::f16, Custom); 513 514 // F16 - VOP2 Actions. 515 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 516 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 517 518 setOperationAction(ISD::FDIV, MVT::f16, Custom); 519 520 // F16 - VOP3 Actions. 521 setOperationAction(ISD::FMA, MVT::f16, Legal); 522 if (STI.hasMadF16()) 523 setOperationAction(ISD::FMAD, MVT::f16, Legal); 524 525 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 526 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 527 switch (Op) { 528 case ISD::LOAD: 529 case ISD::STORE: 530 case ISD::BUILD_VECTOR: 531 case ISD::BITCAST: 532 case ISD::EXTRACT_VECTOR_ELT: 533 case ISD::INSERT_VECTOR_ELT: 534 case ISD::INSERT_SUBVECTOR: 535 case ISD::EXTRACT_SUBVECTOR: 536 case ISD::SCALAR_TO_VECTOR: 537 break; 538 case ISD::CONCAT_VECTORS: 539 setOperationAction(Op, VT, Custom); 540 break; 541 default: 542 setOperationAction(Op, VT, Expand); 543 break; 544 } 545 } 546 } 547 548 // XXX - Do these do anything? Vector constants turn into build_vector. 549 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 550 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 551 552 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 553 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 554 555 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 556 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 557 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 558 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 559 560 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 561 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 562 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 563 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 564 565 setOperationAction(ISD::AND, MVT::v2i16, Promote); 566 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 567 setOperationAction(ISD::OR, MVT::v2i16, Promote); 568 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 569 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 571 572 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 573 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 574 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 575 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 576 577 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 578 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 579 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 580 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 581 582 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 583 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 584 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 585 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 586 587 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 588 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 589 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 590 591 if (!Subtarget->hasVOP3PInsts()) { 592 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 593 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 594 } 595 596 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 597 // This isn't really legal, but this avoids the legalizer unrolling it (and 598 // allows matching fneg (fabs x) patterns) 599 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 600 601 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 602 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 603 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 604 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 605 606 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 607 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 608 609 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 610 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 611 } 612 613 if (Subtarget->hasVOP3PInsts()) { 614 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 615 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 616 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 617 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 618 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 619 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 620 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 621 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 622 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 623 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 624 625 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 626 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 627 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 628 629 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 630 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 631 632 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 633 634 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 635 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 636 637 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 638 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 639 640 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 641 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 642 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 643 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 644 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 645 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 646 647 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 648 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 649 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 650 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 651 652 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 653 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 654 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 655 656 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 657 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 658 659 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 660 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 661 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 662 663 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 664 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 665 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 666 } 667 668 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 669 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 670 671 if (Subtarget->has16BitInsts()) { 672 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 673 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 674 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 675 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 676 } else { 677 // Legalization hack. 678 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 679 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 680 681 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 682 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 683 } 684 685 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 686 setOperationAction(ISD::SELECT, VT, Custom); 687 } 688 689 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 690 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 691 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 692 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 693 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 694 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 695 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 696 697 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 698 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 699 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 700 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 701 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 702 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 703 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 704 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 705 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 706 707 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 708 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 709 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 710 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 711 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 712 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 713 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 714 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 715 716 setTargetDAGCombine(ISD::ADD); 717 setTargetDAGCombine(ISD::ADDCARRY); 718 setTargetDAGCombine(ISD::SUB); 719 setTargetDAGCombine(ISD::SUBCARRY); 720 setTargetDAGCombine(ISD::FADD); 721 setTargetDAGCombine(ISD::FSUB); 722 setTargetDAGCombine(ISD::FMINNUM); 723 setTargetDAGCombine(ISD::FMAXNUM); 724 setTargetDAGCombine(ISD::FMINNUM_IEEE); 725 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 726 setTargetDAGCombine(ISD::FMA); 727 setTargetDAGCombine(ISD::SMIN); 728 setTargetDAGCombine(ISD::SMAX); 729 setTargetDAGCombine(ISD::UMIN); 730 setTargetDAGCombine(ISD::UMAX); 731 setTargetDAGCombine(ISD::SETCC); 732 setTargetDAGCombine(ISD::AND); 733 setTargetDAGCombine(ISD::OR); 734 setTargetDAGCombine(ISD::XOR); 735 setTargetDAGCombine(ISD::SINT_TO_FP); 736 setTargetDAGCombine(ISD::UINT_TO_FP); 737 setTargetDAGCombine(ISD::FCANONICALIZE); 738 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 739 setTargetDAGCombine(ISD::ZERO_EXTEND); 740 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 741 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 742 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 743 744 // All memory operations. Some folding on the pointer operand is done to help 745 // matching the constant offsets in the addressing modes. 746 setTargetDAGCombine(ISD::LOAD); 747 setTargetDAGCombine(ISD::STORE); 748 setTargetDAGCombine(ISD::ATOMIC_LOAD); 749 setTargetDAGCombine(ISD::ATOMIC_STORE); 750 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 751 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 752 setTargetDAGCombine(ISD::ATOMIC_SWAP); 753 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 754 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 755 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 756 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 757 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 758 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 759 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 760 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 761 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 762 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 763 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 764 765 setSchedulingPreference(Sched::RegPressure); 766 } 767 768 const GCNSubtarget *SITargetLowering::getSubtarget() const { 769 return Subtarget; 770 } 771 772 //===----------------------------------------------------------------------===// 773 // TargetLowering queries 774 //===----------------------------------------------------------------------===// 775 776 // v_mad_mix* support a conversion from f16 to f32. 777 // 778 // There is only one special case when denormals are enabled we don't currently, 779 // where this is OK to use. 780 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 781 EVT DestVT, EVT SrcVT) const { 782 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 783 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 784 DestVT.getScalarType() == MVT::f32 && 785 SrcVT.getScalarType() == MVT::f16 && 786 !hasFP32Denormals(DAG.getMachineFunction()); 787 } 788 789 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 790 // SI has some legal vector types, but no legal vector operations. Say no 791 // shuffles are legal in order to prefer scalarizing some vector operations. 792 return false; 793 } 794 795 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 796 CallingConv::ID CC, 797 EVT VT) const { 798 if (CC == CallingConv::AMDGPU_KERNEL) 799 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 800 801 if (VT.isVector()) { 802 EVT ScalarVT = VT.getScalarType(); 803 unsigned Size = ScalarVT.getSizeInBits(); 804 if (Size == 32) 805 return ScalarVT.getSimpleVT(); 806 807 if (Size > 32) 808 return MVT::i32; 809 810 if (Size == 16 && Subtarget->has16BitInsts()) 811 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 812 } else if (VT.getSizeInBits() > 32) 813 return MVT::i32; 814 815 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 816 } 817 818 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 819 CallingConv::ID CC, 820 EVT VT) const { 821 if (CC == CallingConv::AMDGPU_KERNEL) 822 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 823 824 if (VT.isVector()) { 825 unsigned NumElts = VT.getVectorNumElements(); 826 EVT ScalarVT = VT.getScalarType(); 827 unsigned Size = ScalarVT.getSizeInBits(); 828 829 if (Size == 32) 830 return NumElts; 831 832 if (Size > 32) 833 return NumElts * ((Size + 31) / 32); 834 835 if (Size == 16 && Subtarget->has16BitInsts()) 836 return (NumElts + 1) / 2; 837 } else if (VT.getSizeInBits() > 32) 838 return (VT.getSizeInBits() + 31) / 32; 839 840 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 841 } 842 843 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 844 LLVMContext &Context, CallingConv::ID CC, 845 EVT VT, EVT &IntermediateVT, 846 unsigned &NumIntermediates, MVT &RegisterVT) const { 847 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 848 unsigned NumElts = VT.getVectorNumElements(); 849 EVT ScalarVT = VT.getScalarType(); 850 unsigned Size = ScalarVT.getSizeInBits(); 851 if (Size == 32) { 852 RegisterVT = ScalarVT.getSimpleVT(); 853 IntermediateVT = RegisterVT; 854 NumIntermediates = NumElts; 855 return NumIntermediates; 856 } 857 858 if (Size > 32) { 859 RegisterVT = MVT::i32; 860 IntermediateVT = RegisterVT; 861 NumIntermediates = NumElts * ((Size + 31) / 32); 862 return NumIntermediates; 863 } 864 865 // FIXME: We should fix the ABI to be the same on targets without 16-bit 866 // support, but unless we can properly handle 3-vectors, it will be still be 867 // inconsistent. 868 if (Size == 16 && Subtarget->has16BitInsts()) { 869 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 870 IntermediateVT = RegisterVT; 871 NumIntermediates = (NumElts + 1) / 2; 872 return NumIntermediates; 873 } 874 } 875 876 return TargetLowering::getVectorTypeBreakdownForCallingConv( 877 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 878 } 879 880 static MVT memVTFromAggregate(Type *Ty) { 881 // Only limited forms of aggregate type currently expected. 882 assert(Ty->isStructTy() && "Expected struct type"); 883 884 885 Type *ElementType = nullptr; 886 unsigned NumElts; 887 if (Ty->getContainedType(0)->isVectorTy()) { 888 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 889 ElementType = VecComponent->getElementType(); 890 NumElts = VecComponent->getNumElements(); 891 } else { 892 ElementType = Ty->getContainedType(0); 893 NumElts = 1; 894 } 895 896 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 897 898 // Calculate the size of the memVT type from the aggregate 899 unsigned Pow2Elts = 0; 900 unsigned ElementSize; 901 switch (ElementType->getTypeID()) { 902 default: 903 llvm_unreachable("Unknown type!"); 904 case Type::IntegerTyID: 905 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 906 break; 907 case Type::HalfTyID: 908 ElementSize = 16; 909 break; 910 case Type::FloatTyID: 911 ElementSize = 32; 912 break; 913 } 914 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 915 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 916 917 return MVT::getVectorVT(MVT::getVT(ElementType, false), 918 Pow2Elts); 919 } 920 921 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 922 const CallInst &CI, 923 MachineFunction &MF, 924 unsigned IntrID) const { 925 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 926 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 927 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 928 (Intrinsic::ID)IntrID); 929 if (Attr.hasFnAttribute(Attribute::ReadNone)) 930 return false; 931 932 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 933 934 if (RsrcIntr->IsImage) { 935 Info.ptrVal = MFI->getImagePSV( 936 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 937 CI.getArgOperand(RsrcIntr->RsrcArg)); 938 Info.align.reset(); 939 } else { 940 Info.ptrVal = MFI->getBufferPSV( 941 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 942 CI.getArgOperand(RsrcIntr->RsrcArg)); 943 } 944 945 Info.flags = MachineMemOperand::MODereferenceable; 946 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 947 Info.opc = ISD::INTRINSIC_W_CHAIN; 948 Info.memVT = MVT::getVT(CI.getType(), true); 949 if (Info.memVT == MVT::Other) { 950 // Some intrinsics return an aggregate type - special case to work out 951 // the correct memVT 952 Info.memVT = memVTFromAggregate(CI.getType()); 953 } 954 Info.flags |= MachineMemOperand::MOLoad; 955 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 956 Info.opc = ISD::INTRINSIC_VOID; 957 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 958 Info.flags |= MachineMemOperand::MOStore; 959 } else { 960 // Atomic 961 Info.opc = ISD::INTRINSIC_W_CHAIN; 962 Info.memVT = MVT::getVT(CI.getType()); 963 Info.flags = MachineMemOperand::MOLoad | 964 MachineMemOperand::MOStore | 965 MachineMemOperand::MODereferenceable; 966 967 // XXX - Should this be volatile without known ordering? 968 Info.flags |= MachineMemOperand::MOVolatile; 969 } 970 return true; 971 } 972 973 switch (IntrID) { 974 case Intrinsic::amdgcn_atomic_inc: 975 case Intrinsic::amdgcn_atomic_dec: 976 case Intrinsic::amdgcn_ds_ordered_add: 977 case Intrinsic::amdgcn_ds_ordered_swap: 978 case Intrinsic::amdgcn_ds_fadd: 979 case Intrinsic::amdgcn_ds_fmin: 980 case Intrinsic::amdgcn_ds_fmax: { 981 Info.opc = ISD::INTRINSIC_W_CHAIN; 982 Info.memVT = MVT::getVT(CI.getType()); 983 Info.ptrVal = CI.getOperand(0); 984 Info.align.reset(); 985 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 986 987 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 988 if (!Vol->isZero()) 989 Info.flags |= MachineMemOperand::MOVolatile; 990 991 return true; 992 } 993 case Intrinsic::amdgcn_buffer_atomic_fadd: { 994 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 995 996 Info.opc = ISD::INTRINSIC_VOID; 997 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 998 Info.ptrVal = MFI->getBufferPSV( 999 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1000 CI.getArgOperand(1)); 1001 Info.align.reset(); 1002 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1003 1004 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1005 if (!Vol || !Vol->isZero()) 1006 Info.flags |= MachineMemOperand::MOVolatile; 1007 1008 return true; 1009 } 1010 case Intrinsic::amdgcn_global_atomic_fadd: { 1011 Info.opc = ISD::INTRINSIC_VOID; 1012 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1013 ->getPointerElementType()); 1014 Info.ptrVal = CI.getOperand(0); 1015 Info.align.reset(); 1016 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1017 1018 return true; 1019 } 1020 case Intrinsic::amdgcn_ds_append: 1021 case Intrinsic::amdgcn_ds_consume: { 1022 Info.opc = ISD::INTRINSIC_W_CHAIN; 1023 Info.memVT = MVT::getVT(CI.getType()); 1024 Info.ptrVal = CI.getOperand(0); 1025 Info.align.reset(); 1026 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1027 1028 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1029 if (!Vol->isZero()) 1030 Info.flags |= MachineMemOperand::MOVolatile; 1031 1032 return true; 1033 } 1034 case Intrinsic::amdgcn_ds_gws_init: 1035 case Intrinsic::amdgcn_ds_gws_barrier: 1036 case Intrinsic::amdgcn_ds_gws_sema_v: 1037 case Intrinsic::amdgcn_ds_gws_sema_br: 1038 case Intrinsic::amdgcn_ds_gws_sema_p: 1039 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1040 Info.opc = ISD::INTRINSIC_VOID; 1041 1042 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1043 Info.ptrVal = 1044 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1045 1046 // This is an abstract access, but we need to specify a type and size. 1047 Info.memVT = MVT::i32; 1048 Info.size = 4; 1049 Info.align = Align(4); 1050 1051 Info.flags = MachineMemOperand::MOStore; 1052 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1053 Info.flags = MachineMemOperand::MOLoad; 1054 return true; 1055 } 1056 default: 1057 return false; 1058 } 1059 } 1060 1061 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1062 SmallVectorImpl<Value*> &Ops, 1063 Type *&AccessTy) const { 1064 switch (II->getIntrinsicID()) { 1065 case Intrinsic::amdgcn_atomic_inc: 1066 case Intrinsic::amdgcn_atomic_dec: 1067 case Intrinsic::amdgcn_ds_ordered_add: 1068 case Intrinsic::amdgcn_ds_ordered_swap: 1069 case Intrinsic::amdgcn_ds_fadd: 1070 case Intrinsic::amdgcn_ds_fmin: 1071 case Intrinsic::amdgcn_ds_fmax: { 1072 Value *Ptr = II->getArgOperand(0); 1073 AccessTy = II->getType(); 1074 Ops.push_back(Ptr); 1075 return true; 1076 } 1077 default: 1078 return false; 1079 } 1080 } 1081 1082 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1083 if (!Subtarget->hasFlatInstOffsets()) { 1084 // Flat instructions do not have offsets, and only have the register 1085 // address. 1086 return AM.BaseOffs == 0 && AM.Scale == 0; 1087 } 1088 1089 return AM.Scale == 0 && 1090 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1091 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1092 /*Signed=*/false)); 1093 } 1094 1095 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1096 if (Subtarget->hasFlatGlobalInsts()) 1097 return AM.Scale == 0 && 1098 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1099 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1100 /*Signed=*/true)); 1101 1102 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1103 // Assume the we will use FLAT for all global memory accesses 1104 // on VI. 1105 // FIXME: This assumption is currently wrong. On VI we still use 1106 // MUBUF instructions for the r + i addressing mode. As currently 1107 // implemented, the MUBUF instructions only work on buffer < 4GB. 1108 // It may be possible to support > 4GB buffers with MUBUF instructions, 1109 // by setting the stride value in the resource descriptor which would 1110 // increase the size limit to (stride * 4GB). However, this is risky, 1111 // because it has never been validated. 1112 return isLegalFlatAddressingMode(AM); 1113 } 1114 1115 return isLegalMUBUFAddressingMode(AM); 1116 } 1117 1118 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1119 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1120 // additionally can do r + r + i with addr64. 32-bit has more addressing 1121 // mode options. Depending on the resource constant, it can also do 1122 // (i64 r0) + (i32 r1) * (i14 i). 1123 // 1124 // Private arrays end up using a scratch buffer most of the time, so also 1125 // assume those use MUBUF instructions. Scratch loads / stores are currently 1126 // implemented as mubuf instructions with offen bit set, so slightly 1127 // different than the normal addr64. 1128 if (!isUInt<12>(AM.BaseOffs)) 1129 return false; 1130 1131 // FIXME: Since we can split immediate into soffset and immediate offset, 1132 // would it make sense to allow any immediate? 1133 1134 switch (AM.Scale) { 1135 case 0: // r + i or just i, depending on HasBaseReg. 1136 return true; 1137 case 1: 1138 return true; // We have r + r or r + i. 1139 case 2: 1140 if (AM.HasBaseReg) { 1141 // Reject 2 * r + r. 1142 return false; 1143 } 1144 1145 // Allow 2 * r as r + r 1146 // Or 2 * r + i is allowed as r + r + i. 1147 return true; 1148 default: // Don't allow n * r 1149 return false; 1150 } 1151 } 1152 1153 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1154 const AddrMode &AM, Type *Ty, 1155 unsigned AS, Instruction *I) const { 1156 // No global is ever allowed as a base. 1157 if (AM.BaseGV) 1158 return false; 1159 1160 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1161 return isLegalGlobalAddressingMode(AM); 1162 1163 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1164 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1165 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1166 // If the offset isn't a multiple of 4, it probably isn't going to be 1167 // correctly aligned. 1168 // FIXME: Can we get the real alignment here? 1169 if (AM.BaseOffs % 4 != 0) 1170 return isLegalMUBUFAddressingMode(AM); 1171 1172 // There are no SMRD extloads, so if we have to do a small type access we 1173 // will use a MUBUF load. 1174 // FIXME?: We also need to do this if unaligned, but we don't know the 1175 // alignment here. 1176 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1177 return isLegalGlobalAddressingMode(AM); 1178 1179 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1180 // SMRD instructions have an 8-bit, dword offset on SI. 1181 if (!isUInt<8>(AM.BaseOffs / 4)) 1182 return false; 1183 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1184 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1185 // in 8-bits, it can use a smaller encoding. 1186 if (!isUInt<32>(AM.BaseOffs / 4)) 1187 return false; 1188 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1189 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1190 if (!isUInt<20>(AM.BaseOffs)) 1191 return false; 1192 } else 1193 llvm_unreachable("unhandled generation"); 1194 1195 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1196 return true; 1197 1198 if (AM.Scale == 1 && AM.HasBaseReg) 1199 return true; 1200 1201 return false; 1202 1203 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1204 return isLegalMUBUFAddressingMode(AM); 1205 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1206 AS == AMDGPUAS::REGION_ADDRESS) { 1207 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1208 // field. 1209 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1210 // an 8-bit dword offset but we don't know the alignment here. 1211 if (!isUInt<16>(AM.BaseOffs)) 1212 return false; 1213 1214 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1215 return true; 1216 1217 if (AM.Scale == 1 && AM.HasBaseReg) 1218 return true; 1219 1220 return false; 1221 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1222 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1223 // For an unknown address space, this usually means that this is for some 1224 // reason being used for pure arithmetic, and not based on some addressing 1225 // computation. We don't have instructions that compute pointers with any 1226 // addressing modes, so treat them as having no offset like flat 1227 // instructions. 1228 return isLegalFlatAddressingMode(AM); 1229 } else { 1230 llvm_unreachable("unhandled address space"); 1231 } 1232 } 1233 1234 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1235 const SelectionDAG &DAG) const { 1236 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1237 return (MemVT.getSizeInBits() <= 4 * 32); 1238 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1239 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1240 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1241 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1242 return (MemVT.getSizeInBits() <= 2 * 32); 1243 } 1244 return true; 1245 } 1246 1247 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1248 unsigned Size, unsigned AddrSpace, unsigned Align, 1249 MachineMemOperand::Flags Flags, bool *IsFast) const { 1250 if (IsFast) 1251 *IsFast = false; 1252 1253 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1254 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1255 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1256 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1257 // with adjacent offsets. 1258 bool AlignedBy4 = (Align % 4 == 0); 1259 if (IsFast) 1260 *IsFast = AlignedBy4; 1261 1262 return AlignedBy4; 1263 } 1264 1265 // FIXME: We have to be conservative here and assume that flat operations 1266 // will access scratch. If we had access to the IR function, then we 1267 // could determine if any private memory was used in the function. 1268 if (!Subtarget->hasUnalignedScratchAccess() && 1269 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1270 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1271 bool AlignedBy4 = Align >= 4; 1272 if (IsFast) 1273 *IsFast = AlignedBy4; 1274 1275 return AlignedBy4; 1276 } 1277 1278 if (Subtarget->hasUnalignedBufferAccess()) { 1279 // If we have an uniform constant load, it still requires using a slow 1280 // buffer instruction if unaligned. 1281 if (IsFast) { 1282 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1283 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1284 (Align % 4 == 0) : true; 1285 } 1286 1287 return true; 1288 } 1289 1290 // Smaller than dword value must be aligned. 1291 if (Size < 32) 1292 return false; 1293 1294 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1295 // byte-address are ignored, thus forcing Dword alignment. 1296 // This applies to private, global, and constant memory. 1297 if (IsFast) 1298 *IsFast = true; 1299 1300 return Size >= 32 && Align >= 4; 1301 } 1302 1303 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1304 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1305 bool *IsFast) const { 1306 if (IsFast) 1307 *IsFast = false; 1308 1309 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1310 // which isn't a simple VT. 1311 // Until MVT is extended to handle this, simply check for the size and 1312 // rely on the condition below: allow accesses if the size is a multiple of 4. 1313 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1314 VT.getStoreSize() > 16)) { 1315 return false; 1316 } 1317 1318 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1319 Align, Flags, IsFast); 1320 } 1321 1322 EVT SITargetLowering::getOptimalMemOpType( 1323 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1324 bool ZeroMemset, bool MemcpyStrSrc, 1325 const AttributeList &FuncAttributes) const { 1326 // FIXME: Should account for address space here. 1327 1328 // The default fallback uses the private pointer size as a guess for a type to 1329 // use. Make sure we switch these to 64-bit accesses. 1330 1331 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1332 return MVT::v4i32; 1333 1334 if (Size >= 8 && DstAlign >= 4) 1335 return MVT::v2i32; 1336 1337 // Use the default. 1338 return MVT::Other; 1339 } 1340 1341 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1342 unsigned DestAS) const { 1343 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1344 } 1345 1346 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1347 const MemSDNode *MemNode = cast<MemSDNode>(N); 1348 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1349 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1350 return I && I->getMetadata("amdgpu.noclobber"); 1351 } 1352 1353 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1354 unsigned DestAS) const { 1355 // Flat -> private/local is a simple truncate. 1356 // Flat -> global is no-op 1357 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1358 return true; 1359 1360 return isNoopAddrSpaceCast(SrcAS, DestAS); 1361 } 1362 1363 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1364 const MemSDNode *MemNode = cast<MemSDNode>(N); 1365 1366 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1367 } 1368 1369 TargetLoweringBase::LegalizeTypeAction 1370 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1371 int NumElts = VT.getVectorNumElements(); 1372 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1373 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1374 return TargetLoweringBase::getPreferredVectorAction(VT); 1375 } 1376 1377 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1378 Type *Ty) const { 1379 // FIXME: Could be smarter if called for vector constants. 1380 return true; 1381 } 1382 1383 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1384 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1385 switch (Op) { 1386 case ISD::LOAD: 1387 case ISD::STORE: 1388 1389 // These operations are done with 32-bit instructions anyway. 1390 case ISD::AND: 1391 case ISD::OR: 1392 case ISD::XOR: 1393 case ISD::SELECT: 1394 // TODO: Extensions? 1395 return true; 1396 default: 1397 return false; 1398 } 1399 } 1400 1401 // SimplifySetCC uses this function to determine whether or not it should 1402 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1403 if (VT == MVT::i1 && Op == ISD::SETCC) 1404 return false; 1405 1406 return TargetLowering::isTypeDesirableForOp(Op, VT); 1407 } 1408 1409 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1410 const SDLoc &SL, 1411 SDValue Chain, 1412 uint64_t Offset) const { 1413 const DataLayout &DL = DAG.getDataLayout(); 1414 MachineFunction &MF = DAG.getMachineFunction(); 1415 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1416 1417 const ArgDescriptor *InputPtrReg; 1418 const TargetRegisterClass *RC; 1419 1420 std::tie(InputPtrReg, RC) 1421 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1422 1423 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1424 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1425 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1426 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1427 1428 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1429 } 1430 1431 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1432 const SDLoc &SL) const { 1433 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1434 FIRST_IMPLICIT); 1435 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1436 } 1437 1438 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1439 const SDLoc &SL, SDValue Val, 1440 bool Signed, 1441 const ISD::InputArg *Arg) const { 1442 // First, if it is a widened vector, narrow it. 1443 if (VT.isVector() && 1444 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1445 EVT NarrowedVT = 1446 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1447 VT.getVectorNumElements()); 1448 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1449 DAG.getConstant(0, SL, MVT::i32)); 1450 } 1451 1452 // Then convert the vector elements or scalar value. 1453 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1454 VT.bitsLT(MemVT)) { 1455 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1456 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1457 } 1458 1459 if (MemVT.isFloatingPoint()) 1460 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1461 else if (Signed) 1462 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1463 else 1464 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1465 1466 return Val; 1467 } 1468 1469 SDValue SITargetLowering::lowerKernargMemParameter( 1470 SelectionDAG &DAG, EVT VT, EVT MemVT, 1471 const SDLoc &SL, SDValue Chain, 1472 uint64_t Offset, unsigned Align, bool Signed, 1473 const ISD::InputArg *Arg) const { 1474 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1475 1476 // Try to avoid using an extload by loading earlier than the argument address, 1477 // and extracting the relevant bits. The load should hopefully be merged with 1478 // the previous argument. 1479 if (MemVT.getStoreSize() < 4 && Align < 4) { 1480 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1481 int64_t AlignDownOffset = alignDown(Offset, 4); 1482 int64_t OffsetDiff = Offset - AlignDownOffset; 1483 1484 EVT IntVT = MemVT.changeTypeToInteger(); 1485 1486 // TODO: If we passed in the base kernel offset we could have a better 1487 // alignment than 4, but we don't really need it. 1488 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1489 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1490 MachineMemOperand::MODereferenceable | 1491 MachineMemOperand::MOInvariant); 1492 1493 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1494 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1495 1496 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1497 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1498 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1499 1500 1501 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1502 } 1503 1504 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1505 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1506 MachineMemOperand::MODereferenceable | 1507 MachineMemOperand::MOInvariant); 1508 1509 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1510 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1511 } 1512 1513 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1514 const SDLoc &SL, SDValue Chain, 1515 const ISD::InputArg &Arg) const { 1516 MachineFunction &MF = DAG.getMachineFunction(); 1517 MachineFrameInfo &MFI = MF.getFrameInfo(); 1518 1519 if (Arg.Flags.isByVal()) { 1520 unsigned Size = Arg.Flags.getByValSize(); 1521 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1522 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1523 } 1524 1525 unsigned ArgOffset = VA.getLocMemOffset(); 1526 unsigned ArgSize = VA.getValVT().getStoreSize(); 1527 1528 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1529 1530 // Create load nodes to retrieve arguments from the stack. 1531 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1532 SDValue ArgValue; 1533 1534 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1535 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1536 MVT MemVT = VA.getValVT(); 1537 1538 switch (VA.getLocInfo()) { 1539 default: 1540 break; 1541 case CCValAssign::BCvt: 1542 MemVT = VA.getLocVT(); 1543 break; 1544 case CCValAssign::SExt: 1545 ExtType = ISD::SEXTLOAD; 1546 break; 1547 case CCValAssign::ZExt: 1548 ExtType = ISD::ZEXTLOAD; 1549 break; 1550 case CCValAssign::AExt: 1551 ExtType = ISD::EXTLOAD; 1552 break; 1553 } 1554 1555 ArgValue = DAG.getExtLoad( 1556 ExtType, SL, VA.getLocVT(), Chain, FIN, 1557 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1558 MemVT); 1559 return ArgValue; 1560 } 1561 1562 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1563 const SIMachineFunctionInfo &MFI, 1564 EVT VT, 1565 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1566 const ArgDescriptor *Reg; 1567 const TargetRegisterClass *RC; 1568 1569 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1570 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1571 } 1572 1573 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1574 CallingConv::ID CallConv, 1575 ArrayRef<ISD::InputArg> Ins, 1576 BitVector &Skipped, 1577 FunctionType *FType, 1578 SIMachineFunctionInfo *Info) { 1579 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1580 const ISD::InputArg *Arg = &Ins[I]; 1581 1582 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1583 "vector type argument should have been split"); 1584 1585 // First check if it's a PS input addr. 1586 if (CallConv == CallingConv::AMDGPU_PS && 1587 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1588 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1589 1590 // Inconveniently only the first part of the split is marked as isSplit, 1591 // so skip to the end. We only want to increment PSInputNum once for the 1592 // entire split argument. 1593 if (Arg->Flags.isSplit()) { 1594 while (!Arg->Flags.isSplitEnd()) { 1595 assert((!Arg->VT.isVector() || 1596 Arg->VT.getScalarSizeInBits() == 16) && 1597 "unexpected vector split in ps argument type"); 1598 if (!SkipArg) 1599 Splits.push_back(*Arg); 1600 Arg = &Ins[++I]; 1601 } 1602 } 1603 1604 if (SkipArg) { 1605 // We can safely skip PS inputs. 1606 Skipped.set(Arg->getOrigArgIndex()); 1607 ++PSInputNum; 1608 continue; 1609 } 1610 1611 Info->markPSInputAllocated(PSInputNum); 1612 if (Arg->Used) 1613 Info->markPSInputEnabled(PSInputNum); 1614 1615 ++PSInputNum; 1616 } 1617 1618 Splits.push_back(*Arg); 1619 } 1620 } 1621 1622 // Allocate special inputs passed in VGPRs. 1623 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1624 MachineFunction &MF, 1625 const SIRegisterInfo &TRI, 1626 SIMachineFunctionInfo &Info) const { 1627 const LLT S32 = LLT::scalar(32); 1628 MachineRegisterInfo &MRI = MF.getRegInfo(); 1629 1630 if (Info.hasWorkItemIDX()) { 1631 Register Reg = AMDGPU::VGPR0; 1632 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1633 1634 CCInfo.AllocateReg(Reg); 1635 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1636 } 1637 1638 if (Info.hasWorkItemIDY()) { 1639 Register Reg = AMDGPU::VGPR1; 1640 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1641 1642 CCInfo.AllocateReg(Reg); 1643 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1644 } 1645 1646 if (Info.hasWorkItemIDZ()) { 1647 Register Reg = AMDGPU::VGPR2; 1648 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1649 1650 CCInfo.AllocateReg(Reg); 1651 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1652 } 1653 } 1654 1655 // Try to allocate a VGPR at the end of the argument list, or if no argument 1656 // VGPRs are left allocating a stack slot. 1657 // If \p Mask is is given it indicates bitfield position in the register. 1658 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1659 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1660 ArgDescriptor Arg = ArgDescriptor()) { 1661 if (Arg.isSet()) 1662 return ArgDescriptor::createArg(Arg, Mask); 1663 1664 ArrayRef<MCPhysReg> ArgVGPRs 1665 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1666 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1667 if (RegIdx == ArgVGPRs.size()) { 1668 // Spill to stack required. 1669 int64_t Offset = CCInfo.AllocateStack(4, 4); 1670 1671 return ArgDescriptor::createStack(Offset, Mask); 1672 } 1673 1674 unsigned Reg = ArgVGPRs[RegIdx]; 1675 Reg = CCInfo.AllocateReg(Reg); 1676 assert(Reg != AMDGPU::NoRegister); 1677 1678 MachineFunction &MF = CCInfo.getMachineFunction(); 1679 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1680 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1681 return ArgDescriptor::createRegister(Reg, Mask); 1682 } 1683 1684 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1685 const TargetRegisterClass *RC, 1686 unsigned NumArgRegs) { 1687 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1688 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1689 if (RegIdx == ArgSGPRs.size()) 1690 report_fatal_error("ran out of SGPRs for arguments"); 1691 1692 unsigned Reg = ArgSGPRs[RegIdx]; 1693 Reg = CCInfo.AllocateReg(Reg); 1694 assert(Reg != AMDGPU::NoRegister); 1695 1696 MachineFunction &MF = CCInfo.getMachineFunction(); 1697 MF.addLiveIn(Reg, RC); 1698 return ArgDescriptor::createRegister(Reg); 1699 } 1700 1701 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1702 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1703 } 1704 1705 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1706 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1707 } 1708 1709 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo, 1710 MachineFunction &MF, 1711 const SIRegisterInfo &TRI, 1712 SIMachineFunctionInfo &Info) const { 1713 const unsigned Mask = 0x3ff; 1714 ArgDescriptor Arg; 1715 1716 if (Info.hasWorkItemIDX()) { 1717 Arg = allocateVGPR32Input(CCInfo, Mask); 1718 Info.setWorkItemIDX(Arg); 1719 } 1720 1721 if (Info.hasWorkItemIDY()) { 1722 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1723 Info.setWorkItemIDY(Arg); 1724 } 1725 1726 if (Info.hasWorkItemIDZ()) 1727 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1728 } 1729 1730 void SITargetLowering::allocateSpecialInputSGPRs( 1731 CCState &CCInfo, 1732 MachineFunction &MF, 1733 const SIRegisterInfo &TRI, 1734 SIMachineFunctionInfo &Info) const { 1735 auto &ArgInfo = Info.getArgInfo(); 1736 1737 // TODO: Unify handling with private memory pointers. 1738 1739 if (Info.hasDispatchPtr()) 1740 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1741 1742 if (Info.hasQueuePtr()) 1743 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1744 1745 if (Info.hasKernargSegmentPtr()) 1746 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1747 1748 if (Info.hasDispatchID()) 1749 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1750 1751 // flat_scratch_init is not applicable for non-kernel functions. 1752 1753 if (Info.hasWorkGroupIDX()) 1754 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1755 1756 if (Info.hasWorkGroupIDY()) 1757 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1758 1759 if (Info.hasWorkGroupIDZ()) 1760 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1761 1762 if (Info.hasImplicitArgPtr()) 1763 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1764 } 1765 1766 // Allocate special inputs passed in user SGPRs. 1767 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1768 MachineFunction &MF, 1769 const SIRegisterInfo &TRI, 1770 SIMachineFunctionInfo &Info) const { 1771 if (Info.hasImplicitBufferPtr()) { 1772 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1773 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1774 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1775 } 1776 1777 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1778 if (Info.hasPrivateSegmentBuffer()) { 1779 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1780 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1781 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1782 } 1783 1784 if (Info.hasDispatchPtr()) { 1785 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1786 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1787 CCInfo.AllocateReg(DispatchPtrReg); 1788 } 1789 1790 if (Info.hasQueuePtr()) { 1791 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1792 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1793 CCInfo.AllocateReg(QueuePtrReg); 1794 } 1795 1796 if (Info.hasKernargSegmentPtr()) { 1797 MachineRegisterInfo &MRI = MF.getRegInfo(); 1798 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1799 CCInfo.AllocateReg(InputPtrReg); 1800 1801 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1802 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1803 } 1804 1805 if (Info.hasDispatchID()) { 1806 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1807 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1808 CCInfo.AllocateReg(DispatchIDReg); 1809 } 1810 1811 if (Info.hasFlatScratchInit()) { 1812 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1813 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1814 CCInfo.AllocateReg(FlatScratchInitReg); 1815 } 1816 1817 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1818 // these from the dispatch pointer. 1819 } 1820 1821 // Allocate special input registers that are initialized per-wave. 1822 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1823 MachineFunction &MF, 1824 SIMachineFunctionInfo &Info, 1825 CallingConv::ID CallConv, 1826 bool IsShader) const { 1827 if (Info.hasWorkGroupIDX()) { 1828 unsigned Reg = Info.addWorkGroupIDX(); 1829 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1830 CCInfo.AllocateReg(Reg); 1831 } 1832 1833 if (Info.hasWorkGroupIDY()) { 1834 unsigned Reg = Info.addWorkGroupIDY(); 1835 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1836 CCInfo.AllocateReg(Reg); 1837 } 1838 1839 if (Info.hasWorkGroupIDZ()) { 1840 unsigned Reg = Info.addWorkGroupIDZ(); 1841 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1842 CCInfo.AllocateReg(Reg); 1843 } 1844 1845 if (Info.hasWorkGroupInfo()) { 1846 unsigned Reg = Info.addWorkGroupInfo(); 1847 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1848 CCInfo.AllocateReg(Reg); 1849 } 1850 1851 if (Info.hasPrivateSegmentWaveByteOffset()) { 1852 // Scratch wave offset passed in system SGPR. 1853 unsigned PrivateSegmentWaveByteOffsetReg; 1854 1855 if (IsShader) { 1856 PrivateSegmentWaveByteOffsetReg = 1857 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1858 1859 // This is true if the scratch wave byte offset doesn't have a fixed 1860 // location. 1861 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1862 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1863 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1864 } 1865 } else 1866 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1867 1868 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1869 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1870 } 1871 } 1872 1873 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1874 MachineFunction &MF, 1875 const SIRegisterInfo &TRI, 1876 SIMachineFunctionInfo &Info) { 1877 // Now that we've figured out where the scratch register inputs are, see if 1878 // should reserve the arguments and use them directly. 1879 MachineFrameInfo &MFI = MF.getFrameInfo(); 1880 bool HasStackObjects = MFI.hasStackObjects(); 1881 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1882 1883 // Record that we know we have non-spill stack objects so we don't need to 1884 // check all stack objects later. 1885 if (HasStackObjects) 1886 Info.setHasNonSpillStackObjects(true); 1887 1888 // Everything live out of a block is spilled with fast regalloc, so it's 1889 // almost certain that spilling will be required. 1890 if (TM.getOptLevel() == CodeGenOpt::None) 1891 HasStackObjects = true; 1892 1893 // For now assume stack access is needed in any callee functions, so we need 1894 // the scratch registers to pass in. 1895 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1896 1897 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1898 // If we have stack objects, we unquestionably need the private buffer 1899 // resource. For the Code Object V2 ABI, this will be the first 4 user 1900 // SGPR inputs. We can reserve those and use them directly. 1901 1902 Register PrivateSegmentBufferReg = 1903 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1904 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1905 } else { 1906 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1907 // We tentatively reserve the last registers (skipping the last registers 1908 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1909 // we'll replace these with the ones immediately after those which were 1910 // really allocated. In the prologue copies will be inserted from the 1911 // argument to these reserved registers. 1912 1913 // Without HSA, relocations are used for the scratch pointer and the 1914 // buffer resource setup is always inserted in the prologue. Scratch wave 1915 // offset is still in an input SGPR. 1916 Info.setScratchRSrcReg(ReservedBufferReg); 1917 } 1918 1919 // hasFP should be accurate for kernels even before the frame is finalized. 1920 if (ST.getFrameLowering()->hasFP(MF)) { 1921 MachineRegisterInfo &MRI = MF.getRegInfo(); 1922 1923 // Try to use s32 as the SP, but move it if it would interfere with input 1924 // arguments. This won't work with calls though. 1925 // 1926 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1927 // registers. 1928 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1929 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1930 } else { 1931 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1932 1933 if (MFI.hasCalls()) 1934 report_fatal_error("call in graphics shader with too many input SGPRs"); 1935 1936 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1937 if (!MRI.isLiveIn(Reg)) { 1938 Info.setStackPtrOffsetReg(Reg); 1939 break; 1940 } 1941 } 1942 1943 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1944 report_fatal_error("failed to find register for SP"); 1945 } 1946 1947 if (MFI.hasCalls()) { 1948 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1949 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1950 } else { 1951 unsigned ReservedOffsetReg = 1952 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1953 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1954 Info.setFrameOffsetReg(ReservedOffsetReg); 1955 } 1956 } else if (RequiresStackAccess) { 1957 assert(!MFI.hasCalls()); 1958 // We know there are accesses and they will be done relative to SP, so just 1959 // pin it to the input. 1960 // 1961 // FIXME: Should not do this if inline asm is reading/writing these 1962 // registers. 1963 Register PreloadedSP = Info.getPreloadedReg( 1964 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1965 1966 Info.setStackPtrOffsetReg(PreloadedSP); 1967 Info.setScratchWaveOffsetReg(PreloadedSP); 1968 Info.setFrameOffsetReg(PreloadedSP); 1969 } else { 1970 assert(!MFI.hasCalls()); 1971 1972 // There may not be stack access at all. There may still be spills, or 1973 // access of a constant pointer (in which cases an extra copy will be 1974 // emitted in the prolog). 1975 unsigned ReservedOffsetReg 1976 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1977 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1978 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1979 Info.setFrameOffsetReg(ReservedOffsetReg); 1980 } 1981 } 1982 1983 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1984 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1985 return !Info->isEntryFunction(); 1986 } 1987 1988 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1989 1990 } 1991 1992 void SITargetLowering::insertCopiesSplitCSR( 1993 MachineBasicBlock *Entry, 1994 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1995 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1996 1997 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1998 if (!IStart) 1999 return; 2000 2001 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2002 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2003 MachineBasicBlock::iterator MBBI = Entry->begin(); 2004 for (const MCPhysReg *I = IStart; *I; ++I) { 2005 const TargetRegisterClass *RC = nullptr; 2006 if (AMDGPU::SReg_64RegClass.contains(*I)) 2007 RC = &AMDGPU::SGPR_64RegClass; 2008 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2009 RC = &AMDGPU::SGPR_32RegClass; 2010 else 2011 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2012 2013 Register NewVR = MRI->createVirtualRegister(RC); 2014 // Create copy from CSR to a virtual register. 2015 Entry->addLiveIn(*I); 2016 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2017 .addReg(*I); 2018 2019 // Insert the copy-back instructions right before the terminator. 2020 for (auto *Exit : Exits) 2021 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2022 TII->get(TargetOpcode::COPY), *I) 2023 .addReg(NewVR); 2024 } 2025 } 2026 2027 SDValue SITargetLowering::LowerFormalArguments( 2028 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2029 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2030 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2031 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2032 2033 MachineFunction &MF = DAG.getMachineFunction(); 2034 const Function &Fn = MF.getFunction(); 2035 FunctionType *FType = MF.getFunction().getFunctionType(); 2036 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2037 2038 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2039 DiagnosticInfoUnsupported NoGraphicsHSA( 2040 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2041 DAG.getContext()->diagnose(NoGraphicsHSA); 2042 return DAG.getEntryNode(); 2043 } 2044 2045 SmallVector<ISD::InputArg, 16> Splits; 2046 SmallVector<CCValAssign, 16> ArgLocs; 2047 BitVector Skipped(Ins.size()); 2048 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2049 *DAG.getContext()); 2050 2051 bool IsShader = AMDGPU::isShader(CallConv); 2052 bool IsKernel = AMDGPU::isKernel(CallConv); 2053 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2054 2055 if (IsShader) { 2056 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2057 2058 // At least one interpolation mode must be enabled or else the GPU will 2059 // hang. 2060 // 2061 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2062 // set PSInputAddr, the user wants to enable some bits after the compilation 2063 // based on run-time states. Since we can't know what the final PSInputEna 2064 // will look like, so we shouldn't do anything here and the user should take 2065 // responsibility for the correct programming. 2066 // 2067 // Otherwise, the following restrictions apply: 2068 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2069 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2070 // enabled too. 2071 if (CallConv == CallingConv::AMDGPU_PS) { 2072 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2073 ((Info->getPSInputAddr() & 0xF) == 0 && 2074 Info->isPSInputAllocated(11))) { 2075 CCInfo.AllocateReg(AMDGPU::VGPR0); 2076 CCInfo.AllocateReg(AMDGPU::VGPR1); 2077 Info->markPSInputAllocated(0); 2078 Info->markPSInputEnabled(0); 2079 } 2080 if (Subtarget->isAmdPalOS()) { 2081 // For isAmdPalOS, the user does not enable some bits after compilation 2082 // based on run-time states; the register values being generated here are 2083 // the final ones set in hardware. Therefore we need to apply the 2084 // workaround to PSInputAddr and PSInputEnable together. (The case where 2085 // a bit is set in PSInputAddr but not PSInputEnable is where the 2086 // frontend set up an input arg for a particular interpolation mode, but 2087 // nothing uses that input arg. Really we should have an earlier pass 2088 // that removes such an arg.) 2089 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2090 if ((PsInputBits & 0x7F) == 0 || 2091 ((PsInputBits & 0xF) == 0 && 2092 (PsInputBits >> 11 & 1))) 2093 Info->markPSInputEnabled( 2094 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2095 } 2096 } 2097 2098 assert(!Info->hasDispatchPtr() && 2099 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2100 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2101 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2102 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2103 !Info->hasWorkItemIDZ()); 2104 } else if (IsKernel) { 2105 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2106 } else { 2107 Splits.append(Ins.begin(), Ins.end()); 2108 } 2109 2110 if (IsEntryFunc) { 2111 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2112 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2113 } 2114 2115 if (IsKernel) { 2116 analyzeFormalArgumentsCompute(CCInfo, Ins); 2117 } else { 2118 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2119 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2120 } 2121 2122 SmallVector<SDValue, 16> Chains; 2123 2124 // FIXME: This is the minimum kernel argument alignment. We should improve 2125 // this to the maximum alignment of the arguments. 2126 // 2127 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2128 // kern arg offset. 2129 const unsigned KernelArgBaseAlign = 16; 2130 2131 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2132 const ISD::InputArg &Arg = Ins[i]; 2133 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2134 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2135 continue; 2136 } 2137 2138 CCValAssign &VA = ArgLocs[ArgIdx++]; 2139 MVT VT = VA.getLocVT(); 2140 2141 if (IsEntryFunc && VA.isMemLoc()) { 2142 VT = Ins[i].VT; 2143 EVT MemVT = VA.getLocVT(); 2144 2145 const uint64_t Offset = VA.getLocMemOffset(); 2146 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2147 2148 SDValue Arg = lowerKernargMemParameter( 2149 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2150 Chains.push_back(Arg.getValue(1)); 2151 2152 auto *ParamTy = 2153 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2154 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2155 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2156 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2157 // On SI local pointers are just offsets into LDS, so they are always 2158 // less than 16-bits. On CI and newer they could potentially be 2159 // real pointers, so we can't guarantee their size. 2160 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2161 DAG.getValueType(MVT::i16)); 2162 } 2163 2164 InVals.push_back(Arg); 2165 continue; 2166 } else if (!IsEntryFunc && VA.isMemLoc()) { 2167 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2168 InVals.push_back(Val); 2169 if (!Arg.Flags.isByVal()) 2170 Chains.push_back(Val.getValue(1)); 2171 continue; 2172 } 2173 2174 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2175 2176 Register Reg = VA.getLocReg(); 2177 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2178 EVT ValVT = VA.getValVT(); 2179 2180 Reg = MF.addLiveIn(Reg, RC); 2181 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2182 2183 if (Arg.Flags.isSRet()) { 2184 // The return object should be reasonably addressable. 2185 2186 // FIXME: This helps when the return is a real sret. If it is a 2187 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2188 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2189 unsigned NumBits 2190 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2191 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2192 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2193 } 2194 2195 // If this is an 8 or 16-bit value, it is really passed promoted 2196 // to 32 bits. Insert an assert[sz]ext to capture this, then 2197 // truncate to the right size. 2198 switch (VA.getLocInfo()) { 2199 case CCValAssign::Full: 2200 break; 2201 case CCValAssign::BCvt: 2202 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2203 break; 2204 case CCValAssign::SExt: 2205 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2206 DAG.getValueType(ValVT)); 2207 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2208 break; 2209 case CCValAssign::ZExt: 2210 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2211 DAG.getValueType(ValVT)); 2212 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2213 break; 2214 case CCValAssign::AExt: 2215 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2216 break; 2217 default: 2218 llvm_unreachable("Unknown loc info!"); 2219 } 2220 2221 InVals.push_back(Val); 2222 } 2223 2224 if (!IsEntryFunc) { 2225 // Special inputs come after user arguments. 2226 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2227 } 2228 2229 // Start adding system SGPRs. 2230 if (IsEntryFunc) { 2231 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2232 } else { 2233 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2234 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2235 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2236 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2237 } 2238 2239 auto &ArgUsageInfo = 2240 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2241 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2242 2243 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2244 Info->setBytesInStackArgArea(StackArgSize); 2245 2246 return Chains.empty() ? Chain : 2247 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2248 } 2249 2250 // TODO: If return values can't fit in registers, we should return as many as 2251 // possible in registers before passing on stack. 2252 bool SITargetLowering::CanLowerReturn( 2253 CallingConv::ID CallConv, 2254 MachineFunction &MF, bool IsVarArg, 2255 const SmallVectorImpl<ISD::OutputArg> &Outs, 2256 LLVMContext &Context) const { 2257 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2258 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2259 // for shaders. Vector types should be explicitly handled by CC. 2260 if (AMDGPU::isEntryFunctionCC(CallConv)) 2261 return true; 2262 2263 SmallVector<CCValAssign, 16> RVLocs; 2264 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2265 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2266 } 2267 2268 SDValue 2269 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2270 bool isVarArg, 2271 const SmallVectorImpl<ISD::OutputArg> &Outs, 2272 const SmallVectorImpl<SDValue> &OutVals, 2273 const SDLoc &DL, SelectionDAG &DAG) const { 2274 MachineFunction &MF = DAG.getMachineFunction(); 2275 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2276 2277 if (AMDGPU::isKernel(CallConv)) { 2278 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2279 OutVals, DL, DAG); 2280 } 2281 2282 bool IsShader = AMDGPU::isShader(CallConv); 2283 2284 Info->setIfReturnsVoid(Outs.empty()); 2285 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2286 2287 // CCValAssign - represent the assignment of the return value to a location. 2288 SmallVector<CCValAssign, 48> RVLocs; 2289 SmallVector<ISD::OutputArg, 48> Splits; 2290 2291 // CCState - Info about the registers and stack slots. 2292 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2293 *DAG.getContext()); 2294 2295 // Analyze outgoing return values. 2296 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2297 2298 SDValue Flag; 2299 SmallVector<SDValue, 48> RetOps; 2300 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2301 2302 // Add return address for callable functions. 2303 if (!Info->isEntryFunction()) { 2304 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2305 SDValue ReturnAddrReg = CreateLiveInRegister( 2306 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2307 2308 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2309 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2310 MVT::i64); 2311 Chain = 2312 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2313 Flag = Chain.getValue(1); 2314 RetOps.push_back(ReturnAddrVirtualReg); 2315 } 2316 2317 // Copy the result values into the output registers. 2318 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2319 ++I, ++RealRVLocIdx) { 2320 CCValAssign &VA = RVLocs[I]; 2321 assert(VA.isRegLoc() && "Can only return in registers!"); 2322 // TODO: Partially return in registers if return values don't fit. 2323 SDValue Arg = OutVals[RealRVLocIdx]; 2324 2325 // Copied from other backends. 2326 switch (VA.getLocInfo()) { 2327 case CCValAssign::Full: 2328 break; 2329 case CCValAssign::BCvt: 2330 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2331 break; 2332 case CCValAssign::SExt: 2333 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2334 break; 2335 case CCValAssign::ZExt: 2336 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2337 break; 2338 case CCValAssign::AExt: 2339 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2340 break; 2341 default: 2342 llvm_unreachable("Unknown loc info!"); 2343 } 2344 2345 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2346 Flag = Chain.getValue(1); 2347 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2348 } 2349 2350 // FIXME: Does sret work properly? 2351 if (!Info->isEntryFunction()) { 2352 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2353 const MCPhysReg *I = 2354 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2355 if (I) { 2356 for (; *I; ++I) { 2357 if (AMDGPU::SReg_64RegClass.contains(*I)) 2358 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2359 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2360 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2361 else 2362 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2363 } 2364 } 2365 } 2366 2367 // Update chain and glue. 2368 RetOps[0] = Chain; 2369 if (Flag.getNode()) 2370 RetOps.push_back(Flag); 2371 2372 unsigned Opc = AMDGPUISD::ENDPGM; 2373 if (!IsWaveEnd) 2374 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2375 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2376 } 2377 2378 SDValue SITargetLowering::LowerCallResult( 2379 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2380 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2381 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2382 SDValue ThisVal) const { 2383 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2384 2385 // Assign locations to each value returned by this call. 2386 SmallVector<CCValAssign, 16> RVLocs; 2387 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2388 *DAG.getContext()); 2389 CCInfo.AnalyzeCallResult(Ins, RetCC); 2390 2391 // Copy all of the result registers out of their specified physreg. 2392 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2393 CCValAssign VA = RVLocs[i]; 2394 SDValue Val; 2395 2396 if (VA.isRegLoc()) { 2397 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2398 Chain = Val.getValue(1); 2399 InFlag = Val.getValue(2); 2400 } else if (VA.isMemLoc()) { 2401 report_fatal_error("TODO: return values in memory"); 2402 } else 2403 llvm_unreachable("unknown argument location type"); 2404 2405 switch (VA.getLocInfo()) { 2406 case CCValAssign::Full: 2407 break; 2408 case CCValAssign::BCvt: 2409 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2410 break; 2411 case CCValAssign::ZExt: 2412 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2413 DAG.getValueType(VA.getValVT())); 2414 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2415 break; 2416 case CCValAssign::SExt: 2417 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2418 DAG.getValueType(VA.getValVT())); 2419 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2420 break; 2421 case CCValAssign::AExt: 2422 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2423 break; 2424 default: 2425 llvm_unreachable("Unknown loc info!"); 2426 } 2427 2428 InVals.push_back(Val); 2429 } 2430 2431 return Chain; 2432 } 2433 2434 // Add code to pass special inputs required depending on used features separate 2435 // from the explicit user arguments present in the IR. 2436 void SITargetLowering::passSpecialInputs( 2437 CallLoweringInfo &CLI, 2438 CCState &CCInfo, 2439 const SIMachineFunctionInfo &Info, 2440 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2441 SmallVectorImpl<SDValue> &MemOpChains, 2442 SDValue Chain) const { 2443 // If we don't have a call site, this was a call inserted by 2444 // legalization. These can never use special inputs. 2445 if (!CLI.CS) 2446 return; 2447 2448 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2449 assert(CalleeFunc); 2450 2451 SelectionDAG &DAG = CLI.DAG; 2452 const SDLoc &DL = CLI.DL; 2453 2454 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2455 2456 auto &ArgUsageInfo = 2457 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2458 const AMDGPUFunctionArgInfo &CalleeArgInfo 2459 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2460 2461 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2462 2463 // TODO: Unify with private memory register handling. This is complicated by 2464 // the fact that at least in kernels, the input argument is not necessarily 2465 // in the same location as the input. 2466 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2467 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2468 AMDGPUFunctionArgInfo::QUEUE_PTR, 2469 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2470 AMDGPUFunctionArgInfo::DISPATCH_ID, 2471 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2472 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2473 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2474 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2475 }; 2476 2477 for (auto InputID : InputRegs) { 2478 const ArgDescriptor *OutgoingArg; 2479 const TargetRegisterClass *ArgRC; 2480 2481 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2482 if (!OutgoingArg) 2483 continue; 2484 2485 const ArgDescriptor *IncomingArg; 2486 const TargetRegisterClass *IncomingArgRC; 2487 std::tie(IncomingArg, IncomingArgRC) 2488 = CallerArgInfo.getPreloadedValue(InputID); 2489 assert(IncomingArgRC == ArgRC); 2490 2491 // All special arguments are ints for now. 2492 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2493 SDValue InputReg; 2494 2495 if (IncomingArg) { 2496 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2497 } else { 2498 // The implicit arg ptr is special because it doesn't have a corresponding 2499 // input for kernels, and is computed from the kernarg segment pointer. 2500 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2501 InputReg = getImplicitArgPtr(DAG, DL); 2502 } 2503 2504 if (OutgoingArg->isRegister()) { 2505 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2506 } else { 2507 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2508 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2509 SpecialArgOffset); 2510 MemOpChains.push_back(ArgStore); 2511 } 2512 } 2513 2514 // Pack workitem IDs into a single register or pass it as is if already 2515 // packed. 2516 const ArgDescriptor *OutgoingArg; 2517 const TargetRegisterClass *ArgRC; 2518 2519 std::tie(OutgoingArg, ArgRC) = 2520 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2521 if (!OutgoingArg) 2522 std::tie(OutgoingArg, ArgRC) = 2523 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2524 if (!OutgoingArg) 2525 std::tie(OutgoingArg, ArgRC) = 2526 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2527 if (!OutgoingArg) 2528 return; 2529 2530 const ArgDescriptor *IncomingArgX 2531 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2532 const ArgDescriptor *IncomingArgY 2533 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2534 const ArgDescriptor *IncomingArgZ 2535 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2536 2537 SDValue InputReg; 2538 SDLoc SL; 2539 2540 // If incoming ids are not packed we need to pack them. 2541 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2542 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2543 2544 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2545 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2546 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2547 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2548 InputReg = InputReg.getNode() ? 2549 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2550 } 2551 2552 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2553 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2554 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2555 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2556 InputReg = InputReg.getNode() ? 2557 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2558 } 2559 2560 if (!InputReg.getNode()) { 2561 // Workitem ids are already packed, any of present incoming arguments 2562 // will carry all required fields. 2563 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2564 IncomingArgX ? *IncomingArgX : 2565 IncomingArgY ? *IncomingArgY : 2566 *IncomingArgZ, ~0u); 2567 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2568 } 2569 2570 if (OutgoingArg->isRegister()) { 2571 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2572 } else { 2573 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2574 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2575 SpecialArgOffset); 2576 MemOpChains.push_back(ArgStore); 2577 } 2578 } 2579 2580 static bool canGuaranteeTCO(CallingConv::ID CC) { 2581 return CC == CallingConv::Fast; 2582 } 2583 2584 /// Return true if we might ever do TCO for calls with this calling convention. 2585 static bool mayTailCallThisCC(CallingConv::ID CC) { 2586 switch (CC) { 2587 case CallingConv::C: 2588 return true; 2589 default: 2590 return canGuaranteeTCO(CC); 2591 } 2592 } 2593 2594 bool SITargetLowering::isEligibleForTailCallOptimization( 2595 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2596 const SmallVectorImpl<ISD::OutputArg> &Outs, 2597 const SmallVectorImpl<SDValue> &OutVals, 2598 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2599 if (!mayTailCallThisCC(CalleeCC)) 2600 return false; 2601 2602 MachineFunction &MF = DAG.getMachineFunction(); 2603 const Function &CallerF = MF.getFunction(); 2604 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2605 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2606 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2607 2608 // Kernels aren't callable, and don't have a live in return address so it 2609 // doesn't make sense to do a tail call with entry functions. 2610 if (!CallerPreserved) 2611 return false; 2612 2613 bool CCMatch = CallerCC == CalleeCC; 2614 2615 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2616 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2617 return true; 2618 return false; 2619 } 2620 2621 // TODO: Can we handle var args? 2622 if (IsVarArg) 2623 return false; 2624 2625 for (const Argument &Arg : CallerF.args()) { 2626 if (Arg.hasByValAttr()) 2627 return false; 2628 } 2629 2630 LLVMContext &Ctx = *DAG.getContext(); 2631 2632 // Check that the call results are passed in the same way. 2633 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2634 CCAssignFnForCall(CalleeCC, IsVarArg), 2635 CCAssignFnForCall(CallerCC, IsVarArg))) 2636 return false; 2637 2638 // The callee has to preserve all registers the caller needs to preserve. 2639 if (!CCMatch) { 2640 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2641 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2642 return false; 2643 } 2644 2645 // Nothing more to check if the callee is taking no arguments. 2646 if (Outs.empty()) 2647 return true; 2648 2649 SmallVector<CCValAssign, 16> ArgLocs; 2650 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2651 2652 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2653 2654 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2655 // If the stack arguments for this call do not fit into our own save area then 2656 // the call cannot be made tail. 2657 // TODO: Is this really necessary? 2658 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2659 return false; 2660 2661 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2662 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2663 } 2664 2665 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2666 if (!CI->isTailCall()) 2667 return false; 2668 2669 const Function *ParentFn = CI->getParent()->getParent(); 2670 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2671 return false; 2672 return true; 2673 } 2674 2675 // The wave scratch offset register is used as the global base pointer. 2676 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2677 SmallVectorImpl<SDValue> &InVals) const { 2678 SelectionDAG &DAG = CLI.DAG; 2679 const SDLoc &DL = CLI.DL; 2680 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2681 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2682 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2683 SDValue Chain = CLI.Chain; 2684 SDValue Callee = CLI.Callee; 2685 bool &IsTailCall = CLI.IsTailCall; 2686 CallingConv::ID CallConv = CLI.CallConv; 2687 bool IsVarArg = CLI.IsVarArg; 2688 bool IsSibCall = false; 2689 bool IsThisReturn = false; 2690 MachineFunction &MF = DAG.getMachineFunction(); 2691 2692 if (Callee.isUndef() || isNullConstant(Callee)) { 2693 if (!CLI.IsTailCall) { 2694 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2695 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2696 } 2697 2698 return Chain; 2699 } 2700 2701 if (IsVarArg) { 2702 return lowerUnhandledCall(CLI, InVals, 2703 "unsupported call to variadic function "); 2704 } 2705 2706 if (!CLI.CS.getInstruction()) 2707 report_fatal_error("unsupported libcall legalization"); 2708 2709 if (!CLI.CS.getCalledFunction()) { 2710 return lowerUnhandledCall(CLI, InVals, 2711 "unsupported indirect call to function "); 2712 } 2713 2714 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2715 return lowerUnhandledCall(CLI, InVals, 2716 "unsupported required tail call to function "); 2717 } 2718 2719 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2720 // Note the issue is with the CC of the calling function, not of the call 2721 // itself. 2722 return lowerUnhandledCall(CLI, InVals, 2723 "unsupported call from graphics shader of function "); 2724 } 2725 2726 if (IsTailCall) { 2727 IsTailCall = isEligibleForTailCallOptimization( 2728 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2729 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2730 report_fatal_error("failed to perform tail call elimination on a call " 2731 "site marked musttail"); 2732 } 2733 2734 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2735 2736 // A sibling call is one where we're under the usual C ABI and not planning 2737 // to change that but can still do a tail call: 2738 if (!TailCallOpt && IsTailCall) 2739 IsSibCall = true; 2740 2741 if (IsTailCall) 2742 ++NumTailCalls; 2743 } 2744 2745 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2746 2747 // Analyze operands of the call, assigning locations to each operand. 2748 SmallVector<CCValAssign, 16> ArgLocs; 2749 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2750 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2751 2752 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2753 2754 // Get a count of how many bytes are to be pushed on the stack. 2755 unsigned NumBytes = CCInfo.getNextStackOffset(); 2756 2757 if (IsSibCall) { 2758 // Since we're not changing the ABI to make this a tail call, the memory 2759 // operands are already available in the caller's incoming argument space. 2760 NumBytes = 0; 2761 } 2762 2763 // FPDiff is the byte offset of the call's argument area from the callee's. 2764 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2765 // by this amount for a tail call. In a sibling call it must be 0 because the 2766 // caller will deallocate the entire stack and the callee still expects its 2767 // arguments to begin at SP+0. Completely unused for non-tail calls. 2768 int32_t FPDiff = 0; 2769 MachineFrameInfo &MFI = MF.getFrameInfo(); 2770 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2771 2772 // Adjust the stack pointer for the new arguments... 2773 // These operations are automatically eliminated by the prolog/epilog pass 2774 if (!IsSibCall) { 2775 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2776 2777 SmallVector<SDValue, 4> CopyFromChains; 2778 2779 // In the HSA case, this should be an identity copy. 2780 SDValue ScratchRSrcReg 2781 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2782 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2783 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2784 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2785 } 2786 2787 SmallVector<SDValue, 8> MemOpChains; 2788 MVT PtrVT = MVT::i32; 2789 2790 // Walk the register/memloc assignments, inserting copies/loads. 2791 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2792 CCValAssign &VA = ArgLocs[i]; 2793 SDValue Arg = OutVals[i]; 2794 2795 // Promote the value if needed. 2796 switch (VA.getLocInfo()) { 2797 case CCValAssign::Full: 2798 break; 2799 case CCValAssign::BCvt: 2800 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2801 break; 2802 case CCValAssign::ZExt: 2803 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2804 break; 2805 case CCValAssign::SExt: 2806 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2807 break; 2808 case CCValAssign::AExt: 2809 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2810 break; 2811 case CCValAssign::FPExt: 2812 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2813 break; 2814 default: 2815 llvm_unreachable("Unknown loc info!"); 2816 } 2817 2818 if (VA.isRegLoc()) { 2819 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2820 } else { 2821 assert(VA.isMemLoc()); 2822 2823 SDValue DstAddr; 2824 MachinePointerInfo DstInfo; 2825 2826 unsigned LocMemOffset = VA.getLocMemOffset(); 2827 int32_t Offset = LocMemOffset; 2828 2829 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2830 MaybeAlign Alignment; 2831 2832 if (IsTailCall) { 2833 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2834 unsigned OpSize = Flags.isByVal() ? 2835 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2836 2837 // FIXME: We can have better than the minimum byval required alignment. 2838 Alignment = 2839 Flags.isByVal() 2840 ? MaybeAlign(Flags.getByValAlign()) 2841 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2842 2843 Offset = Offset + FPDiff; 2844 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2845 2846 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2847 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2848 2849 // Make sure any stack arguments overlapping with where we're storing 2850 // are loaded before this eventual operation. Otherwise they'll be 2851 // clobbered. 2852 2853 // FIXME: Why is this really necessary? This seems to just result in a 2854 // lot of code to copy the stack and write them back to the same 2855 // locations, which are supposed to be immutable? 2856 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2857 } else { 2858 DstAddr = PtrOff; 2859 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2860 Alignment = 2861 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2862 } 2863 2864 if (Outs[i].Flags.isByVal()) { 2865 SDValue SizeNode = 2866 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2867 SDValue Cpy = DAG.getMemcpy( 2868 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2869 /*isVol = */ false, /*AlwaysInline = */ true, 2870 /*isTailCall = */ false, DstInfo, 2871 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2872 2873 MemOpChains.push_back(Cpy); 2874 } else { 2875 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2876 Alignment ? Alignment->value() : 0); 2877 MemOpChains.push_back(Store); 2878 } 2879 } 2880 } 2881 2882 // Copy special input registers after user input arguments. 2883 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2884 2885 if (!MemOpChains.empty()) 2886 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2887 2888 // Build a sequence of copy-to-reg nodes chained together with token chain 2889 // and flag operands which copy the outgoing args into the appropriate regs. 2890 SDValue InFlag; 2891 for (auto &RegToPass : RegsToPass) { 2892 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2893 RegToPass.second, InFlag); 2894 InFlag = Chain.getValue(1); 2895 } 2896 2897 2898 SDValue PhysReturnAddrReg; 2899 if (IsTailCall) { 2900 // Since the return is being combined with the call, we need to pass on the 2901 // return address. 2902 2903 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2904 SDValue ReturnAddrReg = CreateLiveInRegister( 2905 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2906 2907 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2908 MVT::i64); 2909 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2910 InFlag = Chain.getValue(1); 2911 } 2912 2913 // We don't usually want to end the call-sequence here because we would tidy 2914 // the frame up *after* the call, however in the ABI-changing tail-call case 2915 // we've carefully laid out the parameters so that when sp is reset they'll be 2916 // in the correct location. 2917 if (IsTailCall && !IsSibCall) { 2918 Chain = DAG.getCALLSEQ_END(Chain, 2919 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2920 DAG.getTargetConstant(0, DL, MVT::i32), 2921 InFlag, DL); 2922 InFlag = Chain.getValue(1); 2923 } 2924 2925 std::vector<SDValue> Ops; 2926 Ops.push_back(Chain); 2927 Ops.push_back(Callee); 2928 // Add a redundant copy of the callee global which will not be legalized, as 2929 // we need direct access to the callee later. 2930 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2931 const GlobalValue *GV = GSD->getGlobal(); 2932 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2933 2934 if (IsTailCall) { 2935 // Each tail call may have to adjust the stack by a different amount, so 2936 // this information must travel along with the operation for eventual 2937 // consumption by emitEpilogue. 2938 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2939 2940 Ops.push_back(PhysReturnAddrReg); 2941 } 2942 2943 // Add argument registers to the end of the list so that they are known live 2944 // into the call. 2945 for (auto &RegToPass : RegsToPass) { 2946 Ops.push_back(DAG.getRegister(RegToPass.first, 2947 RegToPass.second.getValueType())); 2948 } 2949 2950 // Add a register mask operand representing the call-preserved registers. 2951 2952 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2953 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2954 assert(Mask && "Missing call preserved mask for calling convention"); 2955 Ops.push_back(DAG.getRegisterMask(Mask)); 2956 2957 if (InFlag.getNode()) 2958 Ops.push_back(InFlag); 2959 2960 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2961 2962 // If we're doing a tall call, use a TC_RETURN here rather than an 2963 // actual call instruction. 2964 if (IsTailCall) { 2965 MFI.setHasTailCall(); 2966 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2967 } 2968 2969 // Returns a chain and a flag for retval copy to use. 2970 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2971 Chain = Call.getValue(0); 2972 InFlag = Call.getValue(1); 2973 2974 uint64_t CalleePopBytes = NumBytes; 2975 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2976 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2977 InFlag, DL); 2978 if (!Ins.empty()) 2979 InFlag = Chain.getValue(1); 2980 2981 // Handle result values, copying them out of physregs into vregs that we 2982 // return. 2983 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2984 InVals, IsThisReturn, 2985 IsThisReturn ? OutVals[0] : SDValue()); 2986 } 2987 2988 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 2989 const MachineFunction &MF) const { 2990 Register Reg = StringSwitch<Register>(RegName) 2991 .Case("m0", AMDGPU::M0) 2992 .Case("exec", AMDGPU::EXEC) 2993 .Case("exec_lo", AMDGPU::EXEC_LO) 2994 .Case("exec_hi", AMDGPU::EXEC_HI) 2995 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2996 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2997 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2998 .Default(Register()); 2999 3000 if (Reg == AMDGPU::NoRegister) { 3001 report_fatal_error(Twine("invalid register name \"" 3002 + StringRef(RegName) + "\".")); 3003 3004 } 3005 3006 if (!Subtarget->hasFlatScrRegister() && 3007 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3008 report_fatal_error(Twine("invalid register \"" 3009 + StringRef(RegName) + "\" for subtarget.")); 3010 } 3011 3012 switch (Reg) { 3013 case AMDGPU::M0: 3014 case AMDGPU::EXEC_LO: 3015 case AMDGPU::EXEC_HI: 3016 case AMDGPU::FLAT_SCR_LO: 3017 case AMDGPU::FLAT_SCR_HI: 3018 if (VT.getSizeInBits() == 32) 3019 return Reg; 3020 break; 3021 case AMDGPU::EXEC: 3022 case AMDGPU::FLAT_SCR: 3023 if (VT.getSizeInBits() == 64) 3024 return Reg; 3025 break; 3026 default: 3027 llvm_unreachable("missing register type checking"); 3028 } 3029 3030 report_fatal_error(Twine("invalid type for register \"" 3031 + StringRef(RegName) + "\".")); 3032 } 3033 3034 // If kill is not the last instruction, split the block so kill is always a 3035 // proper terminator. 3036 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3037 MachineBasicBlock *BB) const { 3038 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3039 3040 MachineBasicBlock::iterator SplitPoint(&MI); 3041 ++SplitPoint; 3042 3043 if (SplitPoint == BB->end()) { 3044 // Don't bother with a new block. 3045 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3046 return BB; 3047 } 3048 3049 MachineFunction *MF = BB->getParent(); 3050 MachineBasicBlock *SplitBB 3051 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3052 3053 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3054 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3055 3056 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3057 BB->addSuccessor(SplitBB); 3058 3059 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3060 return SplitBB; 3061 } 3062 3063 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3064 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3065 // be the first instruction in the remainder block. 3066 // 3067 /// \returns { LoopBody, Remainder } 3068 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3069 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3070 MachineFunction *MF = MBB.getParent(); 3071 MachineBasicBlock::iterator I(&MI); 3072 3073 // To insert the loop we need to split the block. Move everything after this 3074 // point to a new block, and insert a new empty block between the two. 3075 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3076 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3077 MachineFunction::iterator MBBI(MBB); 3078 ++MBBI; 3079 3080 MF->insert(MBBI, LoopBB); 3081 MF->insert(MBBI, RemainderBB); 3082 3083 LoopBB->addSuccessor(LoopBB); 3084 LoopBB->addSuccessor(RemainderBB); 3085 3086 // Move the rest of the block into a new block. 3087 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3088 3089 if (InstInLoop) { 3090 auto Next = std::next(I); 3091 3092 // Move instruction to loop body. 3093 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3094 3095 // Move the rest of the block. 3096 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3097 } else { 3098 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3099 } 3100 3101 MBB.addSuccessor(LoopBB); 3102 3103 return std::make_pair(LoopBB, RemainderBB); 3104 } 3105 3106 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3107 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3108 MachineBasicBlock *MBB = MI.getParent(); 3109 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3110 auto I = MI.getIterator(); 3111 auto E = std::next(I); 3112 3113 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3114 .addImm(0); 3115 3116 MIBundleBuilder Bundler(*MBB, I, E); 3117 finalizeBundle(*MBB, Bundler.begin()); 3118 } 3119 3120 MachineBasicBlock * 3121 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3122 MachineBasicBlock *BB) const { 3123 const DebugLoc &DL = MI.getDebugLoc(); 3124 3125 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3126 3127 MachineBasicBlock *LoopBB; 3128 MachineBasicBlock *RemainderBB; 3129 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3130 3131 // Apparently kill flags are only valid if the def is in the same block? 3132 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3133 Src->setIsKill(false); 3134 3135 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3136 3137 MachineBasicBlock::iterator I = LoopBB->end(); 3138 3139 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3140 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3141 3142 // Clear TRAP_STS.MEM_VIOL 3143 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3144 .addImm(0) 3145 .addImm(EncodedReg); 3146 3147 bundleInstWithWaitcnt(MI); 3148 3149 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3150 3151 // Load and check TRAP_STS.MEM_VIOL 3152 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3153 .addImm(EncodedReg); 3154 3155 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3156 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3157 .addReg(Reg, RegState::Kill) 3158 .addImm(0); 3159 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3160 .addMBB(LoopBB); 3161 3162 return RemainderBB; 3163 } 3164 3165 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3166 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3167 // will only do one iteration. In the worst case, this will loop 64 times. 3168 // 3169 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3170 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3171 const SIInstrInfo *TII, 3172 MachineRegisterInfo &MRI, 3173 MachineBasicBlock &OrigBB, 3174 MachineBasicBlock &LoopBB, 3175 const DebugLoc &DL, 3176 const MachineOperand &IdxReg, 3177 unsigned InitReg, 3178 unsigned ResultReg, 3179 unsigned PhiReg, 3180 unsigned InitSaveExecReg, 3181 int Offset, 3182 bool UseGPRIdxMode, 3183 bool IsIndirectSrc) { 3184 MachineFunction *MF = OrigBB.getParent(); 3185 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3186 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3187 MachineBasicBlock::iterator I = LoopBB.begin(); 3188 3189 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3190 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3191 Register NewExec = MRI.createVirtualRegister(BoolRC); 3192 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3193 Register CondReg = MRI.createVirtualRegister(BoolRC); 3194 3195 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3196 .addReg(InitReg) 3197 .addMBB(&OrigBB) 3198 .addReg(ResultReg) 3199 .addMBB(&LoopBB); 3200 3201 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3202 .addReg(InitSaveExecReg) 3203 .addMBB(&OrigBB) 3204 .addReg(NewExec) 3205 .addMBB(&LoopBB); 3206 3207 // Read the next variant <- also loop target. 3208 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3209 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3210 3211 // Compare the just read M0 value to all possible Idx values. 3212 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3213 .addReg(CurrentIdxReg) 3214 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3215 3216 // Update EXEC, save the original EXEC value to VCC. 3217 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3218 : AMDGPU::S_AND_SAVEEXEC_B64), 3219 NewExec) 3220 .addReg(CondReg, RegState::Kill); 3221 3222 MRI.setSimpleHint(NewExec, CondReg); 3223 3224 if (UseGPRIdxMode) { 3225 unsigned IdxReg; 3226 if (Offset == 0) { 3227 IdxReg = CurrentIdxReg; 3228 } else { 3229 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3230 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3231 .addReg(CurrentIdxReg, RegState::Kill) 3232 .addImm(Offset); 3233 } 3234 unsigned IdxMode = IsIndirectSrc ? 3235 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3236 MachineInstr *SetOn = 3237 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3238 .addReg(IdxReg, RegState::Kill) 3239 .addImm(IdxMode); 3240 SetOn->getOperand(3).setIsUndef(); 3241 } else { 3242 // Move index from VCC into M0 3243 if (Offset == 0) { 3244 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3245 .addReg(CurrentIdxReg, RegState::Kill); 3246 } else { 3247 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3248 .addReg(CurrentIdxReg, RegState::Kill) 3249 .addImm(Offset); 3250 } 3251 } 3252 3253 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3254 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3255 MachineInstr *InsertPt = 3256 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3257 : AMDGPU::S_XOR_B64_term), Exec) 3258 .addReg(Exec) 3259 .addReg(NewExec); 3260 3261 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3262 // s_cbranch_scc0? 3263 3264 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3265 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3266 .addMBB(&LoopBB); 3267 3268 return InsertPt->getIterator(); 3269 } 3270 3271 // This has slightly sub-optimal regalloc when the source vector is killed by 3272 // the read. The register allocator does not understand that the kill is 3273 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3274 // subregister from it, using 1 more VGPR than necessary. This was saved when 3275 // this was expanded after register allocation. 3276 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3277 MachineBasicBlock &MBB, 3278 MachineInstr &MI, 3279 unsigned InitResultReg, 3280 unsigned PhiReg, 3281 int Offset, 3282 bool UseGPRIdxMode, 3283 bool IsIndirectSrc) { 3284 MachineFunction *MF = MBB.getParent(); 3285 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3286 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3287 MachineRegisterInfo &MRI = MF->getRegInfo(); 3288 const DebugLoc &DL = MI.getDebugLoc(); 3289 MachineBasicBlock::iterator I(&MI); 3290 3291 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3292 Register DstReg = MI.getOperand(0).getReg(); 3293 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3294 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3295 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3296 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3297 3298 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3299 3300 // Save the EXEC mask 3301 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3302 .addReg(Exec); 3303 3304 MachineBasicBlock *LoopBB; 3305 MachineBasicBlock *RemainderBB; 3306 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3307 3308 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3309 3310 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3311 InitResultReg, DstReg, PhiReg, TmpExec, 3312 Offset, UseGPRIdxMode, IsIndirectSrc); 3313 3314 MachineBasicBlock::iterator First = RemainderBB->begin(); 3315 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3316 .addReg(SaveExec); 3317 3318 return InsPt; 3319 } 3320 3321 // Returns subreg index, offset 3322 static std::pair<unsigned, int> 3323 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3324 const TargetRegisterClass *SuperRC, 3325 unsigned VecReg, 3326 int Offset) { 3327 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3328 3329 // Skip out of bounds offsets, or else we would end up using an undefined 3330 // register. 3331 if (Offset >= NumElts || Offset < 0) 3332 return std::make_pair(AMDGPU::sub0, Offset); 3333 3334 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3335 } 3336 3337 // Return true if the index is an SGPR and was set. 3338 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3339 MachineRegisterInfo &MRI, 3340 MachineInstr &MI, 3341 int Offset, 3342 bool UseGPRIdxMode, 3343 bool IsIndirectSrc) { 3344 MachineBasicBlock *MBB = MI.getParent(); 3345 const DebugLoc &DL = MI.getDebugLoc(); 3346 MachineBasicBlock::iterator I(&MI); 3347 3348 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3349 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3350 3351 assert(Idx->getReg() != AMDGPU::NoRegister); 3352 3353 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3354 return false; 3355 3356 if (UseGPRIdxMode) { 3357 unsigned IdxMode = IsIndirectSrc ? 3358 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3359 if (Offset == 0) { 3360 MachineInstr *SetOn = 3361 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3362 .add(*Idx) 3363 .addImm(IdxMode); 3364 3365 SetOn->getOperand(3).setIsUndef(); 3366 } else { 3367 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3368 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3369 .add(*Idx) 3370 .addImm(Offset); 3371 MachineInstr *SetOn = 3372 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3373 .addReg(Tmp, RegState::Kill) 3374 .addImm(IdxMode); 3375 3376 SetOn->getOperand(3).setIsUndef(); 3377 } 3378 3379 return true; 3380 } 3381 3382 if (Offset == 0) { 3383 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3384 .add(*Idx); 3385 } else { 3386 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3387 .add(*Idx) 3388 .addImm(Offset); 3389 } 3390 3391 return true; 3392 } 3393 3394 // Control flow needs to be inserted if indexing with a VGPR. 3395 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3396 MachineBasicBlock &MBB, 3397 const GCNSubtarget &ST) { 3398 const SIInstrInfo *TII = ST.getInstrInfo(); 3399 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3400 MachineFunction *MF = MBB.getParent(); 3401 MachineRegisterInfo &MRI = MF->getRegInfo(); 3402 3403 Register Dst = MI.getOperand(0).getReg(); 3404 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3405 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3406 3407 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3408 3409 unsigned SubReg; 3410 std::tie(SubReg, Offset) 3411 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3412 3413 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3414 3415 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3416 MachineBasicBlock::iterator I(&MI); 3417 const DebugLoc &DL = MI.getDebugLoc(); 3418 3419 if (UseGPRIdxMode) { 3420 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3421 // to avoid interfering with other uses, so probably requires a new 3422 // optimization pass. 3423 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3424 .addReg(SrcReg, RegState::Undef, SubReg) 3425 .addReg(SrcReg, RegState::Implicit) 3426 .addReg(AMDGPU::M0, RegState::Implicit); 3427 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3428 } else { 3429 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3430 .addReg(SrcReg, RegState::Undef, SubReg) 3431 .addReg(SrcReg, RegState::Implicit); 3432 } 3433 3434 MI.eraseFromParent(); 3435 3436 return &MBB; 3437 } 3438 3439 const DebugLoc &DL = MI.getDebugLoc(); 3440 MachineBasicBlock::iterator I(&MI); 3441 3442 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3443 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3444 3445 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3446 3447 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3448 Offset, UseGPRIdxMode, true); 3449 MachineBasicBlock *LoopBB = InsPt->getParent(); 3450 3451 if (UseGPRIdxMode) { 3452 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3453 .addReg(SrcReg, RegState::Undef, SubReg) 3454 .addReg(SrcReg, RegState::Implicit) 3455 .addReg(AMDGPU::M0, RegState::Implicit); 3456 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3457 } else { 3458 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3459 .addReg(SrcReg, RegState::Undef, SubReg) 3460 .addReg(SrcReg, RegState::Implicit); 3461 } 3462 3463 MI.eraseFromParent(); 3464 3465 return LoopBB; 3466 } 3467 3468 static unsigned getIndirectRegWritePseudo(const SIRegisterInfo &TRI, 3469 const TargetRegisterClass *VecRC) { 3470 switch (TRI.getRegSizeInBits(*VecRC)) { 3471 case 32: // 4 bytes 3472 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V1; 3473 case 64: // 8 bytes 3474 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V2; 3475 case 96: // 12 bytes 3476 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V3; 3477 case 128: // 16 bytes 3478 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V4; 3479 case 160: // 20 bytes 3480 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V5; 3481 case 256: // 32 bytes 3482 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V8; 3483 case 512: // 64 bytes 3484 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V16; 3485 case 1024: // 128 bytes 3486 return AMDGPU::V_INDIRECT_REG_WRITE_B32_V32; 3487 default: 3488 llvm_unreachable("unsupported size for IndirectRegWrite pseudos"); 3489 } 3490 } 3491 3492 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3493 MachineBasicBlock &MBB, 3494 const GCNSubtarget &ST) { 3495 const SIInstrInfo *TII = ST.getInstrInfo(); 3496 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3497 MachineFunction *MF = MBB.getParent(); 3498 MachineRegisterInfo &MRI = MF->getRegInfo(); 3499 3500 Register Dst = MI.getOperand(0).getReg(); 3501 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3502 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3503 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3504 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3505 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3506 3507 // This can be an immediate, but will be folded later. 3508 assert(Val->getReg()); 3509 3510 unsigned SubReg; 3511 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3512 SrcVec->getReg(), 3513 Offset); 3514 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3515 3516 if (Idx->getReg() == AMDGPU::NoRegister) { 3517 MachineBasicBlock::iterator I(&MI); 3518 const DebugLoc &DL = MI.getDebugLoc(); 3519 3520 assert(Offset == 0); 3521 3522 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3523 .add(*SrcVec) 3524 .add(*Val) 3525 .addImm(SubReg); 3526 3527 MI.eraseFromParent(); 3528 return &MBB; 3529 } 3530 3531 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3532 MachineBasicBlock::iterator I(&MI); 3533 const DebugLoc &DL = MI.getDebugLoc(); 3534 3535 const MCInstrDesc &MovRelDesc 3536 = TII->get(getIndirectRegWritePseudo(TRI, VecRC)); 3537 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3538 .addReg(SrcVec->getReg()) 3539 .add(*Val) 3540 .addImm(SubReg); 3541 if (UseGPRIdxMode) 3542 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3543 3544 MI.eraseFromParent(); 3545 return &MBB; 3546 } 3547 3548 if (Val->isReg()) 3549 MRI.clearKillFlags(Val->getReg()); 3550 3551 const DebugLoc &DL = MI.getDebugLoc(); 3552 3553 Register PhiReg = MRI.createVirtualRegister(VecRC); 3554 3555 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3556 Offset, UseGPRIdxMode, false); 3557 MachineBasicBlock *LoopBB = InsPt->getParent(); 3558 3559 const MCInstrDesc &MovRelDesc = TII->get(getIndirectRegWritePseudo(TRI, VecRC)); 3560 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3561 .addReg(PhiReg) 3562 .add(*Val) 3563 .addImm(AMDGPU::sub0); 3564 if (UseGPRIdxMode) 3565 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3566 3567 MI.eraseFromParent(); 3568 return LoopBB; 3569 } 3570 3571 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3572 MachineInstr &MI, MachineBasicBlock *BB) const { 3573 3574 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3575 MachineFunction *MF = BB->getParent(); 3576 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3577 3578 if (TII->isMIMG(MI)) { 3579 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3580 report_fatal_error("missing mem operand from MIMG instruction"); 3581 } 3582 // Add a memoperand for mimg instructions so that they aren't assumed to 3583 // be ordered memory instuctions. 3584 3585 return BB; 3586 } 3587 3588 switch (MI.getOpcode()) { 3589 case AMDGPU::S_ADD_U64_PSEUDO: 3590 case AMDGPU::S_SUB_U64_PSEUDO: { 3591 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3592 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3593 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3594 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3595 const DebugLoc &DL = MI.getDebugLoc(); 3596 3597 MachineOperand &Dest = MI.getOperand(0); 3598 MachineOperand &Src0 = MI.getOperand(1); 3599 MachineOperand &Src1 = MI.getOperand(2); 3600 3601 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3602 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3603 3604 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3605 Src0, BoolRC, AMDGPU::sub0, 3606 &AMDGPU::SReg_32RegClass); 3607 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3608 Src0, BoolRC, AMDGPU::sub1, 3609 &AMDGPU::SReg_32RegClass); 3610 3611 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3612 Src1, BoolRC, AMDGPU::sub0, 3613 &AMDGPU::SReg_32RegClass); 3614 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3615 Src1, BoolRC, AMDGPU::sub1, 3616 &AMDGPU::SReg_32RegClass); 3617 3618 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3619 3620 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3621 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3622 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3623 .add(Src0Sub0) 3624 .add(Src1Sub0); 3625 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3626 .add(Src0Sub1) 3627 .add(Src1Sub1); 3628 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3629 .addReg(DestSub0) 3630 .addImm(AMDGPU::sub0) 3631 .addReg(DestSub1) 3632 .addImm(AMDGPU::sub1); 3633 MI.eraseFromParent(); 3634 return BB; 3635 } 3636 case AMDGPU::SI_INIT_M0: { 3637 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3638 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3639 .add(MI.getOperand(0)); 3640 MI.eraseFromParent(); 3641 return BB; 3642 } 3643 case AMDGPU::SI_INIT_EXEC: 3644 // This should be before all vector instructions. 3645 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3646 AMDGPU::EXEC) 3647 .addImm(MI.getOperand(0).getImm()); 3648 MI.eraseFromParent(); 3649 return BB; 3650 3651 case AMDGPU::SI_INIT_EXEC_LO: 3652 // This should be before all vector instructions. 3653 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3654 AMDGPU::EXEC_LO) 3655 .addImm(MI.getOperand(0).getImm()); 3656 MI.eraseFromParent(); 3657 return BB; 3658 3659 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3660 // Extract the thread count from an SGPR input and set EXEC accordingly. 3661 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3662 // 3663 // S_BFE_U32 count, input, {shift, 7} 3664 // S_BFM_B64 exec, count, 0 3665 // S_CMP_EQ_U32 count, 64 3666 // S_CMOV_B64 exec, -1 3667 MachineInstr *FirstMI = &*BB->begin(); 3668 MachineRegisterInfo &MRI = MF->getRegInfo(); 3669 Register InputReg = MI.getOperand(0).getReg(); 3670 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3671 bool Found = false; 3672 3673 // Move the COPY of the input reg to the beginning, so that we can use it. 3674 for (auto I = BB->begin(); I != &MI; I++) { 3675 if (I->getOpcode() != TargetOpcode::COPY || 3676 I->getOperand(0).getReg() != InputReg) 3677 continue; 3678 3679 if (I == FirstMI) { 3680 FirstMI = &*++BB->begin(); 3681 } else { 3682 I->removeFromParent(); 3683 BB->insert(FirstMI, &*I); 3684 } 3685 Found = true; 3686 break; 3687 } 3688 assert(Found); 3689 (void)Found; 3690 3691 // This should be before all vector instructions. 3692 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3693 bool isWave32 = getSubtarget()->isWave32(); 3694 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3695 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3696 .addReg(InputReg) 3697 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3698 BuildMI(*BB, FirstMI, DebugLoc(), 3699 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3700 Exec) 3701 .addReg(CountReg) 3702 .addImm(0); 3703 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3704 .addReg(CountReg, RegState::Kill) 3705 .addImm(getSubtarget()->getWavefrontSize()); 3706 BuildMI(*BB, FirstMI, DebugLoc(), 3707 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3708 Exec) 3709 .addImm(-1); 3710 MI.eraseFromParent(); 3711 return BB; 3712 } 3713 3714 case AMDGPU::GET_GROUPSTATICSIZE: { 3715 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3716 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3717 DebugLoc DL = MI.getDebugLoc(); 3718 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3719 .add(MI.getOperand(0)) 3720 .addImm(MFI->getLDSSize()); 3721 MI.eraseFromParent(); 3722 return BB; 3723 } 3724 case AMDGPU::SI_INDIRECT_SRC_V1: 3725 case AMDGPU::SI_INDIRECT_SRC_V2: 3726 case AMDGPU::SI_INDIRECT_SRC_V4: 3727 case AMDGPU::SI_INDIRECT_SRC_V8: 3728 case AMDGPU::SI_INDIRECT_SRC_V16: 3729 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3730 case AMDGPU::SI_INDIRECT_DST_V1: 3731 case AMDGPU::SI_INDIRECT_DST_V2: 3732 case AMDGPU::SI_INDIRECT_DST_V4: 3733 case AMDGPU::SI_INDIRECT_DST_V8: 3734 case AMDGPU::SI_INDIRECT_DST_V16: 3735 return emitIndirectDst(MI, *BB, *getSubtarget()); 3736 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3737 case AMDGPU::SI_KILL_I1_PSEUDO: 3738 return splitKillBlock(MI, BB); 3739 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3740 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3741 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3742 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3743 3744 Register Dst = MI.getOperand(0).getReg(); 3745 Register Src0 = MI.getOperand(1).getReg(); 3746 Register Src1 = MI.getOperand(2).getReg(); 3747 const DebugLoc &DL = MI.getDebugLoc(); 3748 Register SrcCond = MI.getOperand(3).getReg(); 3749 3750 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3751 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3752 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3753 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3754 3755 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3756 .addReg(SrcCond); 3757 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3758 .addImm(0) 3759 .addReg(Src0, 0, AMDGPU::sub0) 3760 .addImm(0) 3761 .addReg(Src1, 0, AMDGPU::sub0) 3762 .addReg(SrcCondCopy); 3763 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3764 .addImm(0) 3765 .addReg(Src0, 0, AMDGPU::sub1) 3766 .addImm(0) 3767 .addReg(Src1, 0, AMDGPU::sub1) 3768 .addReg(SrcCondCopy); 3769 3770 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3771 .addReg(DstLo) 3772 .addImm(AMDGPU::sub0) 3773 .addReg(DstHi) 3774 .addImm(AMDGPU::sub1); 3775 MI.eraseFromParent(); 3776 return BB; 3777 } 3778 case AMDGPU::SI_BR_UNDEF: { 3779 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3780 const DebugLoc &DL = MI.getDebugLoc(); 3781 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3782 .add(MI.getOperand(0)); 3783 Br->getOperand(1).setIsUndef(true); // read undef SCC 3784 MI.eraseFromParent(); 3785 return BB; 3786 } 3787 case AMDGPU::ADJCALLSTACKUP: 3788 case AMDGPU::ADJCALLSTACKDOWN: { 3789 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3790 MachineInstrBuilder MIB(*MF, &MI); 3791 3792 // Add an implicit use of the frame offset reg to prevent the restore copy 3793 // inserted after the call from being reorderd after stack operations in the 3794 // the caller's frame. 3795 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3796 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3797 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3798 return BB; 3799 } 3800 case AMDGPU::SI_CALL_ISEL: { 3801 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3802 const DebugLoc &DL = MI.getDebugLoc(); 3803 3804 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3805 3806 MachineInstrBuilder MIB; 3807 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3808 3809 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3810 MIB.add(MI.getOperand(I)); 3811 3812 MIB.cloneMemRefs(MI); 3813 MI.eraseFromParent(); 3814 return BB; 3815 } 3816 case AMDGPU::V_ADD_I32_e32: 3817 case AMDGPU::V_SUB_I32_e32: 3818 case AMDGPU::V_SUBREV_I32_e32: { 3819 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3820 const DebugLoc &DL = MI.getDebugLoc(); 3821 unsigned Opc = MI.getOpcode(); 3822 3823 bool NeedClampOperand = false; 3824 if (TII->pseudoToMCOpcode(Opc) == -1) { 3825 Opc = AMDGPU::getVOPe64(Opc); 3826 NeedClampOperand = true; 3827 } 3828 3829 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3830 if (TII->isVOP3(*I)) { 3831 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3832 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3833 I.addReg(TRI->getVCC(), RegState::Define); 3834 } 3835 I.add(MI.getOperand(1)) 3836 .add(MI.getOperand(2)); 3837 if (NeedClampOperand) 3838 I.addImm(0); // clamp bit for e64 encoding 3839 3840 TII->legalizeOperands(*I); 3841 3842 MI.eraseFromParent(); 3843 return BB; 3844 } 3845 case AMDGPU::DS_GWS_INIT: 3846 case AMDGPU::DS_GWS_SEMA_V: 3847 case AMDGPU::DS_GWS_SEMA_BR: 3848 case AMDGPU::DS_GWS_SEMA_P: 3849 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3850 case AMDGPU::DS_GWS_BARRIER: 3851 // A s_waitcnt 0 is required to be the instruction immediately following. 3852 if (getSubtarget()->hasGWSAutoReplay()) { 3853 bundleInstWithWaitcnt(MI); 3854 return BB; 3855 } 3856 3857 return emitGWSMemViolTestLoop(MI, BB); 3858 default: 3859 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3860 } 3861 } 3862 3863 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3864 return isTypeLegal(VT.getScalarType()); 3865 } 3866 3867 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3868 // This currently forces unfolding various combinations of fsub into fma with 3869 // free fneg'd operands. As long as we have fast FMA (controlled by 3870 // isFMAFasterThanFMulAndFAdd), we should perform these. 3871 3872 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3873 // most of these combines appear to be cycle neutral but save on instruction 3874 // count / code size. 3875 return true; 3876 } 3877 3878 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3879 EVT VT) const { 3880 if (!VT.isVector()) { 3881 return MVT::i1; 3882 } 3883 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3884 } 3885 3886 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3887 // TODO: Should i16 be used always if legal? For now it would force VALU 3888 // shifts. 3889 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3890 } 3891 3892 // Answering this is somewhat tricky and depends on the specific device which 3893 // have different rates for fma or all f64 operations. 3894 // 3895 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3896 // regardless of which device (although the number of cycles differs between 3897 // devices), so it is always profitable for f64. 3898 // 3899 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3900 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3901 // which we can always do even without fused FP ops since it returns the same 3902 // result as the separate operations and since it is always full 3903 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3904 // however does not support denormals, so we do report fma as faster if we have 3905 // a fast fma device and require denormals. 3906 // 3907 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3908 EVT VT) const { 3909 VT = VT.getScalarType(); 3910 3911 switch (VT.getSimpleVT().SimpleTy) { 3912 case MVT::f32: { 3913 // This is as fast on some subtargets. However, we always have full rate f32 3914 // mad available which returns the same result as the separate operations 3915 // which we should prefer over fma. We can't use this if we want to support 3916 // denormals, so only report this in these cases. 3917 if (hasFP32Denormals(MF)) 3918 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3919 3920 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3921 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3922 } 3923 case MVT::f64: 3924 return true; 3925 case MVT::f16: 3926 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3927 default: 3928 break; 3929 } 3930 3931 return false; 3932 } 3933 3934 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3935 const SDNode *N) const { 3936 // TODO: Check future ftz flag 3937 // v_mad_f32/v_mac_f32 do not support denormals. 3938 EVT VT = N->getValueType(0); 3939 if (VT == MVT::f32) 3940 return !hasFP32Denormals(DAG.getMachineFunction()); 3941 if (VT == MVT::f16) { 3942 return Subtarget->hasMadF16() && 3943 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3944 } 3945 3946 return false; 3947 } 3948 3949 //===----------------------------------------------------------------------===// 3950 // Custom DAG Lowering Operations 3951 //===----------------------------------------------------------------------===// 3952 3953 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3954 // wider vector type is legal. 3955 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3956 SelectionDAG &DAG) const { 3957 unsigned Opc = Op.getOpcode(); 3958 EVT VT = Op.getValueType(); 3959 assert(VT == MVT::v4f16); 3960 3961 SDValue Lo, Hi; 3962 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3963 3964 SDLoc SL(Op); 3965 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3966 Op->getFlags()); 3967 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3968 Op->getFlags()); 3969 3970 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3971 } 3972 3973 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3974 // wider vector type is legal. 3975 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3976 SelectionDAG &DAG) const { 3977 unsigned Opc = Op.getOpcode(); 3978 EVT VT = Op.getValueType(); 3979 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3980 3981 SDValue Lo0, Hi0; 3982 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3983 SDValue Lo1, Hi1; 3984 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3985 3986 SDLoc SL(Op); 3987 3988 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3989 Op->getFlags()); 3990 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3991 Op->getFlags()); 3992 3993 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3994 } 3995 3996 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 3997 SelectionDAG &DAG) const { 3998 unsigned Opc = Op.getOpcode(); 3999 EVT VT = Op.getValueType(); 4000 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4001 4002 SDValue Lo0, Hi0; 4003 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4004 SDValue Lo1, Hi1; 4005 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4006 SDValue Lo2, Hi2; 4007 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4008 4009 SDLoc SL(Op); 4010 4011 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4012 Op->getFlags()); 4013 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4014 Op->getFlags()); 4015 4016 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4017 } 4018 4019 4020 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4021 switch (Op.getOpcode()) { 4022 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4023 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4024 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4025 case ISD::LOAD: { 4026 SDValue Result = LowerLOAD(Op, DAG); 4027 assert((!Result.getNode() || 4028 Result.getNode()->getNumValues() == 2) && 4029 "Load should return a value and a chain"); 4030 return Result; 4031 } 4032 4033 case ISD::FSIN: 4034 case ISD::FCOS: 4035 return LowerTrig(Op, DAG); 4036 case ISD::SELECT: return LowerSELECT(Op, DAG); 4037 case ISD::FDIV: return LowerFDIV(Op, DAG); 4038 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4039 case ISD::STORE: return LowerSTORE(Op, DAG); 4040 case ISD::GlobalAddress: { 4041 MachineFunction &MF = DAG.getMachineFunction(); 4042 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4043 return LowerGlobalAddress(MFI, Op, DAG); 4044 } 4045 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4046 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4047 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4048 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4049 case ISD::INSERT_SUBVECTOR: 4050 return lowerINSERT_SUBVECTOR(Op, DAG); 4051 case ISD::INSERT_VECTOR_ELT: 4052 return lowerINSERT_VECTOR_ELT(Op, DAG); 4053 case ISD::EXTRACT_VECTOR_ELT: 4054 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4055 case ISD::VECTOR_SHUFFLE: 4056 return lowerVECTOR_SHUFFLE(Op, DAG); 4057 case ISD::BUILD_VECTOR: 4058 return lowerBUILD_VECTOR(Op, DAG); 4059 case ISD::FP_ROUND: 4060 return lowerFP_ROUND(Op, DAG); 4061 case ISD::TRAP: 4062 return lowerTRAP(Op, DAG); 4063 case ISD::DEBUGTRAP: 4064 return lowerDEBUGTRAP(Op, DAG); 4065 case ISD::FABS: 4066 case ISD::FNEG: 4067 case ISD::FCANONICALIZE: 4068 return splitUnaryVectorOp(Op, DAG); 4069 case ISD::FMINNUM: 4070 case ISD::FMAXNUM: 4071 return lowerFMINNUM_FMAXNUM(Op, DAG); 4072 case ISD::FMA: 4073 return splitTernaryVectorOp(Op, DAG); 4074 case ISD::SHL: 4075 case ISD::SRA: 4076 case ISD::SRL: 4077 case ISD::ADD: 4078 case ISD::SUB: 4079 case ISD::MUL: 4080 case ISD::SMIN: 4081 case ISD::SMAX: 4082 case ISD::UMIN: 4083 case ISD::UMAX: 4084 case ISD::FADD: 4085 case ISD::FMUL: 4086 case ISD::FMINNUM_IEEE: 4087 case ISD::FMAXNUM_IEEE: 4088 return splitBinaryVectorOp(Op, DAG); 4089 } 4090 return SDValue(); 4091 } 4092 4093 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4094 const SDLoc &DL, 4095 SelectionDAG &DAG, bool Unpacked) { 4096 if (!LoadVT.isVector()) 4097 return Result; 4098 4099 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4100 // Truncate to v2i16/v4i16. 4101 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4102 4103 // Workaround legalizer not scalarizing truncate after vector op 4104 // legalization byt not creating intermediate vector trunc. 4105 SmallVector<SDValue, 4> Elts; 4106 DAG.ExtractVectorElements(Result, Elts); 4107 for (SDValue &Elt : Elts) 4108 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4109 4110 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4111 4112 // Bitcast to original type (v2f16/v4f16). 4113 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4114 } 4115 4116 // Cast back to the original packed type. 4117 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4118 } 4119 4120 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4121 MemSDNode *M, 4122 SelectionDAG &DAG, 4123 ArrayRef<SDValue> Ops, 4124 bool IsIntrinsic) const { 4125 SDLoc DL(M); 4126 4127 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4128 EVT LoadVT = M->getValueType(0); 4129 4130 EVT EquivLoadVT = LoadVT; 4131 if (Unpacked && LoadVT.isVector()) { 4132 EquivLoadVT = LoadVT.isVector() ? 4133 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4134 LoadVT.getVectorNumElements()) : LoadVT; 4135 } 4136 4137 // Change from v4f16/v2f16 to EquivLoadVT. 4138 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4139 4140 SDValue Load 4141 = DAG.getMemIntrinsicNode( 4142 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4143 VTList, Ops, M->getMemoryVT(), 4144 M->getMemOperand()); 4145 if (!Unpacked) // Just adjusted the opcode. 4146 return Load; 4147 4148 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4149 4150 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4151 } 4152 4153 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4154 SelectionDAG &DAG, 4155 ArrayRef<SDValue> Ops) const { 4156 SDLoc DL(M); 4157 EVT LoadVT = M->getValueType(0); 4158 EVT EltType = LoadVT.getScalarType(); 4159 EVT IntVT = LoadVT.changeTypeToInteger(); 4160 4161 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4162 4163 unsigned Opc = 4164 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4165 4166 if (IsD16) { 4167 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4168 } 4169 4170 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4171 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4172 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4173 4174 if (isTypeLegal(LoadVT)) { 4175 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4176 M->getMemOperand(), DAG); 4177 } 4178 4179 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4180 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4181 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4182 M->getMemOperand(), DAG); 4183 return DAG.getMergeValues( 4184 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4185 DL); 4186 } 4187 4188 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4189 SDNode *N, SelectionDAG &DAG) { 4190 EVT VT = N->getValueType(0); 4191 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4192 int CondCode = CD->getSExtValue(); 4193 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4194 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4195 return DAG.getUNDEF(VT); 4196 4197 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4198 4199 SDValue LHS = N->getOperand(1); 4200 SDValue RHS = N->getOperand(2); 4201 4202 SDLoc DL(N); 4203 4204 EVT CmpVT = LHS.getValueType(); 4205 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4206 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4207 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4208 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4209 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4210 } 4211 4212 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4213 4214 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4215 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4216 4217 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4218 DAG.getCondCode(CCOpcode)); 4219 if (VT.bitsEq(CCVT)) 4220 return SetCC; 4221 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4222 } 4223 4224 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4225 SDNode *N, SelectionDAG &DAG) { 4226 EVT VT = N->getValueType(0); 4227 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4228 4229 int CondCode = CD->getSExtValue(); 4230 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4231 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4232 return DAG.getUNDEF(VT); 4233 } 4234 4235 SDValue Src0 = N->getOperand(1); 4236 SDValue Src1 = N->getOperand(2); 4237 EVT CmpVT = Src0.getValueType(); 4238 SDLoc SL(N); 4239 4240 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4241 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4242 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4243 } 4244 4245 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4246 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4247 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4248 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4249 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4250 Src1, DAG.getCondCode(CCOpcode)); 4251 if (VT.bitsEq(CCVT)) 4252 return SetCC; 4253 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4254 } 4255 4256 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4257 SmallVectorImpl<SDValue> &Results, 4258 SelectionDAG &DAG) const { 4259 switch (N->getOpcode()) { 4260 case ISD::INSERT_VECTOR_ELT: { 4261 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4262 Results.push_back(Res); 4263 return; 4264 } 4265 case ISD::EXTRACT_VECTOR_ELT: { 4266 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4267 Results.push_back(Res); 4268 return; 4269 } 4270 case ISD::INTRINSIC_WO_CHAIN: { 4271 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4272 switch (IID) { 4273 case Intrinsic::amdgcn_cvt_pkrtz: { 4274 SDValue Src0 = N->getOperand(1); 4275 SDValue Src1 = N->getOperand(2); 4276 SDLoc SL(N); 4277 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4278 Src0, Src1); 4279 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4280 return; 4281 } 4282 case Intrinsic::amdgcn_cvt_pknorm_i16: 4283 case Intrinsic::amdgcn_cvt_pknorm_u16: 4284 case Intrinsic::amdgcn_cvt_pk_i16: 4285 case Intrinsic::amdgcn_cvt_pk_u16: { 4286 SDValue Src0 = N->getOperand(1); 4287 SDValue Src1 = N->getOperand(2); 4288 SDLoc SL(N); 4289 unsigned Opcode; 4290 4291 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4292 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4293 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4294 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4295 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4296 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4297 else 4298 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4299 4300 EVT VT = N->getValueType(0); 4301 if (isTypeLegal(VT)) 4302 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4303 else { 4304 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4305 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4306 } 4307 return; 4308 } 4309 } 4310 break; 4311 } 4312 case ISD::INTRINSIC_W_CHAIN: { 4313 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4314 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4315 // FIXME: Hacky 4316 Results.push_back(Res.getOperand(0)); 4317 Results.push_back(Res.getOperand(1)); 4318 } else { 4319 Results.push_back(Res); 4320 Results.push_back(Res.getValue(1)); 4321 } 4322 return; 4323 } 4324 4325 break; 4326 } 4327 case ISD::SELECT: { 4328 SDLoc SL(N); 4329 EVT VT = N->getValueType(0); 4330 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4331 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4332 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4333 4334 EVT SelectVT = NewVT; 4335 if (NewVT.bitsLT(MVT::i32)) { 4336 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4337 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4338 SelectVT = MVT::i32; 4339 } 4340 4341 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4342 N->getOperand(0), LHS, RHS); 4343 4344 if (NewVT != SelectVT) 4345 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4346 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4347 return; 4348 } 4349 case ISD::FNEG: { 4350 if (N->getValueType(0) != MVT::v2f16) 4351 break; 4352 4353 SDLoc SL(N); 4354 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4355 4356 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4357 BC, 4358 DAG.getConstant(0x80008000, SL, MVT::i32)); 4359 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4360 return; 4361 } 4362 case ISD::FABS: { 4363 if (N->getValueType(0) != MVT::v2f16) 4364 break; 4365 4366 SDLoc SL(N); 4367 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4368 4369 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4370 BC, 4371 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4372 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4373 return; 4374 } 4375 default: 4376 break; 4377 } 4378 } 4379 4380 /// Helper function for LowerBRCOND 4381 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4382 4383 SDNode *Parent = Value.getNode(); 4384 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4385 I != E; ++I) { 4386 4387 if (I.getUse().get() != Value) 4388 continue; 4389 4390 if (I->getOpcode() == Opcode) 4391 return *I; 4392 } 4393 return nullptr; 4394 } 4395 4396 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4397 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4398 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4399 case Intrinsic::amdgcn_if: 4400 return AMDGPUISD::IF; 4401 case Intrinsic::amdgcn_else: 4402 return AMDGPUISD::ELSE; 4403 case Intrinsic::amdgcn_loop: 4404 return AMDGPUISD::LOOP; 4405 case Intrinsic::amdgcn_end_cf: 4406 llvm_unreachable("should not occur"); 4407 default: 4408 return 0; 4409 } 4410 } 4411 4412 // break, if_break, else_break are all only used as inputs to loop, not 4413 // directly as branch conditions. 4414 return 0; 4415 } 4416 4417 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4418 const Triple &TT = getTargetMachine().getTargetTriple(); 4419 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4420 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4421 AMDGPU::shouldEmitConstantsToTextSection(TT); 4422 } 4423 4424 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4425 // FIXME: Either avoid relying on address space here or change the default 4426 // address space for functions to avoid the explicit check. 4427 return (GV->getValueType()->isFunctionTy() || 4428 GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4429 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4430 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4431 !shouldEmitFixup(GV) && 4432 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4433 } 4434 4435 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4436 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4437 } 4438 4439 /// This transforms the control flow intrinsics to get the branch destination as 4440 /// last parameter, also switches branch target with BR if the need arise 4441 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4442 SelectionDAG &DAG) const { 4443 SDLoc DL(BRCOND); 4444 4445 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4446 SDValue Target = BRCOND.getOperand(2); 4447 SDNode *BR = nullptr; 4448 SDNode *SetCC = nullptr; 4449 4450 if (Intr->getOpcode() == ISD::SETCC) { 4451 // As long as we negate the condition everything is fine 4452 SetCC = Intr; 4453 Intr = SetCC->getOperand(0).getNode(); 4454 4455 } else { 4456 // Get the target from BR if we don't negate the condition 4457 BR = findUser(BRCOND, ISD::BR); 4458 Target = BR->getOperand(1); 4459 } 4460 4461 // FIXME: This changes the types of the intrinsics instead of introducing new 4462 // nodes with the correct types. 4463 // e.g. llvm.amdgcn.loop 4464 4465 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4466 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4467 4468 unsigned CFNode = isCFIntrinsic(Intr); 4469 if (CFNode == 0) { 4470 // This is a uniform branch so we don't need to legalize. 4471 return BRCOND; 4472 } 4473 4474 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4475 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4476 4477 assert(!SetCC || 4478 (SetCC->getConstantOperandVal(1) == 1 && 4479 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4480 ISD::SETNE)); 4481 4482 // operands of the new intrinsic call 4483 SmallVector<SDValue, 4> Ops; 4484 if (HaveChain) 4485 Ops.push_back(BRCOND.getOperand(0)); 4486 4487 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4488 Ops.push_back(Target); 4489 4490 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4491 4492 // build the new intrinsic call 4493 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4494 4495 if (!HaveChain) { 4496 SDValue Ops[] = { 4497 SDValue(Result, 0), 4498 BRCOND.getOperand(0) 4499 }; 4500 4501 Result = DAG.getMergeValues(Ops, DL).getNode(); 4502 } 4503 4504 if (BR) { 4505 // Give the branch instruction our target 4506 SDValue Ops[] = { 4507 BR->getOperand(0), 4508 BRCOND.getOperand(2) 4509 }; 4510 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4511 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4512 BR = NewBR.getNode(); 4513 } 4514 4515 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4516 4517 // Copy the intrinsic results to registers 4518 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4519 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4520 if (!CopyToReg) 4521 continue; 4522 4523 Chain = DAG.getCopyToReg( 4524 Chain, DL, 4525 CopyToReg->getOperand(1), 4526 SDValue(Result, i - 1), 4527 SDValue()); 4528 4529 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4530 } 4531 4532 // Remove the old intrinsic from the chain 4533 DAG.ReplaceAllUsesOfValueWith( 4534 SDValue(Intr, Intr->getNumValues() - 1), 4535 Intr->getOperand(0)); 4536 4537 return Chain; 4538 } 4539 4540 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4541 SelectionDAG &DAG) const { 4542 MVT VT = Op.getSimpleValueType(); 4543 SDLoc DL(Op); 4544 // Checking the depth 4545 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4546 return DAG.getConstant(0, DL, VT); 4547 4548 MachineFunction &MF = DAG.getMachineFunction(); 4549 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4550 // Check for kernel and shader functions 4551 if (Info->isEntryFunction()) 4552 return DAG.getConstant(0, DL, VT); 4553 4554 MachineFrameInfo &MFI = MF.getFrameInfo(); 4555 // There is a call to @llvm.returnaddress in this function 4556 MFI.setReturnAddressIsTaken(true); 4557 4558 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4559 // Get the return address reg and mark it as an implicit live-in 4560 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4561 4562 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4563 } 4564 4565 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4566 SDValue Op, 4567 const SDLoc &DL, 4568 EVT VT) const { 4569 return Op.getValueType().bitsLE(VT) ? 4570 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4571 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4572 } 4573 4574 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4575 assert(Op.getValueType() == MVT::f16 && 4576 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4577 4578 SDValue Src = Op.getOperand(0); 4579 EVT SrcVT = Src.getValueType(); 4580 if (SrcVT != MVT::f64) 4581 return Op; 4582 4583 SDLoc DL(Op); 4584 4585 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4586 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4587 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4588 } 4589 4590 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4591 SelectionDAG &DAG) const { 4592 EVT VT = Op.getValueType(); 4593 const MachineFunction &MF = DAG.getMachineFunction(); 4594 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4595 bool IsIEEEMode = Info->getMode().IEEE; 4596 4597 // FIXME: Assert during eslection that this is only selected for 4598 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4599 // mode functions, but this happens to be OK since it's only done in cases 4600 // where there is known no sNaN. 4601 if (IsIEEEMode) 4602 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4603 4604 if (VT == MVT::v4f16) 4605 return splitBinaryVectorOp(Op, DAG); 4606 return Op; 4607 } 4608 4609 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4610 SDLoc SL(Op); 4611 SDValue Chain = Op.getOperand(0); 4612 4613 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4614 !Subtarget->isTrapHandlerEnabled()) 4615 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4616 4617 MachineFunction &MF = DAG.getMachineFunction(); 4618 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4619 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4620 assert(UserSGPR != AMDGPU::NoRegister); 4621 SDValue QueuePtr = CreateLiveInRegister( 4622 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4623 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4624 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4625 QueuePtr, SDValue()); 4626 SDValue Ops[] = { 4627 ToReg, 4628 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4629 SGPR01, 4630 ToReg.getValue(1) 4631 }; 4632 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4633 } 4634 4635 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4636 SDLoc SL(Op); 4637 SDValue Chain = Op.getOperand(0); 4638 MachineFunction &MF = DAG.getMachineFunction(); 4639 4640 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4641 !Subtarget->isTrapHandlerEnabled()) { 4642 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4643 "debugtrap handler not supported", 4644 Op.getDebugLoc(), 4645 DS_Warning); 4646 LLVMContext &Ctx = MF.getFunction().getContext(); 4647 Ctx.diagnose(NoTrap); 4648 return Chain; 4649 } 4650 4651 SDValue Ops[] = { 4652 Chain, 4653 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4654 }; 4655 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4656 } 4657 4658 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4659 SelectionDAG &DAG) const { 4660 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4661 if (Subtarget->hasApertureRegs()) { 4662 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4663 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4664 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4665 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4666 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4667 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4668 unsigned Encoding = 4669 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4670 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4671 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4672 4673 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4674 SDValue ApertureReg = SDValue( 4675 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4676 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4677 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4678 } 4679 4680 MachineFunction &MF = DAG.getMachineFunction(); 4681 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4682 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4683 assert(UserSGPR != AMDGPU::NoRegister); 4684 4685 SDValue QueuePtr = CreateLiveInRegister( 4686 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4687 4688 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4689 // private_segment_aperture_base_hi. 4690 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4691 4692 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4693 4694 // TODO: Use custom target PseudoSourceValue. 4695 // TODO: We should use the value from the IR intrinsic call, but it might not 4696 // be available and how do we get it? 4697 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4698 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4699 MinAlign(64, StructOffset), 4700 MachineMemOperand::MODereferenceable | 4701 MachineMemOperand::MOInvariant); 4702 } 4703 4704 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4705 SelectionDAG &DAG) const { 4706 SDLoc SL(Op); 4707 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4708 4709 SDValue Src = ASC->getOperand(0); 4710 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4711 4712 const AMDGPUTargetMachine &TM = 4713 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4714 4715 // flat -> local/private 4716 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4717 unsigned DestAS = ASC->getDestAddressSpace(); 4718 4719 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4720 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4721 unsigned NullVal = TM.getNullPointerValue(DestAS); 4722 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4723 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4724 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4725 4726 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4727 NonNull, Ptr, SegmentNullPtr); 4728 } 4729 } 4730 4731 // local/private -> flat 4732 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4733 unsigned SrcAS = ASC->getSrcAddressSpace(); 4734 4735 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4736 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4737 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4738 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4739 4740 SDValue NonNull 4741 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4742 4743 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4744 SDValue CvtPtr 4745 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4746 4747 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4748 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4749 FlatNullPtr); 4750 } 4751 } 4752 4753 // global <-> flat are no-ops and never emitted. 4754 4755 const MachineFunction &MF = DAG.getMachineFunction(); 4756 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4757 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4758 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4759 4760 return DAG.getUNDEF(ASC->getValueType(0)); 4761 } 4762 4763 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4764 // the small vector and inserting them into the big vector. That is better than 4765 // the default expansion of doing it via a stack slot. Even though the use of 4766 // the stack slot would be optimized away afterwards, the stack slot itself 4767 // remains. 4768 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4769 SelectionDAG &DAG) const { 4770 SDValue Vec = Op.getOperand(0); 4771 SDValue Ins = Op.getOperand(1); 4772 SDValue Idx = Op.getOperand(2); 4773 EVT VecVT = Vec.getValueType(); 4774 EVT InsVT = Ins.getValueType(); 4775 EVT EltVT = VecVT.getVectorElementType(); 4776 unsigned InsNumElts = InsVT.getVectorNumElements(); 4777 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4778 SDLoc SL(Op); 4779 4780 for (unsigned I = 0; I != InsNumElts; ++I) { 4781 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4782 DAG.getConstant(I, SL, MVT::i32)); 4783 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4784 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4785 } 4786 return Vec; 4787 } 4788 4789 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4790 SelectionDAG &DAG) const { 4791 SDValue Vec = Op.getOperand(0); 4792 SDValue InsVal = Op.getOperand(1); 4793 SDValue Idx = Op.getOperand(2); 4794 EVT VecVT = Vec.getValueType(); 4795 EVT EltVT = VecVT.getVectorElementType(); 4796 unsigned VecSize = VecVT.getSizeInBits(); 4797 unsigned EltSize = EltVT.getSizeInBits(); 4798 4799 4800 assert(VecSize <= 64); 4801 4802 unsigned NumElts = VecVT.getVectorNumElements(); 4803 SDLoc SL(Op); 4804 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4805 4806 if (NumElts == 4 && EltSize == 16 && KIdx) { 4807 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4808 4809 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4810 DAG.getConstant(0, SL, MVT::i32)); 4811 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4812 DAG.getConstant(1, SL, MVT::i32)); 4813 4814 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4815 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4816 4817 unsigned Idx = KIdx->getZExtValue(); 4818 bool InsertLo = Idx < 2; 4819 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4820 InsertLo ? LoVec : HiVec, 4821 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4822 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4823 4824 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4825 4826 SDValue Concat = InsertLo ? 4827 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4828 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4829 4830 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4831 } 4832 4833 if (isa<ConstantSDNode>(Idx)) 4834 return SDValue(); 4835 4836 MVT IntVT = MVT::getIntegerVT(VecSize); 4837 4838 // Avoid stack access for dynamic indexing. 4839 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4840 4841 // Create a congruent vector with the target value in each element so that 4842 // the required element can be masked and ORed into the target vector. 4843 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4844 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4845 4846 assert(isPowerOf2_32(EltSize)); 4847 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4848 4849 // Convert vector index to bit-index. 4850 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4851 4852 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4853 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4854 DAG.getConstant(0xffff, SL, IntVT), 4855 ScaledIdx); 4856 4857 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4858 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4859 DAG.getNOT(SL, BFM, IntVT), BCVec); 4860 4861 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4862 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4863 } 4864 4865 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4866 SelectionDAG &DAG) const { 4867 SDLoc SL(Op); 4868 4869 EVT ResultVT = Op.getValueType(); 4870 SDValue Vec = Op.getOperand(0); 4871 SDValue Idx = Op.getOperand(1); 4872 EVT VecVT = Vec.getValueType(); 4873 unsigned VecSize = VecVT.getSizeInBits(); 4874 EVT EltVT = VecVT.getVectorElementType(); 4875 assert(VecSize <= 64); 4876 4877 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4878 4879 // Make sure we do any optimizations that will make it easier to fold 4880 // source modifiers before obscuring it with bit operations. 4881 4882 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4883 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4884 return Combined; 4885 4886 unsigned EltSize = EltVT.getSizeInBits(); 4887 assert(isPowerOf2_32(EltSize)); 4888 4889 MVT IntVT = MVT::getIntegerVT(VecSize); 4890 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4891 4892 // Convert vector index to bit-index (* EltSize) 4893 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4894 4895 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4896 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4897 4898 if (ResultVT == MVT::f16) { 4899 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4900 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4901 } 4902 4903 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4904 } 4905 4906 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4907 assert(Elt % 2 == 0); 4908 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4909 } 4910 4911 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4912 SelectionDAG &DAG) const { 4913 SDLoc SL(Op); 4914 EVT ResultVT = Op.getValueType(); 4915 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4916 4917 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4918 EVT EltVT = PackVT.getVectorElementType(); 4919 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4920 4921 // vector_shuffle <0,1,6,7> lhs, rhs 4922 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4923 // 4924 // vector_shuffle <6,7,2,3> lhs, rhs 4925 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4926 // 4927 // vector_shuffle <6,7,0,1> lhs, rhs 4928 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4929 4930 // Avoid scalarizing when both halves are reading from consecutive elements. 4931 SmallVector<SDValue, 4> Pieces; 4932 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4933 if (elementPairIsContiguous(SVN->getMask(), I)) { 4934 const int Idx = SVN->getMaskElt(I); 4935 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4936 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4937 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4938 PackVT, SVN->getOperand(VecIdx), 4939 DAG.getConstant(EltIdx, SL, MVT::i32)); 4940 Pieces.push_back(SubVec); 4941 } else { 4942 const int Idx0 = SVN->getMaskElt(I); 4943 const int Idx1 = SVN->getMaskElt(I + 1); 4944 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4945 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4946 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4947 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4948 4949 SDValue Vec0 = SVN->getOperand(VecIdx0); 4950 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4951 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4952 4953 SDValue Vec1 = SVN->getOperand(VecIdx1); 4954 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4955 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4956 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4957 } 4958 } 4959 4960 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4961 } 4962 4963 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4964 SelectionDAG &DAG) const { 4965 SDLoc SL(Op); 4966 EVT VT = Op.getValueType(); 4967 4968 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4969 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4970 4971 // Turn into pair of packed build_vectors. 4972 // TODO: Special case for constants that can be materialized with s_mov_b64. 4973 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4974 { Op.getOperand(0), Op.getOperand(1) }); 4975 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4976 { Op.getOperand(2), Op.getOperand(3) }); 4977 4978 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4979 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4980 4981 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4982 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4983 } 4984 4985 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4986 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4987 4988 SDValue Lo = Op.getOperand(0); 4989 SDValue Hi = Op.getOperand(1); 4990 4991 // Avoid adding defined bits with the zero_extend. 4992 if (Hi.isUndef()) { 4993 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4994 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4995 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4996 } 4997 4998 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4999 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5000 5001 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5002 DAG.getConstant(16, SL, MVT::i32)); 5003 if (Lo.isUndef()) 5004 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5005 5006 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5007 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5008 5009 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5010 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5011 } 5012 5013 bool 5014 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5015 // We can fold offsets for anything that doesn't require a GOT relocation. 5016 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5017 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5018 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5019 !shouldEmitGOTReloc(GA->getGlobal()); 5020 } 5021 5022 static SDValue 5023 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5024 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5025 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5026 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5027 // lowered to the following code sequence: 5028 // 5029 // For constant address space: 5030 // s_getpc_b64 s[0:1] 5031 // s_add_u32 s0, s0, $symbol 5032 // s_addc_u32 s1, s1, 0 5033 // 5034 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5035 // a fixup or relocation is emitted to replace $symbol with a literal 5036 // constant, which is a pc-relative offset from the encoding of the $symbol 5037 // operand to the global variable. 5038 // 5039 // For global address space: 5040 // s_getpc_b64 s[0:1] 5041 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5042 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5043 // 5044 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5045 // fixups or relocations are emitted to replace $symbol@*@lo and 5046 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5047 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5048 // operand to the global variable. 5049 // 5050 // What we want here is an offset from the value returned by s_getpc 5051 // (which is the address of the s_add_u32 instruction) to the global 5052 // variable, but since the encoding of $symbol starts 4 bytes after the start 5053 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5054 // small. This requires us to add 4 to the global variable offset in order to 5055 // compute the correct address. 5056 SDValue PtrLo = 5057 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5058 SDValue PtrHi; 5059 if (GAFlags == SIInstrInfo::MO_NONE) { 5060 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5061 } else { 5062 PtrHi = 5063 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5064 } 5065 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5066 } 5067 5068 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5069 SDValue Op, 5070 SelectionDAG &DAG) const { 5071 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5072 const GlobalValue *GV = GSD->getGlobal(); 5073 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5074 (!GV->hasExternalLinkage() || 5075 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 5076 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 5077 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5078 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5079 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5080 5081 SDLoc DL(GSD); 5082 EVT PtrVT = Op.getValueType(); 5083 5084 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5085 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5086 SIInstrInfo::MO_ABS32_LO); 5087 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5088 } 5089 5090 if (shouldEmitFixup(GV)) 5091 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5092 else if (shouldEmitPCReloc(GV)) 5093 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5094 SIInstrInfo::MO_REL32); 5095 5096 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5097 SIInstrInfo::MO_GOTPCREL32); 5098 5099 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5100 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5101 const DataLayout &DataLayout = DAG.getDataLayout(); 5102 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5103 MachinePointerInfo PtrInfo 5104 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5105 5106 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5107 MachineMemOperand::MODereferenceable | 5108 MachineMemOperand::MOInvariant); 5109 } 5110 5111 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5112 const SDLoc &DL, SDValue V) const { 5113 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5114 // the destination register. 5115 // 5116 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5117 // so we will end up with redundant moves to m0. 5118 // 5119 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5120 5121 // A Null SDValue creates a glue result. 5122 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5123 V, Chain); 5124 return SDValue(M0, 0); 5125 } 5126 5127 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5128 SDValue Op, 5129 MVT VT, 5130 unsigned Offset) const { 5131 SDLoc SL(Op); 5132 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5133 DAG.getEntryNode(), Offset, 4, false); 5134 // The local size values will have the hi 16-bits as zero. 5135 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5136 DAG.getValueType(VT)); 5137 } 5138 5139 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5140 EVT VT) { 5141 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5142 "non-hsa intrinsic with hsa target", 5143 DL.getDebugLoc()); 5144 DAG.getContext()->diagnose(BadIntrin); 5145 return DAG.getUNDEF(VT); 5146 } 5147 5148 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5149 EVT VT) { 5150 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5151 "intrinsic not supported on subtarget", 5152 DL.getDebugLoc()); 5153 DAG.getContext()->diagnose(BadIntrin); 5154 return DAG.getUNDEF(VT); 5155 } 5156 5157 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5158 ArrayRef<SDValue> Elts) { 5159 assert(!Elts.empty()); 5160 MVT Type; 5161 unsigned NumElts; 5162 5163 if (Elts.size() == 1) { 5164 Type = MVT::f32; 5165 NumElts = 1; 5166 } else if (Elts.size() == 2) { 5167 Type = MVT::v2f32; 5168 NumElts = 2; 5169 } else if (Elts.size() <= 4) { 5170 Type = MVT::v4f32; 5171 NumElts = 4; 5172 } else if (Elts.size() <= 8) { 5173 Type = MVT::v8f32; 5174 NumElts = 8; 5175 } else { 5176 assert(Elts.size() <= 16); 5177 Type = MVT::v16f32; 5178 NumElts = 16; 5179 } 5180 5181 SmallVector<SDValue, 16> VecElts(NumElts); 5182 for (unsigned i = 0; i < Elts.size(); ++i) { 5183 SDValue Elt = Elts[i]; 5184 if (Elt.getValueType() != MVT::f32) 5185 Elt = DAG.getBitcast(MVT::f32, Elt); 5186 VecElts[i] = Elt; 5187 } 5188 for (unsigned i = Elts.size(); i < NumElts; ++i) 5189 VecElts[i] = DAG.getUNDEF(MVT::f32); 5190 5191 if (NumElts == 1) 5192 return VecElts[0]; 5193 return DAG.getBuildVector(Type, DL, VecElts); 5194 } 5195 5196 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5197 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5198 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5199 5200 uint64_t Value = CachePolicyConst->getZExtValue(); 5201 SDLoc DL(CachePolicy); 5202 if (GLC) { 5203 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5204 Value &= ~(uint64_t)0x1; 5205 } 5206 if (SLC) { 5207 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5208 Value &= ~(uint64_t)0x2; 5209 } 5210 if (DLC) { 5211 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5212 Value &= ~(uint64_t)0x4; 5213 } 5214 5215 return Value == 0; 5216 } 5217 5218 // Re-construct the required return value for a image load intrinsic. 5219 // This is more complicated due to the optional use TexFailCtrl which means the required 5220 // return type is an aggregate 5221 static SDValue constructRetValue(SelectionDAG &DAG, 5222 MachineSDNode *Result, 5223 ArrayRef<EVT> ResultTypes, 5224 bool IsTexFail, bool Unpacked, bool IsD16, 5225 int DMaskPop, int NumVDataDwords, 5226 const SDLoc &DL, LLVMContext &Context) { 5227 // Determine the required return type. This is the same regardless of IsTexFail flag 5228 EVT ReqRetVT = ResultTypes[0]; 5229 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5230 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5231 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5232 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5233 : AdjEltVT 5234 : ReqRetVT; 5235 5236 // Extract data part of the result 5237 // Bitcast the result to the same type as the required return type 5238 int NumElts; 5239 if (IsD16 && !Unpacked) 5240 NumElts = NumVDataDwords << 1; 5241 else 5242 NumElts = NumVDataDwords; 5243 5244 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5245 : AdjEltVT; 5246 5247 // Special case for v6f16. Rather than add support for this, use v3i32 to 5248 // extract the data elements 5249 bool V6F16Special = false; 5250 if (NumElts == 6) { 5251 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5252 DMaskPop >>= 1; 5253 ReqRetNumElts >>= 1; 5254 V6F16Special = true; 5255 AdjVT = MVT::v2i32; 5256 } 5257 5258 SDValue N = SDValue(Result, 0); 5259 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5260 5261 // Iterate over the result 5262 SmallVector<SDValue, 4> BVElts; 5263 5264 if (CastVT.isVector()) { 5265 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5266 } else { 5267 BVElts.push_back(CastRes); 5268 } 5269 int ExtraElts = ReqRetNumElts - DMaskPop; 5270 while(ExtraElts--) 5271 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5272 5273 SDValue PreTFCRes; 5274 if (ReqRetNumElts > 1) { 5275 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5276 if (IsD16 && Unpacked) 5277 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5278 else 5279 PreTFCRes = NewVec; 5280 } else { 5281 PreTFCRes = BVElts[0]; 5282 } 5283 5284 if (V6F16Special) 5285 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5286 5287 if (!IsTexFail) { 5288 if (Result->getNumValues() > 1) 5289 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5290 else 5291 return PreTFCRes; 5292 } 5293 5294 // Extract the TexFail result and insert into aggregate return 5295 SmallVector<SDValue, 1> TFCElt; 5296 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5297 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5298 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5299 } 5300 5301 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5302 SDValue *LWE, bool &IsTexFail) { 5303 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5304 5305 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5306 if (Value) { 5307 IsTexFail = true; 5308 } 5309 5310 SDLoc DL(TexFailCtrlConst); 5311 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5312 Value &= ~(uint64_t)0x1; 5313 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5314 Value &= ~(uint64_t)0x2; 5315 5316 return Value == 0; 5317 } 5318 5319 SDValue SITargetLowering::lowerImage(SDValue Op, 5320 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5321 SelectionDAG &DAG) const { 5322 SDLoc DL(Op); 5323 MachineFunction &MF = DAG.getMachineFunction(); 5324 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5325 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5326 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5327 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5328 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5329 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5330 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5331 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5332 unsigned IntrOpcode = Intr->BaseOpcode; 5333 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5334 5335 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5336 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5337 bool IsD16 = false; 5338 bool IsA16 = false; 5339 SDValue VData; 5340 int NumVDataDwords; 5341 bool AdjustRetType = false; 5342 5343 unsigned AddrIdx; // Index of first address argument 5344 unsigned DMask; 5345 unsigned DMaskLanes = 0; 5346 5347 if (BaseOpcode->Atomic) { 5348 VData = Op.getOperand(2); 5349 5350 bool Is64Bit = VData.getValueType() == MVT::i64; 5351 if (BaseOpcode->AtomicX2) { 5352 SDValue VData2 = Op.getOperand(3); 5353 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5354 {VData, VData2}); 5355 if (Is64Bit) 5356 VData = DAG.getBitcast(MVT::v4i32, VData); 5357 5358 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5359 DMask = Is64Bit ? 0xf : 0x3; 5360 NumVDataDwords = Is64Bit ? 4 : 2; 5361 AddrIdx = 4; 5362 } else { 5363 DMask = Is64Bit ? 0x3 : 0x1; 5364 NumVDataDwords = Is64Bit ? 2 : 1; 5365 AddrIdx = 3; 5366 } 5367 } else { 5368 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5369 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5370 DMask = DMaskConst->getZExtValue(); 5371 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5372 5373 if (BaseOpcode->Store) { 5374 VData = Op.getOperand(2); 5375 5376 MVT StoreVT = VData.getSimpleValueType(); 5377 if (StoreVT.getScalarType() == MVT::f16) { 5378 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5379 return Op; // D16 is unsupported for this instruction 5380 5381 IsD16 = true; 5382 VData = handleD16VData(VData, DAG); 5383 } 5384 5385 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5386 } else { 5387 // Work out the num dwords based on the dmask popcount and underlying type 5388 // and whether packing is supported. 5389 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5390 if (LoadVT.getScalarType() == MVT::f16) { 5391 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5392 return Op; // D16 is unsupported for this instruction 5393 5394 IsD16 = true; 5395 } 5396 5397 // Confirm that the return type is large enough for the dmask specified 5398 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5399 (!LoadVT.isVector() && DMaskLanes > 1)) 5400 return Op; 5401 5402 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5403 NumVDataDwords = (DMaskLanes + 1) / 2; 5404 else 5405 NumVDataDwords = DMaskLanes; 5406 5407 AdjustRetType = true; 5408 } 5409 5410 AddrIdx = DMaskIdx + 1; 5411 } 5412 5413 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5414 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5415 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5416 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5417 NumCoords + NumLCM; 5418 unsigned NumMIVAddrs = NumVAddrs; 5419 5420 SmallVector<SDValue, 4> VAddrs; 5421 5422 // Optimize _L to _LZ when _L is zero 5423 if (LZMappingInfo) { 5424 if (auto ConstantLod = 5425 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5426 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5427 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5428 NumMIVAddrs--; // remove 'lod' 5429 } 5430 } 5431 } 5432 5433 // Optimize _mip away, when 'lod' is zero 5434 if (MIPMappingInfo) { 5435 if (auto ConstantLod = 5436 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5437 if (ConstantLod->isNullValue()) { 5438 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5439 NumMIVAddrs--; // remove 'lod' 5440 } 5441 } 5442 } 5443 5444 // Check for 16 bit addresses and pack if true. 5445 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5446 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5447 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5448 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5449 // Illegal to use a16 images 5450 if (!ST->hasFeature(AMDGPU::FeatureR128A16)) 5451 return Op; 5452 5453 IsA16 = true; 5454 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5455 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5456 SDValue AddrLo, AddrHi; 5457 // Push back extra arguments. 5458 if (i < DimIdx) { 5459 AddrLo = Op.getOperand(i); 5460 } else { 5461 AddrLo = Op.getOperand(i); 5462 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5463 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5464 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5465 ((NumGradients / 2) % 2 == 1 && 5466 (i == DimIdx + (NumGradients / 2) - 1 || 5467 i == DimIdx + NumGradients - 1))) { 5468 AddrHi = DAG.getUNDEF(MVT::f16); 5469 } else { 5470 AddrHi = Op.getOperand(i + 1); 5471 i++; 5472 } 5473 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5474 {AddrLo, AddrHi}); 5475 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5476 } 5477 VAddrs.push_back(AddrLo); 5478 } 5479 } else { 5480 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5481 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5482 } 5483 5484 // If the register allocator cannot place the address registers contiguously 5485 // without introducing moves, then using the non-sequential address encoding 5486 // is always preferable, since it saves VALU instructions and is usually a 5487 // wash in terms of code size or even better. 5488 // 5489 // However, we currently have no way of hinting to the register allocator that 5490 // MIMG addresses should be placed contiguously when it is possible to do so, 5491 // so force non-NSA for the common 2-address case as a heuristic. 5492 // 5493 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5494 // allocation when possible. 5495 bool UseNSA = 5496 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5497 SDValue VAddr; 5498 if (!UseNSA) 5499 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5500 5501 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5502 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5503 unsigned CtrlIdx; // Index of texfailctrl argument 5504 SDValue Unorm; 5505 if (!BaseOpcode->Sampler) { 5506 Unorm = True; 5507 CtrlIdx = AddrIdx + NumVAddrs + 1; 5508 } else { 5509 auto UnormConst = 5510 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5511 5512 Unorm = UnormConst->getZExtValue() ? True : False; 5513 CtrlIdx = AddrIdx + NumVAddrs + 3; 5514 } 5515 5516 SDValue TFE; 5517 SDValue LWE; 5518 SDValue TexFail = Op.getOperand(CtrlIdx); 5519 bool IsTexFail = false; 5520 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5521 return Op; 5522 5523 if (IsTexFail) { 5524 if (!DMaskLanes) { 5525 // Expecting to get an error flag since TFC is on - and dmask is 0 5526 // Force dmask to be at least 1 otherwise the instruction will fail 5527 DMask = 0x1; 5528 DMaskLanes = 1; 5529 NumVDataDwords = 1; 5530 } 5531 NumVDataDwords += 1; 5532 AdjustRetType = true; 5533 } 5534 5535 // Has something earlier tagged that the return type needs adjusting 5536 // This happens if the instruction is a load or has set TexFailCtrl flags 5537 if (AdjustRetType) { 5538 // NumVDataDwords reflects the true number of dwords required in the return type 5539 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5540 // This is a no-op load. This can be eliminated 5541 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5542 if (isa<MemSDNode>(Op)) 5543 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5544 return Undef; 5545 } 5546 5547 EVT NewVT = NumVDataDwords > 1 ? 5548 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5549 : MVT::f32; 5550 5551 ResultTypes[0] = NewVT; 5552 if (ResultTypes.size() == 3) { 5553 // Original result was aggregate type used for TexFailCtrl results 5554 // The actual instruction returns as a vector type which has now been 5555 // created. Remove the aggregate result. 5556 ResultTypes.erase(&ResultTypes[1]); 5557 } 5558 } 5559 5560 SDValue GLC; 5561 SDValue SLC; 5562 SDValue DLC; 5563 if (BaseOpcode->Atomic) { 5564 GLC = True; // TODO no-return optimization 5565 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5566 IsGFX10 ? &DLC : nullptr)) 5567 return Op; 5568 } else { 5569 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5570 IsGFX10 ? &DLC : nullptr)) 5571 return Op; 5572 } 5573 5574 SmallVector<SDValue, 26> Ops; 5575 if (BaseOpcode->Store || BaseOpcode->Atomic) 5576 Ops.push_back(VData); // vdata 5577 if (UseNSA) { 5578 for (const SDValue &Addr : VAddrs) 5579 Ops.push_back(Addr); 5580 } else { 5581 Ops.push_back(VAddr); 5582 } 5583 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5584 if (BaseOpcode->Sampler) 5585 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5586 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5587 if (IsGFX10) 5588 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5589 Ops.push_back(Unorm); 5590 if (IsGFX10) 5591 Ops.push_back(DLC); 5592 Ops.push_back(GLC); 5593 Ops.push_back(SLC); 5594 Ops.push_back(IsA16 && // a16 or r128 5595 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5596 Ops.push_back(TFE); // tfe 5597 Ops.push_back(LWE); // lwe 5598 if (!IsGFX10) 5599 Ops.push_back(DimInfo->DA ? True : False); 5600 if (BaseOpcode->HasD16) 5601 Ops.push_back(IsD16 ? True : False); 5602 if (isa<MemSDNode>(Op)) 5603 Ops.push_back(Op.getOperand(0)); // chain 5604 5605 int NumVAddrDwords = 5606 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5607 int Opcode = -1; 5608 5609 if (IsGFX10) { 5610 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5611 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5612 : AMDGPU::MIMGEncGfx10Default, 5613 NumVDataDwords, NumVAddrDwords); 5614 } else { 5615 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5616 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5617 NumVDataDwords, NumVAddrDwords); 5618 if (Opcode == -1) 5619 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5620 NumVDataDwords, NumVAddrDwords); 5621 } 5622 assert(Opcode != -1); 5623 5624 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5625 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5626 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5627 DAG.setNodeMemRefs(NewNode, {MemRef}); 5628 } 5629 5630 if (BaseOpcode->AtomicX2) { 5631 SmallVector<SDValue, 1> Elt; 5632 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5633 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5634 } else if (!BaseOpcode->Store) { 5635 return constructRetValue(DAG, NewNode, 5636 OrigResultTypes, IsTexFail, 5637 Subtarget->hasUnpackedD16VMem(), IsD16, 5638 DMaskLanes, NumVDataDwords, DL, 5639 *DAG.getContext()); 5640 } 5641 5642 return SDValue(NewNode, 0); 5643 } 5644 5645 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5646 SDValue Offset, SDValue GLC, SDValue DLC, 5647 SelectionDAG &DAG) const { 5648 MachineFunction &MF = DAG.getMachineFunction(); 5649 5650 const DataLayout &DataLayout = DAG.getDataLayout(); 5651 unsigned Align = 5652 DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5653 5654 MachineMemOperand *MMO = MF.getMachineMemOperand( 5655 MachinePointerInfo(), 5656 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5657 MachineMemOperand::MOInvariant, 5658 VT.getStoreSize(), Align); 5659 5660 if (!Offset->isDivergent()) { 5661 SDValue Ops[] = { 5662 Rsrc, 5663 Offset, // Offset 5664 GLC, 5665 DLC, 5666 }; 5667 5668 // Widen vec3 load to vec4. 5669 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5670 EVT WidenedVT = 5671 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5672 auto WidenedOp = DAG.getMemIntrinsicNode( 5673 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5674 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5675 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5676 DAG.getVectorIdxConstant(0, DL)); 5677 return Subvector; 5678 } 5679 5680 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5681 DAG.getVTList(VT), Ops, VT, MMO); 5682 } 5683 5684 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5685 // assume that the buffer is unswizzled. 5686 SmallVector<SDValue, 4> Loads; 5687 unsigned NumLoads = 1; 5688 MVT LoadVT = VT.getSimpleVT(); 5689 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5690 assert((LoadVT.getScalarType() == MVT::i32 || 5691 LoadVT.getScalarType() == MVT::f32)); 5692 5693 if (NumElts == 8 || NumElts == 16) { 5694 NumLoads = NumElts / 4; 5695 LoadVT = MVT::v4i32; 5696 } 5697 5698 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5699 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5700 SDValue Ops[] = { 5701 DAG.getEntryNode(), // Chain 5702 Rsrc, // rsrc 5703 DAG.getConstant(0, DL, MVT::i32), // vindex 5704 {}, // voffset 5705 {}, // soffset 5706 {}, // offset 5707 DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5708 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5709 }; 5710 5711 // Use the alignment to ensure that the required offsets will fit into the 5712 // immediate offsets. 5713 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5714 5715 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5716 for (unsigned i = 0; i < NumLoads; ++i) { 5717 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5718 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5719 LoadVT, MMO, DAG)); 5720 } 5721 5722 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5723 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5724 5725 return Loads[0]; 5726 } 5727 5728 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5729 SelectionDAG &DAG) const { 5730 MachineFunction &MF = DAG.getMachineFunction(); 5731 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5732 5733 EVT VT = Op.getValueType(); 5734 SDLoc DL(Op); 5735 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5736 5737 // TODO: Should this propagate fast-math-flags? 5738 5739 switch (IntrinsicID) { 5740 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5741 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5742 return emitNonHSAIntrinsicError(DAG, DL, VT); 5743 return getPreloadedValue(DAG, *MFI, VT, 5744 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5745 } 5746 case Intrinsic::amdgcn_dispatch_ptr: 5747 case Intrinsic::amdgcn_queue_ptr: { 5748 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5749 DiagnosticInfoUnsupported BadIntrin( 5750 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5751 DL.getDebugLoc()); 5752 DAG.getContext()->diagnose(BadIntrin); 5753 return DAG.getUNDEF(VT); 5754 } 5755 5756 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5757 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5758 return getPreloadedValue(DAG, *MFI, VT, RegID); 5759 } 5760 case Intrinsic::amdgcn_implicitarg_ptr: { 5761 if (MFI->isEntryFunction()) 5762 return getImplicitArgPtr(DAG, DL); 5763 return getPreloadedValue(DAG, *MFI, VT, 5764 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5765 } 5766 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5767 return getPreloadedValue(DAG, *MFI, VT, 5768 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5769 } 5770 case Intrinsic::amdgcn_dispatch_id: { 5771 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5772 } 5773 case Intrinsic::amdgcn_rcp: 5774 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5775 case Intrinsic::amdgcn_rsq: 5776 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5777 case Intrinsic::amdgcn_rsq_legacy: 5778 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5779 return emitRemovedIntrinsicError(DAG, DL, VT); 5780 5781 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5782 case Intrinsic::amdgcn_rcp_legacy: 5783 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5784 return emitRemovedIntrinsicError(DAG, DL, VT); 5785 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5786 case Intrinsic::amdgcn_rsq_clamp: { 5787 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5788 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5789 5790 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5791 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5792 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5793 5794 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5795 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5796 DAG.getConstantFP(Max, DL, VT)); 5797 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5798 DAG.getConstantFP(Min, DL, VT)); 5799 } 5800 case Intrinsic::r600_read_ngroups_x: 5801 if (Subtarget->isAmdHsaOS()) 5802 return emitNonHSAIntrinsicError(DAG, DL, VT); 5803 5804 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5805 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5806 case Intrinsic::r600_read_ngroups_y: 5807 if (Subtarget->isAmdHsaOS()) 5808 return emitNonHSAIntrinsicError(DAG, DL, VT); 5809 5810 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5811 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5812 case Intrinsic::r600_read_ngroups_z: 5813 if (Subtarget->isAmdHsaOS()) 5814 return emitNonHSAIntrinsicError(DAG, DL, VT); 5815 5816 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5817 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5818 case Intrinsic::r600_read_global_size_x: 5819 if (Subtarget->isAmdHsaOS()) 5820 return emitNonHSAIntrinsicError(DAG, DL, VT); 5821 5822 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5823 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5824 case Intrinsic::r600_read_global_size_y: 5825 if (Subtarget->isAmdHsaOS()) 5826 return emitNonHSAIntrinsicError(DAG, DL, VT); 5827 5828 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5829 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5830 case Intrinsic::r600_read_global_size_z: 5831 if (Subtarget->isAmdHsaOS()) 5832 return emitNonHSAIntrinsicError(DAG, DL, VT); 5833 5834 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5835 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5836 case Intrinsic::r600_read_local_size_x: 5837 if (Subtarget->isAmdHsaOS()) 5838 return emitNonHSAIntrinsicError(DAG, DL, VT); 5839 5840 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5841 SI::KernelInputOffsets::LOCAL_SIZE_X); 5842 case Intrinsic::r600_read_local_size_y: 5843 if (Subtarget->isAmdHsaOS()) 5844 return emitNonHSAIntrinsicError(DAG, DL, VT); 5845 5846 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5847 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5848 case Intrinsic::r600_read_local_size_z: 5849 if (Subtarget->isAmdHsaOS()) 5850 return emitNonHSAIntrinsicError(DAG, DL, VT); 5851 5852 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5853 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5854 case Intrinsic::amdgcn_workgroup_id_x: 5855 case Intrinsic::r600_read_tgid_x: 5856 return getPreloadedValue(DAG, *MFI, VT, 5857 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5858 case Intrinsic::amdgcn_workgroup_id_y: 5859 case Intrinsic::r600_read_tgid_y: 5860 return getPreloadedValue(DAG, *MFI, VT, 5861 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5862 case Intrinsic::amdgcn_workgroup_id_z: 5863 case Intrinsic::r600_read_tgid_z: 5864 return getPreloadedValue(DAG, *MFI, VT, 5865 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5866 case Intrinsic::amdgcn_workitem_id_x: 5867 case Intrinsic::r600_read_tidig_x: 5868 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5869 SDLoc(DAG.getEntryNode()), 5870 MFI->getArgInfo().WorkItemIDX); 5871 case Intrinsic::amdgcn_workitem_id_y: 5872 case Intrinsic::r600_read_tidig_y: 5873 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5874 SDLoc(DAG.getEntryNode()), 5875 MFI->getArgInfo().WorkItemIDY); 5876 case Intrinsic::amdgcn_workitem_id_z: 5877 case Intrinsic::r600_read_tidig_z: 5878 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5879 SDLoc(DAG.getEntryNode()), 5880 MFI->getArgInfo().WorkItemIDZ); 5881 case Intrinsic::amdgcn_wavefrontsize: 5882 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5883 SDLoc(Op), MVT::i32); 5884 case Intrinsic::amdgcn_s_buffer_load: { 5885 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5886 SDValue GLC; 5887 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5888 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5889 IsGFX10 ? &DLC : nullptr)) 5890 return Op; 5891 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5892 DAG); 5893 } 5894 case Intrinsic::amdgcn_fdiv_fast: 5895 return lowerFDIV_FAST(Op, DAG); 5896 case Intrinsic::amdgcn_interp_p1_f16: { 5897 if (getSubtarget()->getLDSBankCount() == 16) { 5898 // 16 bank LDS 5899 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0, 5900 Op.getOperand(5), SDValue()); 5901 5902 // FIXME: This implicitly will insert a second CopyToReg to M0. 5903 SDValue S = DAG.getNode( 5904 ISD::INTRINSIC_WO_CHAIN, DL, MVT::f32, 5905 DAG.getTargetConstant(Intrinsic::amdgcn_interp_mov, DL, MVT::i32), 5906 DAG.getConstant(2, DL, MVT::i32), // P0 5907 Op.getOperand(2), // Attrchan 5908 Op.getOperand(3), // Attr 5909 Op.getOperand(5)); // m0 5910 5911 SDValue Ops[] = { 5912 Op.getOperand(1), // Src0 5913 Op.getOperand(2), // Attrchan 5914 Op.getOperand(3), // Attr 5915 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5916 S, // Src2 - holds two f16 values selected by high 5917 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5918 Op.getOperand(4), // high 5919 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5920 DAG.getTargetConstant(0, DL, MVT::i32), // $omod 5921 ToM0.getValue(1) 5922 }; 5923 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5924 } 5925 5926 return SDValue(); 5927 } 5928 case Intrinsic::amdgcn_sin: 5929 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5930 5931 case Intrinsic::amdgcn_cos: 5932 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5933 5934 case Intrinsic::amdgcn_mul_u24: 5935 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5936 case Intrinsic::amdgcn_mul_i24: 5937 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5938 5939 case Intrinsic::amdgcn_log_clamp: { 5940 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5941 return SDValue(); 5942 5943 DiagnosticInfoUnsupported BadIntrin( 5944 MF.getFunction(), "intrinsic not supported on subtarget", 5945 DL.getDebugLoc()); 5946 DAG.getContext()->diagnose(BadIntrin); 5947 return DAG.getUNDEF(VT); 5948 } 5949 case Intrinsic::amdgcn_ldexp: 5950 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5951 Op.getOperand(1), Op.getOperand(2)); 5952 5953 case Intrinsic::amdgcn_fract: 5954 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5955 5956 case Intrinsic::amdgcn_class: 5957 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5958 Op.getOperand(1), Op.getOperand(2)); 5959 case Intrinsic::amdgcn_div_fmas: 5960 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5961 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5962 Op.getOperand(4)); 5963 5964 case Intrinsic::amdgcn_div_fixup: 5965 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5966 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5967 5968 case Intrinsic::amdgcn_trig_preop: 5969 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5970 Op.getOperand(1), Op.getOperand(2)); 5971 case Intrinsic::amdgcn_div_scale: { 5972 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5973 5974 // Translate to the operands expected by the machine instruction. The 5975 // first parameter must be the same as the first instruction. 5976 SDValue Numerator = Op.getOperand(1); 5977 SDValue Denominator = Op.getOperand(2); 5978 5979 // Note this order is opposite of the machine instruction's operations, 5980 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5981 // intrinsic has the numerator as the first operand to match a normal 5982 // division operation. 5983 5984 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5985 5986 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5987 Denominator, Numerator); 5988 } 5989 case Intrinsic::amdgcn_icmp: { 5990 // There is a Pat that handles this variant, so return it as-is. 5991 if (Op.getOperand(1).getValueType() == MVT::i1 && 5992 Op.getConstantOperandVal(2) == 0 && 5993 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5994 return Op; 5995 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5996 } 5997 case Intrinsic::amdgcn_fcmp: { 5998 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5999 } 6000 case Intrinsic::amdgcn_fmed3: 6001 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6002 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6003 case Intrinsic::amdgcn_fdot2: 6004 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6005 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6006 Op.getOperand(4)); 6007 case Intrinsic::amdgcn_fmul_legacy: 6008 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6009 Op.getOperand(1), Op.getOperand(2)); 6010 case Intrinsic::amdgcn_sffbh: 6011 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6012 case Intrinsic::amdgcn_sbfe: 6013 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6014 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6015 case Intrinsic::amdgcn_ubfe: 6016 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6017 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6018 case Intrinsic::amdgcn_cvt_pkrtz: 6019 case Intrinsic::amdgcn_cvt_pknorm_i16: 6020 case Intrinsic::amdgcn_cvt_pknorm_u16: 6021 case Intrinsic::amdgcn_cvt_pk_i16: 6022 case Intrinsic::amdgcn_cvt_pk_u16: { 6023 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6024 EVT VT = Op.getValueType(); 6025 unsigned Opcode; 6026 6027 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6028 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6029 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6030 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6031 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6032 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6033 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6034 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6035 else 6036 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6037 6038 if (isTypeLegal(VT)) 6039 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6040 6041 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6042 Op.getOperand(1), Op.getOperand(2)); 6043 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6044 } 6045 case Intrinsic::amdgcn_fmad_ftz: 6046 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6047 Op.getOperand(2), Op.getOperand(3)); 6048 6049 case Intrinsic::amdgcn_if_break: 6050 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6051 Op->getOperand(1), Op->getOperand(2)), 0); 6052 6053 case Intrinsic::amdgcn_groupstaticsize: { 6054 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6055 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6056 return Op; 6057 6058 const Module *M = MF.getFunction().getParent(); 6059 const GlobalValue *GV = 6060 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6061 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6062 SIInstrInfo::MO_ABS32_LO); 6063 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6064 } 6065 case Intrinsic::amdgcn_is_shared: 6066 case Intrinsic::amdgcn_is_private: { 6067 SDLoc SL(Op); 6068 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6069 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6070 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6071 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6072 Op.getOperand(1)); 6073 6074 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6075 DAG.getConstant(1, SL, MVT::i32)); 6076 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6077 } 6078 default: 6079 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6080 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6081 return lowerImage(Op, ImageDimIntr, DAG); 6082 6083 return Op; 6084 } 6085 } 6086 6087 // This function computes an appropriate offset to pass to 6088 // MachineMemOperand::setOffset() based on the offset inputs to 6089 // an intrinsic. If any of the offsets are non-contstant or 6090 // if VIndex is non-zero then this function returns 0. Otherwise, 6091 // it returns the sum of VOffset, SOffset, and Offset. 6092 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6093 SDValue SOffset, 6094 SDValue Offset, 6095 SDValue VIndex = SDValue()) { 6096 6097 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6098 !isa<ConstantSDNode>(Offset)) 6099 return 0; 6100 6101 if (VIndex) { 6102 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6103 return 0; 6104 } 6105 6106 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6107 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6108 cast<ConstantSDNode>(Offset)->getSExtValue(); 6109 } 6110 6111 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6112 SelectionDAG &DAG) const { 6113 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6114 SDLoc DL(Op); 6115 6116 switch (IntrID) { 6117 case Intrinsic::amdgcn_ds_ordered_add: 6118 case Intrinsic::amdgcn_ds_ordered_swap: { 6119 MemSDNode *M = cast<MemSDNode>(Op); 6120 SDValue Chain = M->getOperand(0); 6121 SDValue M0 = M->getOperand(2); 6122 SDValue Value = M->getOperand(3); 6123 unsigned IndexOperand = M->getConstantOperandVal(7); 6124 unsigned WaveRelease = M->getConstantOperandVal(8); 6125 unsigned WaveDone = M->getConstantOperandVal(9); 6126 unsigned ShaderType; 6127 unsigned Instruction; 6128 6129 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6130 IndexOperand &= ~0x3f; 6131 unsigned CountDw = 0; 6132 6133 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6134 CountDw = (IndexOperand >> 24) & 0xf; 6135 IndexOperand &= ~(0xf << 24); 6136 6137 if (CountDw < 1 || CountDw > 4) { 6138 report_fatal_error( 6139 "ds_ordered_count: dword count must be between 1 and 4"); 6140 } 6141 } 6142 6143 if (IndexOperand) 6144 report_fatal_error("ds_ordered_count: bad index operand"); 6145 6146 switch (IntrID) { 6147 case Intrinsic::amdgcn_ds_ordered_add: 6148 Instruction = 0; 6149 break; 6150 case Intrinsic::amdgcn_ds_ordered_swap: 6151 Instruction = 1; 6152 break; 6153 } 6154 6155 if (WaveDone && !WaveRelease) 6156 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6157 6158 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6159 case CallingConv::AMDGPU_CS: 6160 case CallingConv::AMDGPU_KERNEL: 6161 ShaderType = 0; 6162 break; 6163 case CallingConv::AMDGPU_PS: 6164 ShaderType = 1; 6165 break; 6166 case CallingConv::AMDGPU_VS: 6167 ShaderType = 2; 6168 break; 6169 case CallingConv::AMDGPU_GS: 6170 ShaderType = 3; 6171 break; 6172 default: 6173 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6174 } 6175 6176 unsigned Offset0 = OrderedCountIndex << 2; 6177 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6178 (Instruction << 4); 6179 6180 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6181 Offset1 |= (CountDw - 1) << 6; 6182 6183 unsigned Offset = Offset0 | (Offset1 << 8); 6184 6185 SDValue Ops[] = { 6186 Chain, 6187 Value, 6188 DAG.getTargetConstant(Offset, DL, MVT::i16), 6189 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6190 }; 6191 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6192 M->getVTList(), Ops, M->getMemoryVT(), 6193 M->getMemOperand()); 6194 } 6195 case Intrinsic::amdgcn_ds_fadd: { 6196 MemSDNode *M = cast<MemSDNode>(Op); 6197 unsigned Opc; 6198 switch (IntrID) { 6199 case Intrinsic::amdgcn_ds_fadd: 6200 Opc = ISD::ATOMIC_LOAD_FADD; 6201 break; 6202 } 6203 6204 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6205 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6206 M->getMemOperand()); 6207 } 6208 case Intrinsic::amdgcn_atomic_inc: 6209 case Intrinsic::amdgcn_atomic_dec: 6210 case Intrinsic::amdgcn_ds_fmin: 6211 case Intrinsic::amdgcn_ds_fmax: { 6212 MemSDNode *M = cast<MemSDNode>(Op); 6213 unsigned Opc; 6214 switch (IntrID) { 6215 case Intrinsic::amdgcn_atomic_inc: 6216 Opc = AMDGPUISD::ATOMIC_INC; 6217 break; 6218 case Intrinsic::amdgcn_atomic_dec: 6219 Opc = AMDGPUISD::ATOMIC_DEC; 6220 break; 6221 case Intrinsic::amdgcn_ds_fmin: 6222 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6223 break; 6224 case Intrinsic::amdgcn_ds_fmax: 6225 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6226 break; 6227 default: 6228 llvm_unreachable("Unknown intrinsic!"); 6229 } 6230 SDValue Ops[] = { 6231 M->getOperand(0), // Chain 6232 M->getOperand(2), // Ptr 6233 M->getOperand(3) // Value 6234 }; 6235 6236 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6237 M->getMemoryVT(), M->getMemOperand()); 6238 } 6239 case Intrinsic::amdgcn_buffer_load: 6240 case Intrinsic::amdgcn_buffer_load_format: { 6241 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6242 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6243 unsigned IdxEn = 1; 6244 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6245 IdxEn = Idx->getZExtValue() != 0; 6246 SDValue Ops[] = { 6247 Op.getOperand(0), // Chain 6248 Op.getOperand(2), // rsrc 6249 Op.getOperand(3), // vindex 6250 SDValue(), // voffset -- will be set by setBufferOffsets 6251 SDValue(), // soffset -- will be set by setBufferOffsets 6252 SDValue(), // offset -- will be set by setBufferOffsets 6253 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6254 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6255 }; 6256 6257 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6258 // We don't know the offset if vindex is non-zero, so clear it. 6259 if (IdxEn) 6260 Offset = 0; 6261 6262 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6263 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6264 6265 EVT VT = Op.getValueType(); 6266 EVT IntVT = VT.changeTypeToInteger(); 6267 auto *M = cast<MemSDNode>(Op); 6268 M->getMemOperand()->setOffset(Offset); 6269 EVT LoadVT = Op.getValueType(); 6270 6271 if (LoadVT.getScalarType() == MVT::f16) 6272 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6273 M, DAG, Ops); 6274 6275 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6276 if (LoadVT.getScalarType() == MVT::i8 || 6277 LoadVT.getScalarType() == MVT::i16) 6278 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6279 6280 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6281 M->getMemOperand(), DAG); 6282 } 6283 case Intrinsic::amdgcn_raw_buffer_load: 6284 case Intrinsic::amdgcn_raw_buffer_load_format: { 6285 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6286 6287 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6288 SDValue Ops[] = { 6289 Op.getOperand(0), // Chain 6290 Op.getOperand(2), // rsrc 6291 DAG.getConstant(0, DL, MVT::i32), // vindex 6292 Offsets.first, // voffset 6293 Op.getOperand(4), // soffset 6294 Offsets.second, // offset 6295 Op.getOperand(5), // cachepolicy, swizzled buffer 6296 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6297 }; 6298 6299 auto *M = cast<MemSDNode>(Op); 6300 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6301 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6302 } 6303 case Intrinsic::amdgcn_struct_buffer_load: 6304 case Intrinsic::amdgcn_struct_buffer_load_format: { 6305 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6306 6307 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6308 SDValue Ops[] = { 6309 Op.getOperand(0), // Chain 6310 Op.getOperand(2), // rsrc 6311 Op.getOperand(3), // vindex 6312 Offsets.first, // voffset 6313 Op.getOperand(5), // soffset 6314 Offsets.second, // offset 6315 Op.getOperand(6), // cachepolicy, swizzled buffer 6316 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6317 }; 6318 6319 auto *M = cast<MemSDNode>(Op); 6320 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6321 Ops[2])); 6322 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6323 } 6324 case Intrinsic::amdgcn_tbuffer_load: { 6325 MemSDNode *M = cast<MemSDNode>(Op); 6326 EVT LoadVT = Op.getValueType(); 6327 6328 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6329 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6330 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6331 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6332 unsigned IdxEn = 1; 6333 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6334 IdxEn = Idx->getZExtValue() != 0; 6335 SDValue Ops[] = { 6336 Op.getOperand(0), // Chain 6337 Op.getOperand(2), // rsrc 6338 Op.getOperand(3), // vindex 6339 Op.getOperand(4), // voffset 6340 Op.getOperand(5), // soffset 6341 Op.getOperand(6), // offset 6342 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6343 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6344 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6345 }; 6346 6347 if (LoadVT.getScalarType() == MVT::f16) 6348 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6349 M, DAG, Ops); 6350 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6351 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6352 DAG); 6353 } 6354 case Intrinsic::amdgcn_raw_tbuffer_load: { 6355 MemSDNode *M = cast<MemSDNode>(Op); 6356 EVT LoadVT = Op.getValueType(); 6357 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6358 6359 SDValue Ops[] = { 6360 Op.getOperand(0), // Chain 6361 Op.getOperand(2), // rsrc 6362 DAG.getConstant(0, DL, MVT::i32), // vindex 6363 Offsets.first, // voffset 6364 Op.getOperand(4), // soffset 6365 Offsets.second, // offset 6366 Op.getOperand(5), // format 6367 Op.getOperand(6), // cachepolicy, swizzled buffer 6368 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6369 }; 6370 6371 if (LoadVT.getScalarType() == MVT::f16) 6372 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6373 M, DAG, Ops); 6374 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6375 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6376 DAG); 6377 } 6378 case Intrinsic::amdgcn_struct_tbuffer_load: { 6379 MemSDNode *M = cast<MemSDNode>(Op); 6380 EVT LoadVT = Op.getValueType(); 6381 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6382 6383 SDValue Ops[] = { 6384 Op.getOperand(0), // Chain 6385 Op.getOperand(2), // rsrc 6386 Op.getOperand(3), // vindex 6387 Offsets.first, // voffset 6388 Op.getOperand(5), // soffset 6389 Offsets.second, // offset 6390 Op.getOperand(6), // format 6391 Op.getOperand(7), // cachepolicy, swizzled buffer 6392 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6393 }; 6394 6395 if (LoadVT.getScalarType() == MVT::f16) 6396 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6397 M, DAG, Ops); 6398 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6399 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6400 DAG); 6401 } 6402 case Intrinsic::amdgcn_buffer_atomic_swap: 6403 case Intrinsic::amdgcn_buffer_atomic_add: 6404 case Intrinsic::amdgcn_buffer_atomic_sub: 6405 case Intrinsic::amdgcn_buffer_atomic_smin: 6406 case Intrinsic::amdgcn_buffer_atomic_umin: 6407 case Intrinsic::amdgcn_buffer_atomic_smax: 6408 case Intrinsic::amdgcn_buffer_atomic_umax: 6409 case Intrinsic::amdgcn_buffer_atomic_and: 6410 case Intrinsic::amdgcn_buffer_atomic_or: 6411 case Intrinsic::amdgcn_buffer_atomic_xor: { 6412 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6413 unsigned IdxEn = 1; 6414 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6415 IdxEn = Idx->getZExtValue() != 0; 6416 SDValue Ops[] = { 6417 Op.getOperand(0), // Chain 6418 Op.getOperand(2), // vdata 6419 Op.getOperand(3), // rsrc 6420 Op.getOperand(4), // vindex 6421 SDValue(), // voffset -- will be set by setBufferOffsets 6422 SDValue(), // soffset -- will be set by setBufferOffsets 6423 SDValue(), // offset -- will be set by setBufferOffsets 6424 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6425 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6426 }; 6427 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6428 // We don't know the offset if vindex is non-zero, so clear it. 6429 if (IdxEn) 6430 Offset = 0; 6431 EVT VT = Op.getValueType(); 6432 6433 auto *M = cast<MemSDNode>(Op); 6434 M->getMemOperand()->setOffset(Offset); 6435 unsigned Opcode = 0; 6436 6437 switch (IntrID) { 6438 case Intrinsic::amdgcn_buffer_atomic_swap: 6439 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6440 break; 6441 case Intrinsic::amdgcn_buffer_atomic_add: 6442 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6443 break; 6444 case Intrinsic::amdgcn_buffer_atomic_sub: 6445 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6446 break; 6447 case Intrinsic::amdgcn_buffer_atomic_smin: 6448 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6449 break; 6450 case Intrinsic::amdgcn_buffer_atomic_umin: 6451 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6452 break; 6453 case Intrinsic::amdgcn_buffer_atomic_smax: 6454 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6455 break; 6456 case Intrinsic::amdgcn_buffer_atomic_umax: 6457 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6458 break; 6459 case Intrinsic::amdgcn_buffer_atomic_and: 6460 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6461 break; 6462 case Intrinsic::amdgcn_buffer_atomic_or: 6463 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6464 break; 6465 case Intrinsic::amdgcn_buffer_atomic_xor: 6466 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6467 break; 6468 default: 6469 llvm_unreachable("unhandled atomic opcode"); 6470 } 6471 6472 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6473 M->getMemOperand()); 6474 } 6475 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6476 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6477 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6478 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6479 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6480 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6481 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6482 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6483 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6484 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6485 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6486 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6487 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6488 SDValue Ops[] = { 6489 Op.getOperand(0), // Chain 6490 Op.getOperand(2), // vdata 6491 Op.getOperand(3), // rsrc 6492 DAG.getConstant(0, DL, MVT::i32), // vindex 6493 Offsets.first, // voffset 6494 Op.getOperand(5), // soffset 6495 Offsets.second, // offset 6496 Op.getOperand(6), // cachepolicy 6497 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6498 }; 6499 EVT VT = Op.getValueType(); 6500 6501 auto *M = cast<MemSDNode>(Op); 6502 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6503 unsigned Opcode = 0; 6504 6505 switch (IntrID) { 6506 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6507 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6508 break; 6509 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6510 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6511 break; 6512 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6513 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6514 break; 6515 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6516 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6517 break; 6518 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6519 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6520 break; 6521 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6522 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6523 break; 6524 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6525 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6526 break; 6527 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6528 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6529 break; 6530 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6531 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6532 break; 6533 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6534 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6535 break; 6536 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6537 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6538 break; 6539 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6540 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6541 break; 6542 default: 6543 llvm_unreachable("unhandled atomic opcode"); 6544 } 6545 6546 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6547 M->getMemOperand()); 6548 } 6549 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6550 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6551 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6552 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6553 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6554 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6555 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6556 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6557 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6558 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6559 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6560 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6561 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6562 SDValue Ops[] = { 6563 Op.getOperand(0), // Chain 6564 Op.getOperand(2), // vdata 6565 Op.getOperand(3), // rsrc 6566 Op.getOperand(4), // vindex 6567 Offsets.first, // voffset 6568 Op.getOperand(6), // soffset 6569 Offsets.second, // offset 6570 Op.getOperand(7), // cachepolicy 6571 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6572 }; 6573 EVT VT = Op.getValueType(); 6574 6575 auto *M = cast<MemSDNode>(Op); 6576 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6577 Ops[3])); 6578 unsigned Opcode = 0; 6579 6580 switch (IntrID) { 6581 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6582 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6583 break; 6584 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6585 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6586 break; 6587 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6588 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6589 break; 6590 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6591 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6592 break; 6593 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6594 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6595 break; 6596 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6597 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6598 break; 6599 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6600 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6601 break; 6602 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6603 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6604 break; 6605 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6606 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6607 break; 6608 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6609 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6610 break; 6611 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6612 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6613 break; 6614 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6615 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6616 break; 6617 default: 6618 llvm_unreachable("unhandled atomic opcode"); 6619 } 6620 6621 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6622 M->getMemOperand()); 6623 } 6624 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6625 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6626 unsigned IdxEn = 1; 6627 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6628 IdxEn = Idx->getZExtValue() != 0; 6629 SDValue Ops[] = { 6630 Op.getOperand(0), // Chain 6631 Op.getOperand(2), // src 6632 Op.getOperand(3), // cmp 6633 Op.getOperand(4), // rsrc 6634 Op.getOperand(5), // 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(6), DAG, &Ops[5]); 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 auto *M = cast<MemSDNode>(Op); 6647 M->getMemOperand()->setOffset(Offset); 6648 6649 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6650 Op->getVTList(), Ops, VT, M->getMemOperand()); 6651 } 6652 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6653 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6654 SDValue Ops[] = { 6655 Op.getOperand(0), // Chain 6656 Op.getOperand(2), // src 6657 Op.getOperand(3), // cmp 6658 Op.getOperand(4), // rsrc 6659 DAG.getConstant(0, DL, MVT::i32), // vindex 6660 Offsets.first, // voffset 6661 Op.getOperand(6), // soffset 6662 Offsets.second, // offset 6663 Op.getOperand(7), // cachepolicy 6664 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6665 }; 6666 EVT VT = Op.getValueType(); 6667 auto *M = cast<MemSDNode>(Op); 6668 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6669 6670 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6671 Op->getVTList(), Ops, VT, M->getMemOperand()); 6672 } 6673 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6674 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6675 SDValue Ops[] = { 6676 Op.getOperand(0), // Chain 6677 Op.getOperand(2), // src 6678 Op.getOperand(3), // cmp 6679 Op.getOperand(4), // rsrc 6680 Op.getOperand(5), // vindex 6681 Offsets.first, // voffset 6682 Op.getOperand(7), // soffset 6683 Offsets.second, // offset 6684 Op.getOperand(8), // cachepolicy 6685 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6686 }; 6687 EVT VT = Op.getValueType(); 6688 auto *M = cast<MemSDNode>(Op); 6689 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6690 Ops[4])); 6691 6692 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6693 Op->getVTList(), Ops, VT, M->getMemOperand()); 6694 } 6695 6696 default: 6697 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6698 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6699 return lowerImage(Op, ImageDimIntr, DAG); 6700 6701 return SDValue(); 6702 } 6703 } 6704 6705 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6706 // dwordx4 if on SI. 6707 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6708 SDVTList VTList, 6709 ArrayRef<SDValue> Ops, EVT MemVT, 6710 MachineMemOperand *MMO, 6711 SelectionDAG &DAG) const { 6712 EVT VT = VTList.VTs[0]; 6713 EVT WidenedVT = VT; 6714 EVT WidenedMemVT = MemVT; 6715 if (!Subtarget->hasDwordx3LoadStores() && 6716 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6717 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6718 WidenedVT.getVectorElementType(), 4); 6719 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6720 WidenedMemVT.getVectorElementType(), 4); 6721 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6722 } 6723 6724 assert(VTList.NumVTs == 2); 6725 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6726 6727 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6728 WidenedMemVT, MMO); 6729 if (WidenedVT != VT) { 6730 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6731 DAG.getVectorIdxConstant(0, DL)); 6732 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6733 } 6734 return NewOp; 6735 } 6736 6737 SDValue SITargetLowering::handleD16VData(SDValue VData, 6738 SelectionDAG &DAG) const { 6739 EVT StoreVT = VData.getValueType(); 6740 6741 // No change for f16 and legal vector D16 types. 6742 if (!StoreVT.isVector()) 6743 return VData; 6744 6745 SDLoc DL(VData); 6746 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6747 6748 if (Subtarget->hasUnpackedD16VMem()) { 6749 // We need to unpack the packed data to store. 6750 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6751 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6752 6753 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6754 StoreVT.getVectorNumElements()); 6755 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6756 return DAG.UnrollVectorOp(ZExt.getNode()); 6757 } 6758 6759 assert(isTypeLegal(StoreVT)); 6760 return VData; 6761 } 6762 6763 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6764 SelectionDAG &DAG) const { 6765 SDLoc DL(Op); 6766 SDValue Chain = Op.getOperand(0); 6767 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6768 MachineFunction &MF = DAG.getMachineFunction(); 6769 6770 switch (IntrinsicID) { 6771 case Intrinsic::amdgcn_exp_compr: { 6772 SDValue Src0 = Op.getOperand(4); 6773 SDValue Src1 = Op.getOperand(5); 6774 // Hack around illegal type on SI by directly selecting it. 6775 if (isTypeLegal(Src0.getValueType())) 6776 return SDValue(); 6777 6778 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6779 SDValue Undef = DAG.getUNDEF(MVT::f32); 6780 const SDValue Ops[] = { 6781 Op.getOperand(2), // tgt 6782 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6783 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6784 Undef, // src2 6785 Undef, // src3 6786 Op.getOperand(7), // vm 6787 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6788 Op.getOperand(3), // en 6789 Op.getOperand(0) // Chain 6790 }; 6791 6792 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6793 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6794 } 6795 case Intrinsic::amdgcn_s_barrier: { 6796 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6797 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6798 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6799 if (WGSize <= ST.getWavefrontSize()) 6800 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6801 Op.getOperand(0)), 0); 6802 } 6803 return SDValue(); 6804 }; 6805 case Intrinsic::amdgcn_tbuffer_store: { 6806 SDValue VData = Op.getOperand(2); 6807 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6808 if (IsD16) 6809 VData = handleD16VData(VData, DAG); 6810 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6811 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6812 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6813 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6814 unsigned IdxEn = 1; 6815 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6816 IdxEn = Idx->getZExtValue() != 0; 6817 SDValue Ops[] = { 6818 Chain, 6819 VData, // vdata 6820 Op.getOperand(3), // rsrc 6821 Op.getOperand(4), // vindex 6822 Op.getOperand(5), // voffset 6823 Op.getOperand(6), // soffset 6824 Op.getOperand(7), // offset 6825 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6826 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6827 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6828 }; 6829 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6830 AMDGPUISD::TBUFFER_STORE_FORMAT; 6831 MemSDNode *M = cast<MemSDNode>(Op); 6832 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6833 M->getMemoryVT(), M->getMemOperand()); 6834 } 6835 6836 case Intrinsic::amdgcn_struct_tbuffer_store: { 6837 SDValue VData = Op.getOperand(2); 6838 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6839 if (IsD16) 6840 VData = handleD16VData(VData, DAG); 6841 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6842 SDValue Ops[] = { 6843 Chain, 6844 VData, // vdata 6845 Op.getOperand(3), // rsrc 6846 Op.getOperand(4), // vindex 6847 Offsets.first, // voffset 6848 Op.getOperand(6), // soffset 6849 Offsets.second, // offset 6850 Op.getOperand(7), // format 6851 Op.getOperand(8), // cachepolicy, swizzled buffer 6852 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6853 }; 6854 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6855 AMDGPUISD::TBUFFER_STORE_FORMAT; 6856 MemSDNode *M = cast<MemSDNode>(Op); 6857 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6858 M->getMemoryVT(), M->getMemOperand()); 6859 } 6860 6861 case Intrinsic::amdgcn_raw_tbuffer_store: { 6862 SDValue VData = Op.getOperand(2); 6863 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6864 if (IsD16) 6865 VData = handleD16VData(VData, DAG); 6866 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6867 SDValue Ops[] = { 6868 Chain, 6869 VData, // vdata 6870 Op.getOperand(3), // rsrc 6871 DAG.getConstant(0, DL, MVT::i32), // vindex 6872 Offsets.first, // voffset 6873 Op.getOperand(5), // soffset 6874 Offsets.second, // offset 6875 Op.getOperand(6), // format 6876 Op.getOperand(7), // cachepolicy, swizzled buffer 6877 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6878 }; 6879 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6880 AMDGPUISD::TBUFFER_STORE_FORMAT; 6881 MemSDNode *M = cast<MemSDNode>(Op); 6882 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6883 M->getMemoryVT(), M->getMemOperand()); 6884 } 6885 6886 case Intrinsic::amdgcn_buffer_store: 6887 case Intrinsic::amdgcn_buffer_store_format: { 6888 SDValue VData = Op.getOperand(2); 6889 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6890 if (IsD16) 6891 VData = handleD16VData(VData, DAG); 6892 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6893 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6894 unsigned IdxEn = 1; 6895 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6896 IdxEn = Idx->getZExtValue() != 0; 6897 SDValue Ops[] = { 6898 Chain, 6899 VData, 6900 Op.getOperand(3), // rsrc 6901 Op.getOperand(4), // vindex 6902 SDValue(), // voffset -- will be set by setBufferOffsets 6903 SDValue(), // soffset -- will be set by setBufferOffsets 6904 SDValue(), // offset -- will be set by setBufferOffsets 6905 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6906 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6907 }; 6908 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6909 // We don't know the offset if vindex is non-zero, so clear it. 6910 if (IdxEn) 6911 Offset = 0; 6912 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6913 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6914 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6915 MemSDNode *M = cast<MemSDNode>(Op); 6916 M->getMemOperand()->setOffset(Offset); 6917 6918 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6919 EVT VDataType = VData.getValueType().getScalarType(); 6920 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6921 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6922 6923 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6924 M->getMemoryVT(), M->getMemOperand()); 6925 } 6926 6927 case Intrinsic::amdgcn_raw_buffer_store: 6928 case Intrinsic::amdgcn_raw_buffer_store_format: { 6929 const bool IsFormat = 6930 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6931 6932 SDValue VData = Op.getOperand(2); 6933 EVT VDataVT = VData.getValueType(); 6934 EVT EltType = VDataVT.getScalarType(); 6935 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6936 if (IsD16) 6937 VData = handleD16VData(VData, DAG); 6938 6939 if (!isTypeLegal(VDataVT)) { 6940 VData = 6941 DAG.getNode(ISD::BITCAST, DL, 6942 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6943 } 6944 6945 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6946 SDValue Ops[] = { 6947 Chain, 6948 VData, 6949 Op.getOperand(3), // rsrc 6950 DAG.getConstant(0, DL, MVT::i32), // vindex 6951 Offsets.first, // voffset 6952 Op.getOperand(5), // soffset 6953 Offsets.second, // offset 6954 Op.getOperand(6), // cachepolicy, swizzled buffer 6955 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6956 }; 6957 unsigned Opc = 6958 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6959 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6960 MemSDNode *M = cast<MemSDNode>(Op); 6961 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6962 6963 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6964 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6965 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 6966 6967 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6968 M->getMemoryVT(), M->getMemOperand()); 6969 } 6970 6971 case Intrinsic::amdgcn_struct_buffer_store: 6972 case Intrinsic::amdgcn_struct_buffer_store_format: { 6973 const bool IsFormat = 6974 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 6975 6976 SDValue VData = Op.getOperand(2); 6977 EVT VDataVT = VData.getValueType(); 6978 EVT EltType = VDataVT.getScalarType(); 6979 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6980 6981 if (IsD16) 6982 VData = handleD16VData(VData, DAG); 6983 6984 if (!isTypeLegal(VDataVT)) { 6985 VData = 6986 DAG.getNode(ISD::BITCAST, DL, 6987 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6988 } 6989 6990 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6991 SDValue Ops[] = { 6992 Chain, 6993 VData, 6994 Op.getOperand(3), // rsrc 6995 Op.getOperand(4), // vindex 6996 Offsets.first, // voffset 6997 Op.getOperand(6), // soffset 6998 Offsets.second, // offset 6999 Op.getOperand(7), // cachepolicy, swizzled buffer 7000 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7001 }; 7002 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7003 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7004 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7005 MemSDNode *M = cast<MemSDNode>(Op); 7006 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7007 Ops[3])); 7008 7009 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7010 EVT VDataType = VData.getValueType().getScalarType(); 7011 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7012 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7013 7014 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7015 M->getMemoryVT(), M->getMemOperand()); 7016 } 7017 7018 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7019 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7020 unsigned IdxEn = 1; 7021 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7022 IdxEn = Idx->getZExtValue() != 0; 7023 SDValue Ops[] = { 7024 Chain, 7025 Op.getOperand(2), // vdata 7026 Op.getOperand(3), // rsrc 7027 Op.getOperand(4), // vindex 7028 SDValue(), // voffset -- will be set by setBufferOffsets 7029 SDValue(), // soffset -- will be set by setBufferOffsets 7030 SDValue(), // offset -- will be set by setBufferOffsets 7031 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7032 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7033 }; 7034 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7035 // We don't know the offset if vindex is non-zero, so clear it. 7036 if (IdxEn) 7037 Offset = 0; 7038 EVT VT = Op.getOperand(2).getValueType(); 7039 7040 auto *M = cast<MemSDNode>(Op); 7041 M->getMemOperand()->setOffset(Offset); 7042 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7043 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7044 7045 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7046 M->getMemOperand()); 7047 } 7048 7049 case Intrinsic::amdgcn_global_atomic_fadd: { 7050 SDValue Ops[] = { 7051 Chain, 7052 Op.getOperand(2), // ptr 7053 Op.getOperand(3) // vdata 7054 }; 7055 EVT VT = Op.getOperand(3).getValueType(); 7056 7057 auto *M = cast<MemSDNode>(Op); 7058 if (VT.isVector()) { 7059 return DAG.getMemIntrinsicNode( 7060 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7061 M->getMemOperand()); 7062 } 7063 7064 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7065 DAG.getVTList(VT, MVT::Other), Ops, 7066 M->getMemOperand()).getValue(1); 7067 } 7068 case Intrinsic::amdgcn_end_cf: 7069 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7070 Op->getOperand(2), Chain), 0); 7071 7072 default: { 7073 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7074 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7075 return lowerImage(Op, ImageDimIntr, DAG); 7076 7077 return Op; 7078 } 7079 } 7080 } 7081 7082 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7083 // offset (the offset that is included in bounds checking and swizzling, to be 7084 // split between the instruction's voffset and immoffset fields) and soffset 7085 // (the offset that is excluded from bounds checking and swizzling, to go in 7086 // the instruction's soffset field). This function takes the first kind of 7087 // offset and figures out how to split it between voffset and immoffset. 7088 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7089 SDValue Offset, SelectionDAG &DAG) const { 7090 SDLoc DL(Offset); 7091 const unsigned MaxImm = 4095; 7092 SDValue N0 = Offset; 7093 ConstantSDNode *C1 = nullptr; 7094 7095 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7096 N0 = SDValue(); 7097 else if (DAG.isBaseWithConstantOffset(N0)) { 7098 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7099 N0 = N0.getOperand(0); 7100 } 7101 7102 if (C1) { 7103 unsigned ImmOffset = C1->getZExtValue(); 7104 // If the immediate value is too big for the immoffset field, put the value 7105 // and -4096 into the immoffset field so that the value that is copied/added 7106 // for the voffset field is a multiple of 4096, and it stands more chance 7107 // of being CSEd with the copy/add for another similar load/store. 7108 // However, do not do that rounding down to a multiple of 4096 if that is a 7109 // negative number, as it appears to be illegal to have a negative offset 7110 // in the vgpr, even if adding the immediate offset makes it positive. 7111 unsigned Overflow = ImmOffset & ~MaxImm; 7112 ImmOffset -= Overflow; 7113 if ((int32_t)Overflow < 0) { 7114 Overflow += ImmOffset; 7115 ImmOffset = 0; 7116 } 7117 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7118 if (Overflow) { 7119 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7120 if (!N0) 7121 N0 = OverflowVal; 7122 else { 7123 SDValue Ops[] = { N0, OverflowVal }; 7124 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7125 } 7126 } 7127 } 7128 if (!N0) 7129 N0 = DAG.getConstant(0, DL, MVT::i32); 7130 if (!C1) 7131 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7132 return {N0, SDValue(C1, 0)}; 7133 } 7134 7135 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7136 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7137 // pointed to by Offsets. 7138 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7139 SelectionDAG &DAG, SDValue *Offsets, 7140 unsigned Align) const { 7141 SDLoc DL(CombinedOffset); 7142 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7143 uint32_t Imm = C->getZExtValue(); 7144 uint32_t SOffset, ImmOffset; 7145 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7146 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7147 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7148 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7149 return SOffset + ImmOffset; 7150 } 7151 } 7152 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7153 SDValue N0 = CombinedOffset.getOperand(0); 7154 SDValue N1 = CombinedOffset.getOperand(1); 7155 uint32_t SOffset, ImmOffset; 7156 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7157 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7158 Subtarget, Align)) { 7159 Offsets[0] = N0; 7160 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7161 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7162 return 0; 7163 } 7164 } 7165 Offsets[0] = CombinedOffset; 7166 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7167 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7168 return 0; 7169 } 7170 7171 // Handle 8 bit and 16 bit buffer loads 7172 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7173 EVT LoadVT, SDLoc DL, 7174 ArrayRef<SDValue> Ops, 7175 MemSDNode *M) const { 7176 EVT IntVT = LoadVT.changeTypeToInteger(); 7177 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7178 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7179 7180 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7181 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7182 Ops, IntVT, 7183 M->getMemOperand()); 7184 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7185 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7186 7187 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7188 } 7189 7190 // Handle 8 bit and 16 bit buffer stores 7191 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7192 EVT VDataType, SDLoc DL, 7193 SDValue Ops[], 7194 MemSDNode *M) const { 7195 if (VDataType == MVT::f16) 7196 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7197 7198 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7199 Ops[1] = BufferStoreExt; 7200 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7201 AMDGPUISD::BUFFER_STORE_SHORT; 7202 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7203 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7204 M->getMemOperand()); 7205 } 7206 7207 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7208 ISD::LoadExtType ExtType, SDValue Op, 7209 const SDLoc &SL, EVT VT) { 7210 if (VT.bitsLT(Op.getValueType())) 7211 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7212 7213 switch (ExtType) { 7214 case ISD::SEXTLOAD: 7215 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7216 case ISD::ZEXTLOAD: 7217 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7218 case ISD::EXTLOAD: 7219 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7220 case ISD::NON_EXTLOAD: 7221 return Op; 7222 } 7223 7224 llvm_unreachable("invalid ext type"); 7225 } 7226 7227 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7228 SelectionDAG &DAG = DCI.DAG; 7229 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7230 return SDValue(); 7231 7232 // FIXME: Constant loads should all be marked invariant. 7233 unsigned AS = Ld->getAddressSpace(); 7234 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7235 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7236 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7237 return SDValue(); 7238 7239 // Don't do this early, since it may interfere with adjacent load merging for 7240 // illegal types. We can avoid losing alignment information for exotic types 7241 // pre-legalize. 7242 EVT MemVT = Ld->getMemoryVT(); 7243 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7244 MemVT.getSizeInBits() >= 32) 7245 return SDValue(); 7246 7247 SDLoc SL(Ld); 7248 7249 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7250 "unexpected vector extload"); 7251 7252 // TODO: Drop only high part of range. 7253 SDValue Ptr = Ld->getBasePtr(); 7254 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7255 MVT::i32, SL, Ld->getChain(), Ptr, 7256 Ld->getOffset(), 7257 Ld->getPointerInfo(), MVT::i32, 7258 Ld->getAlignment(), 7259 Ld->getMemOperand()->getFlags(), 7260 Ld->getAAInfo(), 7261 nullptr); // Drop ranges 7262 7263 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7264 if (MemVT.isFloatingPoint()) { 7265 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7266 "unexpected fp extload"); 7267 TruncVT = MemVT.changeTypeToInteger(); 7268 } 7269 7270 SDValue Cvt = NewLoad; 7271 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7272 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7273 DAG.getValueType(TruncVT)); 7274 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7275 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7276 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7277 } else { 7278 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7279 } 7280 7281 EVT VT = Ld->getValueType(0); 7282 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7283 7284 DCI.AddToWorklist(Cvt.getNode()); 7285 7286 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7287 // the appropriate extension from the 32-bit load. 7288 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7289 DCI.AddToWorklist(Cvt.getNode()); 7290 7291 // Handle conversion back to floating point if necessary. 7292 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7293 7294 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7295 } 7296 7297 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7298 SDLoc DL(Op); 7299 LoadSDNode *Load = cast<LoadSDNode>(Op); 7300 ISD::LoadExtType ExtType = Load->getExtensionType(); 7301 EVT MemVT = Load->getMemoryVT(); 7302 7303 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7304 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7305 return SDValue(); 7306 7307 // FIXME: Copied from PPC 7308 // First, load into 32 bits, then truncate to 1 bit. 7309 7310 SDValue Chain = Load->getChain(); 7311 SDValue BasePtr = Load->getBasePtr(); 7312 MachineMemOperand *MMO = Load->getMemOperand(); 7313 7314 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7315 7316 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7317 BasePtr, RealMemVT, MMO); 7318 7319 if (!MemVT.isVector()) { 7320 SDValue Ops[] = { 7321 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7322 NewLD.getValue(1) 7323 }; 7324 7325 return DAG.getMergeValues(Ops, DL); 7326 } 7327 7328 SmallVector<SDValue, 3> Elts; 7329 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7330 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7331 DAG.getConstant(I, DL, MVT::i32)); 7332 7333 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7334 } 7335 7336 SDValue Ops[] = { 7337 DAG.getBuildVector(MemVT, DL, Elts), 7338 NewLD.getValue(1) 7339 }; 7340 7341 return DAG.getMergeValues(Ops, DL); 7342 } 7343 7344 if (!MemVT.isVector()) 7345 return SDValue(); 7346 7347 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7348 "Custom lowering for non-i32 vectors hasn't been implemented."); 7349 7350 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7351 MemVT, *Load->getMemOperand())) { 7352 SDValue Ops[2]; 7353 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7354 return DAG.getMergeValues(Ops, DL); 7355 } 7356 7357 unsigned Alignment = Load->getAlignment(); 7358 unsigned AS = Load->getAddressSpace(); 7359 if (Subtarget->hasLDSMisalignedBug() && 7360 AS == AMDGPUAS::FLAT_ADDRESS && 7361 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7362 return SplitVectorLoad(Op, DAG); 7363 } 7364 7365 MachineFunction &MF = DAG.getMachineFunction(); 7366 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7367 // If there is a possibilty that flat instruction access scratch memory 7368 // then we need to use the same legalization rules we use for private. 7369 if (AS == AMDGPUAS::FLAT_ADDRESS && 7370 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7371 AS = MFI->hasFlatScratchInit() ? 7372 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7373 7374 unsigned NumElements = MemVT.getVectorNumElements(); 7375 7376 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7377 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7378 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7379 if (MemVT.isPow2VectorType()) 7380 return SDValue(); 7381 if (NumElements == 3) 7382 return WidenVectorLoad(Op, DAG); 7383 return SplitVectorLoad(Op, DAG); 7384 } 7385 // Non-uniform loads will be selected to MUBUF instructions, so they 7386 // have the same legalization requirements as global and private 7387 // loads. 7388 // 7389 } 7390 7391 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7392 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7393 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7394 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7395 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7396 Alignment >= 4 && NumElements < 32) { 7397 if (MemVT.isPow2VectorType()) 7398 return SDValue(); 7399 if (NumElements == 3) 7400 return WidenVectorLoad(Op, DAG); 7401 return SplitVectorLoad(Op, DAG); 7402 } 7403 // Non-uniform loads will be selected to MUBUF instructions, so they 7404 // have the same legalization requirements as global and private 7405 // loads. 7406 // 7407 } 7408 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7409 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7410 AS == AMDGPUAS::GLOBAL_ADDRESS || 7411 AS == AMDGPUAS::FLAT_ADDRESS) { 7412 if (NumElements > 4) 7413 return SplitVectorLoad(Op, DAG); 7414 // v3 loads not supported on SI. 7415 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7416 return WidenVectorLoad(Op, DAG); 7417 // v3 and v4 loads are supported for private and global memory. 7418 return SDValue(); 7419 } 7420 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7421 // Depending on the setting of the private_element_size field in the 7422 // resource descriptor, we can only make private accesses up to a certain 7423 // size. 7424 switch (Subtarget->getMaxPrivateElementSize()) { 7425 case 4: { 7426 SDValue Ops[2]; 7427 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7428 return DAG.getMergeValues(Ops, DL); 7429 } 7430 case 8: 7431 if (NumElements > 2) 7432 return SplitVectorLoad(Op, DAG); 7433 return SDValue(); 7434 case 16: 7435 // Same as global/flat 7436 if (NumElements > 4) 7437 return SplitVectorLoad(Op, DAG); 7438 // v3 loads not supported on SI. 7439 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7440 return WidenVectorLoad(Op, DAG); 7441 return SDValue(); 7442 default: 7443 llvm_unreachable("unsupported private_element_size"); 7444 } 7445 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7446 // Use ds_read_b128 if possible. 7447 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7448 MemVT.getStoreSize() == 16) 7449 return SDValue(); 7450 7451 if (NumElements > 2) 7452 return SplitVectorLoad(Op, DAG); 7453 7454 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7455 // address is negative, then the instruction is incorrectly treated as 7456 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7457 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7458 // load later in the SILoadStoreOptimizer. 7459 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7460 NumElements == 2 && MemVT.getStoreSize() == 8 && 7461 Load->getAlignment() < 8) { 7462 return SplitVectorLoad(Op, DAG); 7463 } 7464 } 7465 return SDValue(); 7466 } 7467 7468 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7469 EVT VT = Op.getValueType(); 7470 assert(VT.getSizeInBits() == 64); 7471 7472 SDLoc DL(Op); 7473 SDValue Cond = Op.getOperand(0); 7474 7475 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7476 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7477 7478 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7479 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7480 7481 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7482 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7483 7484 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7485 7486 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7487 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7488 7489 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7490 7491 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7492 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7493 } 7494 7495 // Catch division cases where we can use shortcuts with rcp and rsq 7496 // instructions. 7497 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7498 SelectionDAG &DAG) const { 7499 SDLoc SL(Op); 7500 SDValue LHS = Op.getOperand(0); 7501 SDValue RHS = Op.getOperand(1); 7502 EVT VT = Op.getValueType(); 7503 const SDNodeFlags Flags = Op->getFlags(); 7504 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7505 7506 if (!Unsafe && VT == MVT::f32 && hasFP32Denormals(DAG.getMachineFunction())) 7507 return SDValue(); 7508 7509 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7510 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7511 if (CLHS->isExactlyValue(1.0)) { 7512 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7513 // the CI documentation has a worst case error of 1 ulp. 7514 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7515 // use it as long as we aren't trying to use denormals. 7516 // 7517 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7518 7519 // 1.0 / sqrt(x) -> rsq(x) 7520 7521 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7522 // error seems really high at 2^29 ULP. 7523 if (RHS.getOpcode() == ISD::FSQRT) 7524 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7525 7526 // 1.0 / x -> rcp(x) 7527 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7528 } 7529 7530 // Same as for 1.0, but expand the sign out of the constant. 7531 if (CLHS->isExactlyValue(-1.0)) { 7532 // -1.0 / x -> rcp (fneg x) 7533 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7534 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7535 } 7536 } 7537 } 7538 7539 if (Unsafe) { 7540 // Turn into multiply by the reciprocal. 7541 // x / y -> x * (1.0 / y) 7542 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7543 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7544 } 7545 7546 return SDValue(); 7547 } 7548 7549 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7550 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7551 if (GlueChain->getNumValues() <= 1) { 7552 return DAG.getNode(Opcode, SL, VT, A, B); 7553 } 7554 7555 assert(GlueChain->getNumValues() == 3); 7556 7557 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7558 switch (Opcode) { 7559 default: llvm_unreachable("no chain equivalent for opcode"); 7560 case ISD::FMUL: 7561 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7562 break; 7563 } 7564 7565 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7566 GlueChain.getValue(2)); 7567 } 7568 7569 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7570 EVT VT, SDValue A, SDValue B, SDValue C, 7571 SDValue GlueChain) { 7572 if (GlueChain->getNumValues() <= 1) { 7573 return DAG.getNode(Opcode, SL, VT, A, B, C); 7574 } 7575 7576 assert(GlueChain->getNumValues() == 3); 7577 7578 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7579 switch (Opcode) { 7580 default: llvm_unreachable("no chain equivalent for opcode"); 7581 case ISD::FMA: 7582 Opcode = AMDGPUISD::FMA_W_CHAIN; 7583 break; 7584 } 7585 7586 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7587 GlueChain.getValue(2)); 7588 } 7589 7590 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7591 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7592 return FastLowered; 7593 7594 SDLoc SL(Op); 7595 SDValue Src0 = Op.getOperand(0); 7596 SDValue Src1 = Op.getOperand(1); 7597 7598 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7599 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7600 7601 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7602 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7603 7604 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7605 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7606 7607 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7608 } 7609 7610 // Faster 2.5 ULP division that does not support denormals. 7611 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7612 SDLoc SL(Op); 7613 SDValue LHS = Op.getOperand(1); 7614 SDValue RHS = Op.getOperand(2); 7615 7616 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7617 7618 const APFloat K0Val(BitsToFloat(0x6f800000)); 7619 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7620 7621 const APFloat K1Val(BitsToFloat(0x2f800000)); 7622 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7623 7624 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7625 7626 EVT SetCCVT = 7627 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7628 7629 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7630 7631 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7632 7633 // TODO: Should this propagate fast-math-flags? 7634 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7635 7636 // rcp does not support denormals. 7637 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7638 7639 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7640 7641 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7642 } 7643 7644 // Returns immediate value for setting the F32 denorm mode when using the 7645 // S_DENORM_MODE instruction. 7646 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7647 const SDLoc &SL, const GCNSubtarget *ST) { 7648 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7649 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7650 ? FP_DENORM_FLUSH_NONE 7651 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7652 7653 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7654 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7655 } 7656 7657 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7658 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7659 return FastLowered; 7660 7661 SDLoc SL(Op); 7662 SDValue LHS = Op.getOperand(0); 7663 SDValue RHS = Op.getOperand(1); 7664 7665 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7666 7667 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7668 7669 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7670 RHS, RHS, LHS); 7671 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7672 LHS, RHS, LHS); 7673 7674 // Denominator is scaled to not be denormal, so using rcp is ok. 7675 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7676 DenominatorScaled); 7677 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7678 DenominatorScaled); 7679 7680 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7681 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7682 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7683 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7684 7685 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7686 7687 if (!HasFP32Denormals) { 7688 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7689 7690 SDValue EnableDenorm; 7691 if (Subtarget->hasDenormModeInst()) { 7692 const SDValue EnableDenormValue = 7693 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7694 7695 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7696 DAG.getEntryNode(), EnableDenormValue); 7697 } else { 7698 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7699 SL, MVT::i32); 7700 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7701 DAG.getEntryNode(), EnableDenormValue, 7702 BitField); 7703 } 7704 7705 SDValue Ops[3] = { 7706 NegDivScale0, 7707 EnableDenorm.getValue(0), 7708 EnableDenorm.getValue(1) 7709 }; 7710 7711 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7712 } 7713 7714 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7715 ApproxRcp, One, NegDivScale0); 7716 7717 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7718 ApproxRcp, Fma0); 7719 7720 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7721 Fma1, Fma1); 7722 7723 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7724 NumeratorScaled, Mul); 7725 7726 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7727 7728 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7729 NumeratorScaled, Fma3); 7730 7731 if (!HasFP32Denormals) { 7732 SDValue DisableDenorm; 7733 if (Subtarget->hasDenormModeInst()) { 7734 const SDValue DisableDenormValue = 7735 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7736 7737 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7738 Fma4.getValue(1), DisableDenormValue, 7739 Fma4.getValue(2)); 7740 } else { 7741 const SDValue DisableDenormValue = 7742 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7743 7744 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7745 Fma4.getValue(1), DisableDenormValue, 7746 BitField, Fma4.getValue(2)); 7747 } 7748 7749 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7750 DisableDenorm, DAG.getRoot()); 7751 DAG.setRoot(OutputChain); 7752 } 7753 7754 SDValue Scale = NumeratorScaled.getValue(1); 7755 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7756 Fma4, Fma1, Fma3, Scale); 7757 7758 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7759 } 7760 7761 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7762 if (DAG.getTarget().Options.UnsafeFPMath) 7763 return lowerFastUnsafeFDIV(Op, DAG); 7764 7765 SDLoc SL(Op); 7766 SDValue X = Op.getOperand(0); 7767 SDValue Y = Op.getOperand(1); 7768 7769 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7770 7771 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7772 7773 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7774 7775 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7776 7777 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7778 7779 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7780 7781 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7782 7783 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7784 7785 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7786 7787 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7788 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7789 7790 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7791 NegDivScale0, Mul, DivScale1); 7792 7793 SDValue Scale; 7794 7795 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7796 // Workaround a hardware bug on SI where the condition output from div_scale 7797 // is not usable. 7798 7799 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7800 7801 // Figure out if the scale to use for div_fmas. 7802 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7803 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7804 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7805 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7806 7807 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7808 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7809 7810 SDValue Scale0Hi 7811 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7812 SDValue Scale1Hi 7813 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7814 7815 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7816 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7817 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7818 } else { 7819 Scale = DivScale1.getValue(1); 7820 } 7821 7822 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7823 Fma4, Fma3, Mul, Scale); 7824 7825 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7826 } 7827 7828 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7829 EVT VT = Op.getValueType(); 7830 7831 if (VT == MVT::f32) 7832 return LowerFDIV32(Op, DAG); 7833 7834 if (VT == MVT::f64) 7835 return LowerFDIV64(Op, DAG); 7836 7837 if (VT == MVT::f16) 7838 return LowerFDIV16(Op, DAG); 7839 7840 llvm_unreachable("Unexpected type for fdiv"); 7841 } 7842 7843 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7844 SDLoc DL(Op); 7845 StoreSDNode *Store = cast<StoreSDNode>(Op); 7846 EVT VT = Store->getMemoryVT(); 7847 7848 if (VT == MVT::i1) { 7849 return DAG.getTruncStore(Store->getChain(), DL, 7850 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7851 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7852 } 7853 7854 assert(VT.isVector() && 7855 Store->getValue().getValueType().getScalarType() == MVT::i32); 7856 7857 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7858 VT, *Store->getMemOperand())) { 7859 return expandUnalignedStore(Store, DAG); 7860 } 7861 7862 unsigned AS = Store->getAddressSpace(); 7863 if (Subtarget->hasLDSMisalignedBug() && 7864 AS == AMDGPUAS::FLAT_ADDRESS && 7865 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7866 return SplitVectorStore(Op, DAG); 7867 } 7868 7869 MachineFunction &MF = DAG.getMachineFunction(); 7870 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7871 // If there is a possibilty that flat instruction access scratch memory 7872 // then we need to use the same legalization rules we use for private. 7873 if (AS == AMDGPUAS::FLAT_ADDRESS && 7874 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7875 AS = MFI->hasFlatScratchInit() ? 7876 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7877 7878 unsigned NumElements = VT.getVectorNumElements(); 7879 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7880 AS == AMDGPUAS::FLAT_ADDRESS) { 7881 if (NumElements > 4) 7882 return SplitVectorStore(Op, DAG); 7883 // v3 stores not supported on SI. 7884 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7885 return SplitVectorStore(Op, DAG); 7886 return SDValue(); 7887 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7888 switch (Subtarget->getMaxPrivateElementSize()) { 7889 case 4: 7890 return scalarizeVectorStore(Store, DAG); 7891 case 8: 7892 if (NumElements > 2) 7893 return SplitVectorStore(Op, DAG); 7894 return SDValue(); 7895 case 16: 7896 if (NumElements > 4 || NumElements == 3) 7897 return SplitVectorStore(Op, DAG); 7898 return SDValue(); 7899 default: 7900 llvm_unreachable("unsupported private_element_size"); 7901 } 7902 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7903 // Use ds_write_b128 if possible. 7904 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7905 VT.getStoreSize() == 16 && NumElements != 3) 7906 return SDValue(); 7907 7908 if (NumElements > 2) 7909 return SplitVectorStore(Op, DAG); 7910 7911 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7912 // address is negative, then the instruction is incorrectly treated as 7913 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7914 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7915 // store later in the SILoadStoreOptimizer. 7916 if (!Subtarget->hasUsableDSOffset() && 7917 NumElements == 2 && VT.getStoreSize() == 8 && 7918 Store->getAlignment() < 8) { 7919 return SplitVectorStore(Op, DAG); 7920 } 7921 7922 return SDValue(); 7923 } else { 7924 llvm_unreachable("unhandled address space"); 7925 } 7926 } 7927 7928 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7929 SDLoc DL(Op); 7930 EVT VT = Op.getValueType(); 7931 SDValue Arg = Op.getOperand(0); 7932 SDValue TrigVal; 7933 7934 // TODO: Should this propagate fast-math-flags? 7935 7936 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7937 7938 if (Subtarget->hasTrigReducedRange()) { 7939 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7940 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7941 } else { 7942 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7943 } 7944 7945 switch (Op.getOpcode()) { 7946 case ISD::FCOS: 7947 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7948 case ISD::FSIN: 7949 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7950 default: 7951 llvm_unreachable("Wrong trig opcode"); 7952 } 7953 } 7954 7955 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7956 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7957 assert(AtomicNode->isCompareAndSwap()); 7958 unsigned AS = AtomicNode->getAddressSpace(); 7959 7960 // No custom lowering required for local address space 7961 if (!isFlatGlobalAddrSpace(AS)) 7962 return Op; 7963 7964 // Non-local address space requires custom lowering for atomic compare 7965 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7966 SDLoc DL(Op); 7967 SDValue ChainIn = Op.getOperand(0); 7968 SDValue Addr = Op.getOperand(1); 7969 SDValue Old = Op.getOperand(2); 7970 SDValue New = Op.getOperand(3); 7971 EVT VT = Op.getValueType(); 7972 MVT SimpleVT = VT.getSimpleVT(); 7973 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7974 7975 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7976 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7977 7978 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7979 Ops, VT, AtomicNode->getMemOperand()); 7980 } 7981 7982 //===----------------------------------------------------------------------===// 7983 // Custom DAG optimizations 7984 //===----------------------------------------------------------------------===// 7985 7986 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7987 DAGCombinerInfo &DCI) const { 7988 EVT VT = N->getValueType(0); 7989 EVT ScalarVT = VT.getScalarType(); 7990 if (ScalarVT != MVT::f32) 7991 return SDValue(); 7992 7993 SelectionDAG &DAG = DCI.DAG; 7994 SDLoc DL(N); 7995 7996 SDValue Src = N->getOperand(0); 7997 EVT SrcVT = Src.getValueType(); 7998 7999 // TODO: We could try to match extracting the higher bytes, which would be 8000 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8001 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8002 // about in practice. 8003 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8004 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8005 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 8006 DCI.AddToWorklist(Cvt.getNode()); 8007 return Cvt; 8008 } 8009 } 8010 8011 return SDValue(); 8012 } 8013 8014 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8015 8016 // This is a variant of 8017 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8018 // 8019 // The normal DAG combiner will do this, but only if the add has one use since 8020 // that would increase the number of instructions. 8021 // 8022 // This prevents us from seeing a constant offset that can be folded into a 8023 // memory instruction's addressing mode. If we know the resulting add offset of 8024 // a pointer can be folded into an addressing offset, we can replace the pointer 8025 // operand with the add of new constant offset. This eliminates one of the uses, 8026 // and may allow the remaining use to also be simplified. 8027 // 8028 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8029 unsigned AddrSpace, 8030 EVT MemVT, 8031 DAGCombinerInfo &DCI) const { 8032 SDValue N0 = N->getOperand(0); 8033 SDValue N1 = N->getOperand(1); 8034 8035 // We only do this to handle cases where it's profitable when there are 8036 // multiple uses of the add, so defer to the standard combine. 8037 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8038 N0->hasOneUse()) 8039 return SDValue(); 8040 8041 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8042 if (!CN1) 8043 return SDValue(); 8044 8045 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8046 if (!CAdd) 8047 return SDValue(); 8048 8049 // If the resulting offset is too large, we can't fold it into the addressing 8050 // mode offset. 8051 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8052 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8053 8054 AddrMode AM; 8055 AM.HasBaseReg = true; 8056 AM.BaseOffs = Offset.getSExtValue(); 8057 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8058 return SDValue(); 8059 8060 SelectionDAG &DAG = DCI.DAG; 8061 SDLoc SL(N); 8062 EVT VT = N->getValueType(0); 8063 8064 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8065 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8066 8067 SDNodeFlags Flags; 8068 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8069 (N0.getOpcode() == ISD::OR || 8070 N0->getFlags().hasNoUnsignedWrap())); 8071 8072 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8073 } 8074 8075 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8076 DAGCombinerInfo &DCI) const { 8077 SDValue Ptr = N->getBasePtr(); 8078 SelectionDAG &DAG = DCI.DAG; 8079 SDLoc SL(N); 8080 8081 // TODO: We could also do this for multiplies. 8082 if (Ptr.getOpcode() == ISD::SHL) { 8083 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8084 N->getMemoryVT(), DCI); 8085 if (NewPtr) { 8086 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8087 8088 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8089 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8090 } 8091 } 8092 8093 return SDValue(); 8094 } 8095 8096 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8097 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8098 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8099 (Opc == ISD::XOR && Val == 0); 8100 } 8101 8102 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8103 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8104 // integer combine opportunities since most 64-bit operations are decomposed 8105 // this way. TODO: We won't want this for SALU especially if it is an inline 8106 // immediate. 8107 SDValue SITargetLowering::splitBinaryBitConstantOp( 8108 DAGCombinerInfo &DCI, 8109 const SDLoc &SL, 8110 unsigned Opc, SDValue LHS, 8111 const ConstantSDNode *CRHS) const { 8112 uint64_t Val = CRHS->getZExtValue(); 8113 uint32_t ValLo = Lo_32(Val); 8114 uint32_t ValHi = Hi_32(Val); 8115 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8116 8117 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8118 bitOpWithConstantIsReducible(Opc, ValHi)) || 8119 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8120 // If we need to materialize a 64-bit immediate, it will be split up later 8121 // anyway. Avoid creating the harder to understand 64-bit immediate 8122 // materialization. 8123 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8124 } 8125 8126 return SDValue(); 8127 } 8128 8129 // Returns true if argument is a boolean value which is not serialized into 8130 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8131 static bool isBoolSGPR(SDValue V) { 8132 if (V.getValueType() != MVT::i1) 8133 return false; 8134 switch (V.getOpcode()) { 8135 default: break; 8136 case ISD::SETCC: 8137 case ISD::AND: 8138 case ISD::OR: 8139 case ISD::XOR: 8140 case AMDGPUISD::FP_CLASS: 8141 return true; 8142 } 8143 return false; 8144 } 8145 8146 // If a constant has all zeroes or all ones within each byte return it. 8147 // Otherwise return 0. 8148 static uint32_t getConstantPermuteMask(uint32_t C) { 8149 // 0xff for any zero byte in the mask 8150 uint32_t ZeroByteMask = 0; 8151 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8152 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8153 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8154 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8155 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8156 if ((NonZeroByteMask & C) != NonZeroByteMask) 8157 return 0; // Partial bytes selected. 8158 return C; 8159 } 8160 8161 // Check if a node selects whole bytes from its operand 0 starting at a byte 8162 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8163 // or -1 if not succeeded. 8164 // Note byte select encoding: 8165 // value 0-3 selects corresponding source byte; 8166 // value 0xc selects zero; 8167 // value 0xff selects 0xff. 8168 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8169 assert(V.getValueSizeInBits() == 32); 8170 8171 if (V.getNumOperands() != 2) 8172 return ~0; 8173 8174 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8175 if (!N1) 8176 return ~0; 8177 8178 uint32_t C = N1->getZExtValue(); 8179 8180 switch (V.getOpcode()) { 8181 default: 8182 break; 8183 case ISD::AND: 8184 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8185 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8186 } 8187 break; 8188 8189 case ISD::OR: 8190 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8191 return (0x03020100 & ~ConstMask) | ConstMask; 8192 } 8193 break; 8194 8195 case ISD::SHL: 8196 if (C % 8) 8197 return ~0; 8198 8199 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8200 8201 case ISD::SRL: 8202 if (C % 8) 8203 return ~0; 8204 8205 return uint32_t(0x0c0c0c0c03020100ull >> C); 8206 } 8207 8208 return ~0; 8209 } 8210 8211 SDValue SITargetLowering::performAndCombine(SDNode *N, 8212 DAGCombinerInfo &DCI) const { 8213 if (DCI.isBeforeLegalize()) 8214 return SDValue(); 8215 8216 SelectionDAG &DAG = DCI.DAG; 8217 EVT VT = N->getValueType(0); 8218 SDValue LHS = N->getOperand(0); 8219 SDValue RHS = N->getOperand(1); 8220 8221 8222 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8223 if (VT == MVT::i64 && CRHS) { 8224 if (SDValue Split 8225 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8226 return Split; 8227 } 8228 8229 if (CRHS && VT == MVT::i32) { 8230 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8231 // nb = number of trailing zeroes in mask 8232 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8233 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8234 uint64_t Mask = CRHS->getZExtValue(); 8235 unsigned Bits = countPopulation(Mask); 8236 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8237 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8238 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8239 unsigned Shift = CShift->getZExtValue(); 8240 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8241 unsigned Offset = NB + Shift; 8242 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8243 SDLoc SL(N); 8244 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8245 LHS->getOperand(0), 8246 DAG.getConstant(Offset, SL, MVT::i32), 8247 DAG.getConstant(Bits, SL, MVT::i32)); 8248 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8249 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8250 DAG.getValueType(NarrowVT)); 8251 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8252 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8253 return Shl; 8254 } 8255 } 8256 } 8257 8258 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8259 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8260 isa<ConstantSDNode>(LHS.getOperand(2))) { 8261 uint32_t Sel = getConstantPermuteMask(Mask); 8262 if (!Sel) 8263 return SDValue(); 8264 8265 // Select 0xc for all zero bytes 8266 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8267 SDLoc DL(N); 8268 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8269 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8270 } 8271 } 8272 8273 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8274 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8275 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8276 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8277 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8278 8279 SDValue X = LHS.getOperand(0); 8280 SDValue Y = RHS.getOperand(0); 8281 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8282 return SDValue(); 8283 8284 if (LCC == ISD::SETO) { 8285 if (X != LHS.getOperand(1)) 8286 return SDValue(); 8287 8288 if (RCC == ISD::SETUNE) { 8289 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8290 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8291 return SDValue(); 8292 8293 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8294 SIInstrFlags::N_SUBNORMAL | 8295 SIInstrFlags::N_ZERO | 8296 SIInstrFlags::P_ZERO | 8297 SIInstrFlags::P_SUBNORMAL | 8298 SIInstrFlags::P_NORMAL; 8299 8300 static_assert(((~(SIInstrFlags::S_NAN | 8301 SIInstrFlags::Q_NAN | 8302 SIInstrFlags::N_INFINITY | 8303 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8304 "mask not equal"); 8305 8306 SDLoc DL(N); 8307 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8308 X, DAG.getConstant(Mask, DL, MVT::i32)); 8309 } 8310 } 8311 } 8312 8313 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8314 std::swap(LHS, RHS); 8315 8316 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8317 RHS.hasOneUse()) { 8318 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8319 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8320 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8321 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8322 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8323 (RHS.getOperand(0) == LHS.getOperand(0) && 8324 LHS.getOperand(0) == LHS.getOperand(1))) { 8325 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8326 unsigned NewMask = LCC == ISD::SETO ? 8327 Mask->getZExtValue() & ~OrdMask : 8328 Mask->getZExtValue() & OrdMask; 8329 8330 SDLoc DL(N); 8331 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8332 DAG.getConstant(NewMask, DL, MVT::i32)); 8333 } 8334 } 8335 8336 if (VT == MVT::i32 && 8337 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8338 // and x, (sext cc from i1) => select cc, x, 0 8339 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8340 std::swap(LHS, RHS); 8341 if (isBoolSGPR(RHS.getOperand(0))) 8342 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8343 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8344 } 8345 8346 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8347 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8348 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8349 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8350 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8351 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8352 if (LHSMask != ~0u && RHSMask != ~0u) { 8353 // Canonicalize the expression in an attempt to have fewer unique masks 8354 // and therefore fewer registers used to hold the masks. 8355 if (LHSMask > RHSMask) { 8356 std::swap(LHSMask, RHSMask); 8357 std::swap(LHS, RHS); 8358 } 8359 8360 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8361 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8362 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8363 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8364 8365 // Check of we need to combine values from two sources within a byte. 8366 if (!(LHSUsedLanes & RHSUsedLanes) && 8367 // If we select high and lower word keep it for SDWA. 8368 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8369 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8370 // Each byte in each mask is either selector mask 0-3, or has higher 8371 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8372 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8373 // mask which is not 0xff wins. By anding both masks we have a correct 8374 // result except that 0x0c shall be corrected to give 0x0c only. 8375 uint32_t Mask = LHSMask & RHSMask; 8376 for (unsigned I = 0; I < 32; I += 8) { 8377 uint32_t ByteSel = 0xff << I; 8378 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8379 Mask &= (0x0c << I) & 0xffffffff; 8380 } 8381 8382 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8383 // or 0x0c. 8384 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8385 SDLoc DL(N); 8386 8387 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8388 LHS.getOperand(0), RHS.getOperand(0), 8389 DAG.getConstant(Sel, DL, MVT::i32)); 8390 } 8391 } 8392 } 8393 8394 return SDValue(); 8395 } 8396 8397 SDValue SITargetLowering::performOrCombine(SDNode *N, 8398 DAGCombinerInfo &DCI) const { 8399 SelectionDAG &DAG = DCI.DAG; 8400 SDValue LHS = N->getOperand(0); 8401 SDValue RHS = N->getOperand(1); 8402 8403 EVT VT = N->getValueType(0); 8404 if (VT == MVT::i1) { 8405 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8406 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8407 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8408 SDValue Src = LHS.getOperand(0); 8409 if (Src != RHS.getOperand(0)) 8410 return SDValue(); 8411 8412 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8413 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8414 if (!CLHS || !CRHS) 8415 return SDValue(); 8416 8417 // Only 10 bits are used. 8418 static const uint32_t MaxMask = 0x3ff; 8419 8420 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8421 SDLoc DL(N); 8422 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8423 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8424 } 8425 8426 return SDValue(); 8427 } 8428 8429 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8430 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8431 LHS.getOpcode() == AMDGPUISD::PERM && 8432 isa<ConstantSDNode>(LHS.getOperand(2))) { 8433 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8434 if (!Sel) 8435 return SDValue(); 8436 8437 Sel |= LHS.getConstantOperandVal(2); 8438 SDLoc DL(N); 8439 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8440 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8441 } 8442 8443 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8444 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8445 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8446 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8447 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8448 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8449 if (LHSMask != ~0u && RHSMask != ~0u) { 8450 // Canonicalize the expression in an attempt to have fewer unique masks 8451 // and therefore fewer registers used to hold the masks. 8452 if (LHSMask > RHSMask) { 8453 std::swap(LHSMask, RHSMask); 8454 std::swap(LHS, RHS); 8455 } 8456 8457 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8458 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8459 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8460 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8461 8462 // Check of we need to combine values from two sources within a byte. 8463 if (!(LHSUsedLanes & RHSUsedLanes) && 8464 // If we select high and lower word keep it for SDWA. 8465 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8466 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8467 // Kill zero bytes selected by other mask. Zero value is 0xc. 8468 LHSMask &= ~RHSUsedLanes; 8469 RHSMask &= ~LHSUsedLanes; 8470 // Add 4 to each active LHS lane 8471 LHSMask |= LHSUsedLanes & 0x04040404; 8472 // Combine masks 8473 uint32_t Sel = LHSMask | RHSMask; 8474 SDLoc DL(N); 8475 8476 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8477 LHS.getOperand(0), RHS.getOperand(0), 8478 DAG.getConstant(Sel, DL, MVT::i32)); 8479 } 8480 } 8481 } 8482 8483 if (VT != MVT::i64) 8484 return SDValue(); 8485 8486 // TODO: This could be a generic combine with a predicate for extracting the 8487 // high half of an integer being free. 8488 8489 // (or i64:x, (zero_extend i32:y)) -> 8490 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8491 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8492 RHS.getOpcode() != ISD::ZERO_EXTEND) 8493 std::swap(LHS, RHS); 8494 8495 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8496 SDValue ExtSrc = RHS.getOperand(0); 8497 EVT SrcVT = ExtSrc.getValueType(); 8498 if (SrcVT == MVT::i32) { 8499 SDLoc SL(N); 8500 SDValue LowLHS, HiBits; 8501 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8502 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8503 8504 DCI.AddToWorklist(LowOr.getNode()); 8505 DCI.AddToWorklist(HiBits.getNode()); 8506 8507 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8508 LowOr, HiBits); 8509 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8510 } 8511 } 8512 8513 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8514 if (CRHS) { 8515 if (SDValue Split 8516 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8517 return Split; 8518 } 8519 8520 return SDValue(); 8521 } 8522 8523 SDValue SITargetLowering::performXorCombine(SDNode *N, 8524 DAGCombinerInfo &DCI) const { 8525 EVT VT = N->getValueType(0); 8526 if (VT != MVT::i64) 8527 return SDValue(); 8528 8529 SDValue LHS = N->getOperand(0); 8530 SDValue RHS = N->getOperand(1); 8531 8532 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8533 if (CRHS) { 8534 if (SDValue Split 8535 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8536 return Split; 8537 } 8538 8539 return SDValue(); 8540 } 8541 8542 // Instructions that will be lowered with a final instruction that zeros the 8543 // high result bits. 8544 // XXX - probably only need to list legal operations. 8545 static bool fp16SrcZerosHighBits(unsigned Opc) { 8546 switch (Opc) { 8547 case ISD::FADD: 8548 case ISD::FSUB: 8549 case ISD::FMUL: 8550 case ISD::FDIV: 8551 case ISD::FREM: 8552 case ISD::FMA: 8553 case ISD::FMAD: 8554 case ISD::FCANONICALIZE: 8555 case ISD::FP_ROUND: 8556 case ISD::UINT_TO_FP: 8557 case ISD::SINT_TO_FP: 8558 case ISD::FABS: 8559 // Fabs is lowered to a bit operation, but it's an and which will clear the 8560 // high bits anyway. 8561 case ISD::FSQRT: 8562 case ISD::FSIN: 8563 case ISD::FCOS: 8564 case ISD::FPOWI: 8565 case ISD::FPOW: 8566 case ISD::FLOG: 8567 case ISD::FLOG2: 8568 case ISD::FLOG10: 8569 case ISD::FEXP: 8570 case ISD::FEXP2: 8571 case ISD::FCEIL: 8572 case ISD::FTRUNC: 8573 case ISD::FRINT: 8574 case ISD::FNEARBYINT: 8575 case ISD::FROUND: 8576 case ISD::FFLOOR: 8577 case ISD::FMINNUM: 8578 case ISD::FMAXNUM: 8579 case AMDGPUISD::FRACT: 8580 case AMDGPUISD::CLAMP: 8581 case AMDGPUISD::COS_HW: 8582 case AMDGPUISD::SIN_HW: 8583 case AMDGPUISD::FMIN3: 8584 case AMDGPUISD::FMAX3: 8585 case AMDGPUISD::FMED3: 8586 case AMDGPUISD::FMAD_FTZ: 8587 case AMDGPUISD::RCP: 8588 case AMDGPUISD::RSQ: 8589 case AMDGPUISD::RCP_IFLAG: 8590 case AMDGPUISD::LDEXP: 8591 return true; 8592 default: 8593 // fcopysign, select and others may be lowered to 32-bit bit operations 8594 // which don't zero the high bits. 8595 return false; 8596 } 8597 } 8598 8599 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8600 DAGCombinerInfo &DCI) const { 8601 if (!Subtarget->has16BitInsts() || 8602 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8603 return SDValue(); 8604 8605 EVT VT = N->getValueType(0); 8606 if (VT != MVT::i32) 8607 return SDValue(); 8608 8609 SDValue Src = N->getOperand(0); 8610 if (Src.getValueType() != MVT::i16) 8611 return SDValue(); 8612 8613 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8614 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8615 if (Src.getOpcode() == ISD::BITCAST) { 8616 SDValue BCSrc = Src.getOperand(0); 8617 if (BCSrc.getValueType() == MVT::f16 && 8618 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8619 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8620 } 8621 8622 return SDValue(); 8623 } 8624 8625 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8626 DAGCombinerInfo &DCI) 8627 const { 8628 SDValue Src = N->getOperand(0); 8629 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8630 8631 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8632 VTSign->getVT() == MVT::i8) || 8633 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8634 VTSign->getVT() == MVT::i16)) && 8635 Src.hasOneUse()) { 8636 auto *M = cast<MemSDNode>(Src); 8637 SDValue Ops[] = { 8638 Src.getOperand(0), // Chain 8639 Src.getOperand(1), // rsrc 8640 Src.getOperand(2), // vindex 8641 Src.getOperand(3), // voffset 8642 Src.getOperand(4), // soffset 8643 Src.getOperand(5), // offset 8644 Src.getOperand(6), 8645 Src.getOperand(7) 8646 }; 8647 // replace with BUFFER_LOAD_BYTE/SHORT 8648 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8649 Src.getOperand(0).getValueType()); 8650 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8651 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8652 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8653 ResList, 8654 Ops, M->getMemoryVT(), 8655 M->getMemOperand()); 8656 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8657 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8658 } 8659 return SDValue(); 8660 } 8661 8662 SDValue SITargetLowering::performClassCombine(SDNode *N, 8663 DAGCombinerInfo &DCI) const { 8664 SelectionDAG &DAG = DCI.DAG; 8665 SDValue Mask = N->getOperand(1); 8666 8667 // fp_class x, 0 -> false 8668 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8669 if (CMask->isNullValue()) 8670 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8671 } 8672 8673 if (N->getOperand(0).isUndef()) 8674 return DAG.getUNDEF(MVT::i1); 8675 8676 return SDValue(); 8677 } 8678 8679 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8680 DAGCombinerInfo &DCI) const { 8681 EVT VT = N->getValueType(0); 8682 SDValue N0 = N->getOperand(0); 8683 8684 if (N0.isUndef()) 8685 return N0; 8686 8687 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8688 N0.getOpcode() == ISD::SINT_TO_FP)) { 8689 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8690 N->getFlags()); 8691 } 8692 8693 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8694 } 8695 8696 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8697 unsigned MaxDepth) const { 8698 unsigned Opcode = Op.getOpcode(); 8699 if (Opcode == ISD::FCANONICALIZE) 8700 return true; 8701 8702 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8703 auto F = CFP->getValueAPF(); 8704 if (F.isNaN() && F.isSignaling()) 8705 return false; 8706 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8707 } 8708 8709 // If source is a result of another standard FP operation it is already in 8710 // canonical form. 8711 if (MaxDepth == 0) 8712 return false; 8713 8714 switch (Opcode) { 8715 // These will flush denorms if required. 8716 case ISD::FADD: 8717 case ISD::FSUB: 8718 case ISD::FMUL: 8719 case ISD::FCEIL: 8720 case ISD::FFLOOR: 8721 case ISD::FMA: 8722 case ISD::FMAD: 8723 case ISD::FSQRT: 8724 case ISD::FDIV: 8725 case ISD::FREM: 8726 case ISD::FP_ROUND: 8727 case ISD::FP_EXTEND: 8728 case AMDGPUISD::FMUL_LEGACY: 8729 case AMDGPUISD::FMAD_FTZ: 8730 case AMDGPUISD::RCP: 8731 case AMDGPUISD::RSQ: 8732 case AMDGPUISD::RSQ_CLAMP: 8733 case AMDGPUISD::RCP_LEGACY: 8734 case AMDGPUISD::RSQ_LEGACY: 8735 case AMDGPUISD::RCP_IFLAG: 8736 case AMDGPUISD::TRIG_PREOP: 8737 case AMDGPUISD::DIV_SCALE: 8738 case AMDGPUISD::DIV_FMAS: 8739 case AMDGPUISD::DIV_FIXUP: 8740 case AMDGPUISD::FRACT: 8741 case AMDGPUISD::LDEXP: 8742 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8743 case AMDGPUISD::CVT_F32_UBYTE0: 8744 case AMDGPUISD::CVT_F32_UBYTE1: 8745 case AMDGPUISD::CVT_F32_UBYTE2: 8746 case AMDGPUISD::CVT_F32_UBYTE3: 8747 return true; 8748 8749 // It can/will be lowered or combined as a bit operation. 8750 // Need to check their input recursively to handle. 8751 case ISD::FNEG: 8752 case ISD::FABS: 8753 case ISD::FCOPYSIGN: 8754 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8755 8756 case ISD::FSIN: 8757 case ISD::FCOS: 8758 case ISD::FSINCOS: 8759 return Op.getValueType().getScalarType() != MVT::f16; 8760 8761 case ISD::FMINNUM: 8762 case ISD::FMAXNUM: 8763 case ISD::FMINNUM_IEEE: 8764 case ISD::FMAXNUM_IEEE: 8765 case AMDGPUISD::CLAMP: 8766 case AMDGPUISD::FMED3: 8767 case AMDGPUISD::FMAX3: 8768 case AMDGPUISD::FMIN3: { 8769 // FIXME: Shouldn't treat the generic operations different based these. 8770 // However, we aren't really required to flush the result from 8771 // minnum/maxnum.. 8772 8773 // snans will be quieted, so we only need to worry about denormals. 8774 if (Subtarget->supportsMinMaxDenormModes() || 8775 denormalsEnabledForType(DAG, Op.getValueType())) 8776 return true; 8777 8778 // Flushing may be required. 8779 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8780 // targets need to check their input recursively. 8781 8782 // FIXME: Does this apply with clamp? It's implemented with max. 8783 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8784 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8785 return false; 8786 } 8787 8788 return true; 8789 } 8790 case ISD::SELECT: { 8791 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8792 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8793 } 8794 case ISD::BUILD_VECTOR: { 8795 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8796 SDValue SrcOp = Op.getOperand(i); 8797 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8798 return false; 8799 } 8800 8801 return true; 8802 } 8803 case ISD::EXTRACT_VECTOR_ELT: 8804 case ISD::EXTRACT_SUBVECTOR: { 8805 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8806 } 8807 case ISD::INSERT_VECTOR_ELT: { 8808 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8809 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8810 } 8811 case ISD::UNDEF: 8812 // Could be anything. 8813 return false; 8814 8815 case ISD::BITCAST: { 8816 // Hack round the mess we make when legalizing extract_vector_elt 8817 SDValue Src = Op.getOperand(0); 8818 if (Src.getValueType() == MVT::i16 && 8819 Src.getOpcode() == ISD::TRUNCATE) { 8820 SDValue TruncSrc = Src.getOperand(0); 8821 if (TruncSrc.getValueType() == MVT::i32 && 8822 TruncSrc.getOpcode() == ISD::BITCAST && 8823 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8824 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8825 } 8826 } 8827 8828 return false; 8829 } 8830 case ISD::INTRINSIC_WO_CHAIN: { 8831 unsigned IntrinsicID 8832 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8833 // TODO: Handle more intrinsics 8834 switch (IntrinsicID) { 8835 case Intrinsic::amdgcn_cvt_pkrtz: 8836 case Intrinsic::amdgcn_cubeid: 8837 case Intrinsic::amdgcn_frexp_mant: 8838 case Intrinsic::amdgcn_fdot2: 8839 return true; 8840 default: 8841 break; 8842 } 8843 8844 LLVM_FALLTHROUGH; 8845 } 8846 default: 8847 return denormalsEnabledForType(DAG, Op.getValueType()) && 8848 DAG.isKnownNeverSNaN(Op); 8849 } 8850 8851 llvm_unreachable("invalid operation"); 8852 } 8853 8854 // Constant fold canonicalize. 8855 SDValue SITargetLowering::getCanonicalConstantFP( 8856 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8857 // Flush denormals to 0 if not enabled. 8858 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8859 return DAG.getConstantFP(0.0, SL, VT); 8860 8861 if (C.isNaN()) { 8862 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8863 if (C.isSignaling()) { 8864 // Quiet a signaling NaN. 8865 // FIXME: Is this supposed to preserve payload bits? 8866 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8867 } 8868 8869 // Make sure it is the canonical NaN bitpattern. 8870 // 8871 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8872 // immediate? 8873 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8874 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8875 } 8876 8877 // Already canonical. 8878 return DAG.getConstantFP(C, SL, VT); 8879 } 8880 8881 static bool vectorEltWillFoldAway(SDValue Op) { 8882 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8883 } 8884 8885 SDValue SITargetLowering::performFCanonicalizeCombine( 8886 SDNode *N, 8887 DAGCombinerInfo &DCI) const { 8888 SelectionDAG &DAG = DCI.DAG; 8889 SDValue N0 = N->getOperand(0); 8890 EVT VT = N->getValueType(0); 8891 8892 // fcanonicalize undef -> qnan 8893 if (N0.isUndef()) { 8894 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8895 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8896 } 8897 8898 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8899 EVT VT = N->getValueType(0); 8900 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8901 } 8902 8903 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8904 // (fcanonicalize k) 8905 // 8906 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8907 8908 // TODO: This could be better with wider vectors that will be split to v2f16, 8909 // and to consider uses since there aren't that many packed operations. 8910 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8911 isTypeLegal(MVT::v2f16)) { 8912 SDLoc SL(N); 8913 SDValue NewElts[2]; 8914 SDValue Lo = N0.getOperand(0); 8915 SDValue Hi = N0.getOperand(1); 8916 EVT EltVT = Lo.getValueType(); 8917 8918 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8919 for (unsigned I = 0; I != 2; ++I) { 8920 SDValue Op = N0.getOperand(I); 8921 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8922 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8923 CFP->getValueAPF()); 8924 } else if (Op.isUndef()) { 8925 // Handled below based on what the other operand is. 8926 NewElts[I] = Op; 8927 } else { 8928 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8929 } 8930 } 8931 8932 // If one half is undef, and one is constant, perfer a splat vector rather 8933 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8934 // cheaper to use and may be free with a packed operation. 8935 if (NewElts[0].isUndef()) { 8936 if (isa<ConstantFPSDNode>(NewElts[1])) 8937 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8938 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8939 } 8940 8941 if (NewElts[1].isUndef()) { 8942 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8943 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8944 } 8945 8946 return DAG.getBuildVector(VT, SL, NewElts); 8947 } 8948 } 8949 8950 unsigned SrcOpc = N0.getOpcode(); 8951 8952 // If it's free to do so, push canonicalizes further up the source, which may 8953 // find a canonical source. 8954 // 8955 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8956 // sNaNs. 8957 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8958 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8959 if (CRHS && N0.hasOneUse()) { 8960 SDLoc SL(N); 8961 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8962 N0.getOperand(0)); 8963 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8964 DCI.AddToWorklist(Canon0.getNode()); 8965 8966 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8967 } 8968 } 8969 8970 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8971 } 8972 8973 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8974 switch (Opc) { 8975 case ISD::FMAXNUM: 8976 case ISD::FMAXNUM_IEEE: 8977 return AMDGPUISD::FMAX3; 8978 case ISD::SMAX: 8979 return AMDGPUISD::SMAX3; 8980 case ISD::UMAX: 8981 return AMDGPUISD::UMAX3; 8982 case ISD::FMINNUM: 8983 case ISD::FMINNUM_IEEE: 8984 return AMDGPUISD::FMIN3; 8985 case ISD::SMIN: 8986 return AMDGPUISD::SMIN3; 8987 case ISD::UMIN: 8988 return AMDGPUISD::UMIN3; 8989 default: 8990 llvm_unreachable("Not a min/max opcode"); 8991 } 8992 } 8993 8994 SDValue SITargetLowering::performIntMed3ImmCombine( 8995 SelectionDAG &DAG, const SDLoc &SL, 8996 SDValue Op0, SDValue Op1, bool Signed) const { 8997 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8998 if (!K1) 8999 return SDValue(); 9000 9001 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9002 if (!K0) 9003 return SDValue(); 9004 9005 if (Signed) { 9006 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9007 return SDValue(); 9008 } else { 9009 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9010 return SDValue(); 9011 } 9012 9013 EVT VT = K0->getValueType(0); 9014 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9015 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9016 return DAG.getNode(Med3Opc, SL, VT, 9017 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9018 } 9019 9020 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9021 MVT NVT = MVT::i32; 9022 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9023 9024 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9025 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9026 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9027 9028 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9029 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9030 } 9031 9032 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9033 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9034 return C; 9035 9036 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9037 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9038 return C; 9039 } 9040 9041 return nullptr; 9042 } 9043 9044 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9045 const SDLoc &SL, 9046 SDValue Op0, 9047 SDValue Op1) const { 9048 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9049 if (!K1) 9050 return SDValue(); 9051 9052 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9053 if (!K0) 9054 return SDValue(); 9055 9056 // Ordered >= (although NaN inputs should have folded away by now). 9057 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 9058 if (Cmp == APFloat::cmpGreaterThan) 9059 return SDValue(); 9060 9061 const MachineFunction &MF = DAG.getMachineFunction(); 9062 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9063 9064 // TODO: Check IEEE bit enabled? 9065 EVT VT = Op0.getValueType(); 9066 if (Info->getMode().DX10Clamp) { 9067 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9068 // hardware fmed3 behavior converting to a min. 9069 // FIXME: Should this be allowing -0.0? 9070 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9071 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9072 } 9073 9074 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9075 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9076 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9077 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9078 // then give the other result, which is different from med3 with a NaN 9079 // input. 9080 SDValue Var = Op0.getOperand(0); 9081 if (!DAG.isKnownNeverSNaN(Var)) 9082 return SDValue(); 9083 9084 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9085 9086 if ((!K0->hasOneUse() || 9087 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9088 (!K1->hasOneUse() || 9089 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9090 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9091 Var, SDValue(K0, 0), SDValue(K1, 0)); 9092 } 9093 } 9094 9095 return SDValue(); 9096 } 9097 9098 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9099 DAGCombinerInfo &DCI) const { 9100 SelectionDAG &DAG = DCI.DAG; 9101 9102 EVT VT = N->getValueType(0); 9103 unsigned Opc = N->getOpcode(); 9104 SDValue Op0 = N->getOperand(0); 9105 SDValue Op1 = N->getOperand(1); 9106 9107 // Only do this if the inner op has one use since this will just increases 9108 // register pressure for no benefit. 9109 9110 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9111 !VT.isVector() && 9112 (VT == MVT::i32 || VT == MVT::f32 || 9113 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9114 // max(max(a, b), c) -> max3(a, b, c) 9115 // min(min(a, b), c) -> min3(a, b, c) 9116 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9117 SDLoc DL(N); 9118 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9119 DL, 9120 N->getValueType(0), 9121 Op0.getOperand(0), 9122 Op0.getOperand(1), 9123 Op1); 9124 } 9125 9126 // Try commuted. 9127 // max(a, max(b, c)) -> max3(a, b, c) 9128 // min(a, min(b, c)) -> min3(a, b, c) 9129 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9130 SDLoc DL(N); 9131 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9132 DL, 9133 N->getValueType(0), 9134 Op0, 9135 Op1.getOperand(0), 9136 Op1.getOperand(1)); 9137 } 9138 } 9139 9140 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9141 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9142 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9143 return Med3; 9144 } 9145 9146 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9147 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9148 return Med3; 9149 } 9150 9151 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9152 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9153 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9154 (Opc == AMDGPUISD::FMIN_LEGACY && 9155 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9156 (VT == MVT::f32 || VT == MVT::f64 || 9157 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9158 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9159 Op0.hasOneUse()) { 9160 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9161 return Res; 9162 } 9163 9164 return SDValue(); 9165 } 9166 9167 static bool isClampZeroToOne(SDValue A, SDValue B) { 9168 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9169 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9170 // FIXME: Should this be allowing -0.0? 9171 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9172 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9173 } 9174 } 9175 9176 return false; 9177 } 9178 9179 // FIXME: Should only worry about snans for version with chain. 9180 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9181 DAGCombinerInfo &DCI) const { 9182 EVT VT = N->getValueType(0); 9183 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9184 // NaNs. With a NaN input, the order of the operands may change the result. 9185 9186 SelectionDAG &DAG = DCI.DAG; 9187 SDLoc SL(N); 9188 9189 SDValue Src0 = N->getOperand(0); 9190 SDValue Src1 = N->getOperand(1); 9191 SDValue Src2 = N->getOperand(2); 9192 9193 if (isClampZeroToOne(Src0, Src1)) { 9194 // const_a, const_b, x -> clamp is safe in all cases including signaling 9195 // nans. 9196 // FIXME: Should this be allowing -0.0? 9197 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9198 } 9199 9200 const MachineFunction &MF = DAG.getMachineFunction(); 9201 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9202 9203 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9204 // handling no dx10-clamp? 9205 if (Info->getMode().DX10Clamp) { 9206 // If NaNs is clamped to 0, we are free to reorder the inputs. 9207 9208 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9209 std::swap(Src0, Src1); 9210 9211 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9212 std::swap(Src1, Src2); 9213 9214 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9215 std::swap(Src0, Src1); 9216 9217 if (isClampZeroToOne(Src1, Src2)) 9218 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9219 } 9220 9221 return SDValue(); 9222 } 9223 9224 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9225 DAGCombinerInfo &DCI) const { 9226 SDValue Src0 = N->getOperand(0); 9227 SDValue Src1 = N->getOperand(1); 9228 if (Src0.isUndef() && Src1.isUndef()) 9229 return DCI.DAG.getUNDEF(N->getValueType(0)); 9230 return SDValue(); 9231 } 9232 9233 SDValue SITargetLowering::performExtractVectorEltCombine( 9234 SDNode *N, DAGCombinerInfo &DCI) const { 9235 SDValue Vec = N->getOperand(0); 9236 SelectionDAG &DAG = DCI.DAG; 9237 9238 EVT VecVT = Vec.getValueType(); 9239 EVT EltVT = VecVT.getVectorElementType(); 9240 9241 if ((Vec.getOpcode() == ISD::FNEG || 9242 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9243 SDLoc SL(N); 9244 EVT EltVT = N->getValueType(0); 9245 SDValue Idx = N->getOperand(1); 9246 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9247 Vec.getOperand(0), Idx); 9248 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9249 } 9250 9251 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9252 // => 9253 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9254 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9255 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9256 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9257 SDLoc SL(N); 9258 EVT EltVT = N->getValueType(0); 9259 SDValue Idx = N->getOperand(1); 9260 unsigned Opc = Vec.getOpcode(); 9261 9262 switch(Opc) { 9263 default: 9264 break; 9265 // TODO: Support other binary operations. 9266 case ISD::FADD: 9267 case ISD::FSUB: 9268 case ISD::FMUL: 9269 case ISD::ADD: 9270 case ISD::UMIN: 9271 case ISD::UMAX: 9272 case ISD::SMIN: 9273 case ISD::SMAX: 9274 case ISD::FMAXNUM: 9275 case ISD::FMINNUM: 9276 case ISD::FMAXNUM_IEEE: 9277 case ISD::FMINNUM_IEEE: { 9278 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9279 Vec.getOperand(0), Idx); 9280 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9281 Vec.getOperand(1), Idx); 9282 9283 DCI.AddToWorklist(Elt0.getNode()); 9284 DCI.AddToWorklist(Elt1.getNode()); 9285 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9286 } 9287 } 9288 } 9289 9290 unsigned VecSize = VecVT.getSizeInBits(); 9291 unsigned EltSize = EltVT.getSizeInBits(); 9292 9293 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9294 // This elminates non-constant index and subsequent movrel or scratch access. 9295 // Sub-dword vectors of size 2 dword or less have better implementation. 9296 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9297 // instructions. 9298 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9299 !isa<ConstantSDNode>(N->getOperand(1))) { 9300 SDLoc SL(N); 9301 SDValue Idx = N->getOperand(1); 9302 SDValue V; 9303 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9304 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9305 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9306 if (I == 0) 9307 V = Elt; 9308 else 9309 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9310 } 9311 return V; 9312 } 9313 9314 if (!DCI.isBeforeLegalize()) 9315 return SDValue(); 9316 9317 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9318 // elements. This exposes more load reduction opportunities by replacing 9319 // multiple small extract_vector_elements with a single 32-bit extract. 9320 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9321 if (isa<MemSDNode>(Vec) && 9322 EltSize <= 16 && 9323 EltVT.isByteSized() && 9324 VecSize > 32 && 9325 VecSize % 32 == 0 && 9326 Idx) { 9327 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9328 9329 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9330 unsigned EltIdx = BitIndex / 32; 9331 unsigned LeftoverBitIdx = BitIndex % 32; 9332 SDLoc SL(N); 9333 9334 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9335 DCI.AddToWorklist(Cast.getNode()); 9336 9337 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9338 DAG.getConstant(EltIdx, SL, MVT::i32)); 9339 DCI.AddToWorklist(Elt.getNode()); 9340 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9341 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9342 DCI.AddToWorklist(Srl.getNode()); 9343 9344 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9345 DCI.AddToWorklist(Trunc.getNode()); 9346 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9347 } 9348 9349 return SDValue(); 9350 } 9351 9352 SDValue 9353 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9354 DAGCombinerInfo &DCI) const { 9355 SDValue Vec = N->getOperand(0); 9356 SDValue Idx = N->getOperand(2); 9357 EVT VecVT = Vec.getValueType(); 9358 EVT EltVT = VecVT.getVectorElementType(); 9359 unsigned VecSize = VecVT.getSizeInBits(); 9360 unsigned EltSize = EltVT.getSizeInBits(); 9361 9362 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9363 // => BUILD_VECTOR n x select (e, const-idx) 9364 // This elminates non-constant index and subsequent movrel or scratch access. 9365 // Sub-dword vectors of size 2 dword or less have better implementation. 9366 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9367 // instructions. 9368 if (isa<ConstantSDNode>(Idx) || 9369 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9370 return SDValue(); 9371 9372 SelectionDAG &DAG = DCI.DAG; 9373 SDLoc SL(N); 9374 SDValue Ins = N->getOperand(1); 9375 EVT IdxVT = Idx.getValueType(); 9376 9377 SmallVector<SDValue, 16> Ops; 9378 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9379 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9380 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9381 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9382 Ops.push_back(V); 9383 } 9384 9385 return DAG.getBuildVector(VecVT, SL, Ops); 9386 } 9387 9388 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9389 const SDNode *N0, 9390 const SDNode *N1) const { 9391 EVT VT = N0->getValueType(0); 9392 9393 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9394 // support denormals ever. 9395 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9396 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9397 getSubtarget()->hasMadF16())) && 9398 isOperationLegal(ISD::FMAD, VT)) 9399 return ISD::FMAD; 9400 9401 const TargetOptions &Options = DAG.getTarget().Options; 9402 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9403 (N0->getFlags().hasAllowContract() && 9404 N1->getFlags().hasAllowContract())) && 9405 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9406 return ISD::FMA; 9407 } 9408 9409 return 0; 9410 } 9411 9412 // For a reassociatable opcode perform: 9413 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9414 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9415 SelectionDAG &DAG) const { 9416 EVT VT = N->getValueType(0); 9417 if (VT != MVT::i32 && VT != MVT::i64) 9418 return SDValue(); 9419 9420 unsigned Opc = N->getOpcode(); 9421 SDValue Op0 = N->getOperand(0); 9422 SDValue Op1 = N->getOperand(1); 9423 9424 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9425 return SDValue(); 9426 9427 if (Op0->isDivergent()) 9428 std::swap(Op0, Op1); 9429 9430 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9431 return SDValue(); 9432 9433 SDValue Op2 = Op1.getOperand(1); 9434 Op1 = Op1.getOperand(0); 9435 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9436 return SDValue(); 9437 9438 if (Op1->isDivergent()) 9439 std::swap(Op1, Op2); 9440 9441 // If either operand is constant this will conflict with 9442 // DAGCombiner::ReassociateOps(). 9443 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9444 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9445 return SDValue(); 9446 9447 SDLoc SL(N); 9448 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9449 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9450 } 9451 9452 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9453 EVT VT, 9454 SDValue N0, SDValue N1, SDValue N2, 9455 bool Signed) { 9456 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9457 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9458 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9459 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9460 } 9461 9462 SDValue SITargetLowering::performAddCombine(SDNode *N, 9463 DAGCombinerInfo &DCI) const { 9464 SelectionDAG &DAG = DCI.DAG; 9465 EVT VT = N->getValueType(0); 9466 SDLoc SL(N); 9467 SDValue LHS = N->getOperand(0); 9468 SDValue RHS = N->getOperand(1); 9469 9470 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9471 && Subtarget->hasMad64_32() && 9472 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9473 VT.getScalarSizeInBits() <= 64) { 9474 if (LHS.getOpcode() != ISD::MUL) 9475 std::swap(LHS, RHS); 9476 9477 SDValue MulLHS = LHS.getOperand(0); 9478 SDValue MulRHS = LHS.getOperand(1); 9479 SDValue AddRHS = RHS; 9480 9481 // TODO: Maybe restrict if SGPR inputs. 9482 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9483 numBitsUnsigned(MulRHS, DAG) <= 32) { 9484 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9485 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9486 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9487 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9488 } 9489 9490 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9491 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9492 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9493 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9494 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9495 } 9496 9497 return SDValue(); 9498 } 9499 9500 if (SDValue V = reassociateScalarOps(N, DAG)) { 9501 return V; 9502 } 9503 9504 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9505 return SDValue(); 9506 9507 // add x, zext (setcc) => addcarry x, 0, setcc 9508 // add x, sext (setcc) => subcarry x, 0, setcc 9509 unsigned Opc = LHS.getOpcode(); 9510 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9511 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9512 std::swap(RHS, LHS); 9513 9514 Opc = RHS.getOpcode(); 9515 switch (Opc) { 9516 default: break; 9517 case ISD::ZERO_EXTEND: 9518 case ISD::SIGN_EXTEND: 9519 case ISD::ANY_EXTEND: { 9520 auto Cond = RHS.getOperand(0); 9521 // If this won't be a real VOPC output, we would still need to insert an 9522 // extra instruction anyway. 9523 if (!isBoolSGPR(Cond)) 9524 break; 9525 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9526 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9527 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9528 return DAG.getNode(Opc, SL, VTList, Args); 9529 } 9530 case ISD::ADDCARRY: { 9531 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9532 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9533 if (!C || C->getZExtValue() != 0) break; 9534 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9535 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9536 } 9537 } 9538 return SDValue(); 9539 } 9540 9541 SDValue SITargetLowering::performSubCombine(SDNode *N, 9542 DAGCombinerInfo &DCI) const { 9543 SelectionDAG &DAG = DCI.DAG; 9544 EVT VT = N->getValueType(0); 9545 9546 if (VT != MVT::i32) 9547 return SDValue(); 9548 9549 SDLoc SL(N); 9550 SDValue LHS = N->getOperand(0); 9551 SDValue RHS = N->getOperand(1); 9552 9553 // sub x, zext (setcc) => subcarry x, 0, setcc 9554 // sub x, sext (setcc) => addcarry x, 0, setcc 9555 unsigned Opc = RHS.getOpcode(); 9556 switch (Opc) { 9557 default: break; 9558 case ISD::ZERO_EXTEND: 9559 case ISD::SIGN_EXTEND: 9560 case ISD::ANY_EXTEND: { 9561 auto Cond = RHS.getOperand(0); 9562 // If this won't be a real VOPC output, we would still need to insert an 9563 // extra instruction anyway. 9564 if (!isBoolSGPR(Cond)) 9565 break; 9566 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9567 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9568 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9569 return DAG.getNode(Opc, SL, VTList, Args); 9570 } 9571 } 9572 9573 if (LHS.getOpcode() == ISD::SUBCARRY) { 9574 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9575 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9576 if (!C || !C->isNullValue()) 9577 return SDValue(); 9578 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9579 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9580 } 9581 return SDValue(); 9582 } 9583 9584 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9585 DAGCombinerInfo &DCI) const { 9586 9587 if (N->getValueType(0) != MVT::i32) 9588 return SDValue(); 9589 9590 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9591 if (!C || C->getZExtValue() != 0) 9592 return SDValue(); 9593 9594 SelectionDAG &DAG = DCI.DAG; 9595 SDValue LHS = N->getOperand(0); 9596 9597 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9598 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9599 unsigned LHSOpc = LHS.getOpcode(); 9600 unsigned Opc = N->getOpcode(); 9601 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9602 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9603 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9604 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9605 } 9606 return SDValue(); 9607 } 9608 9609 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9610 DAGCombinerInfo &DCI) const { 9611 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9612 return SDValue(); 9613 9614 SelectionDAG &DAG = DCI.DAG; 9615 EVT VT = N->getValueType(0); 9616 9617 SDLoc SL(N); 9618 SDValue LHS = N->getOperand(0); 9619 SDValue RHS = N->getOperand(1); 9620 9621 // These should really be instruction patterns, but writing patterns with 9622 // source modiifiers is a pain. 9623 9624 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9625 if (LHS.getOpcode() == ISD::FADD) { 9626 SDValue A = LHS.getOperand(0); 9627 if (A == LHS.getOperand(1)) { 9628 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9629 if (FusedOp != 0) { 9630 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9631 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9632 } 9633 } 9634 } 9635 9636 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9637 if (RHS.getOpcode() == ISD::FADD) { 9638 SDValue A = RHS.getOperand(0); 9639 if (A == RHS.getOperand(1)) { 9640 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9641 if (FusedOp != 0) { 9642 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9643 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9644 } 9645 } 9646 } 9647 9648 return SDValue(); 9649 } 9650 9651 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9652 DAGCombinerInfo &DCI) const { 9653 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9654 return SDValue(); 9655 9656 SelectionDAG &DAG = DCI.DAG; 9657 SDLoc SL(N); 9658 EVT VT = N->getValueType(0); 9659 assert(!VT.isVector()); 9660 9661 // Try to get the fneg to fold into the source modifier. This undoes generic 9662 // DAG combines and folds them into the mad. 9663 // 9664 // Only do this if we are not trying to support denormals. v_mad_f32 does 9665 // not support denormals ever. 9666 SDValue LHS = N->getOperand(0); 9667 SDValue RHS = N->getOperand(1); 9668 if (LHS.getOpcode() == ISD::FADD) { 9669 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9670 SDValue A = LHS.getOperand(0); 9671 if (A == LHS.getOperand(1)) { 9672 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9673 if (FusedOp != 0){ 9674 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9675 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9676 9677 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9678 } 9679 } 9680 } 9681 9682 if (RHS.getOpcode() == ISD::FADD) { 9683 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9684 9685 SDValue A = RHS.getOperand(0); 9686 if (A == RHS.getOperand(1)) { 9687 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9688 if (FusedOp != 0){ 9689 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9690 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9691 } 9692 } 9693 } 9694 9695 return SDValue(); 9696 } 9697 9698 SDValue SITargetLowering::performFMACombine(SDNode *N, 9699 DAGCombinerInfo &DCI) const { 9700 SelectionDAG &DAG = DCI.DAG; 9701 EVT VT = N->getValueType(0); 9702 SDLoc SL(N); 9703 9704 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9705 return SDValue(); 9706 9707 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9708 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9709 SDValue Op1 = N->getOperand(0); 9710 SDValue Op2 = N->getOperand(1); 9711 SDValue FMA = N->getOperand(2); 9712 9713 if (FMA.getOpcode() != ISD::FMA || 9714 Op1.getOpcode() != ISD::FP_EXTEND || 9715 Op2.getOpcode() != ISD::FP_EXTEND) 9716 return SDValue(); 9717 9718 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9719 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9720 // is sufficient to allow generaing fdot2. 9721 const TargetOptions &Options = DAG.getTarget().Options; 9722 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9723 (N->getFlags().hasAllowContract() && 9724 FMA->getFlags().hasAllowContract())) { 9725 Op1 = Op1.getOperand(0); 9726 Op2 = Op2.getOperand(0); 9727 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9728 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9729 return SDValue(); 9730 9731 SDValue Vec1 = Op1.getOperand(0); 9732 SDValue Idx1 = Op1.getOperand(1); 9733 SDValue Vec2 = Op2.getOperand(0); 9734 9735 SDValue FMAOp1 = FMA.getOperand(0); 9736 SDValue FMAOp2 = FMA.getOperand(1); 9737 SDValue FMAAcc = FMA.getOperand(2); 9738 9739 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9740 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9741 return SDValue(); 9742 9743 FMAOp1 = FMAOp1.getOperand(0); 9744 FMAOp2 = FMAOp2.getOperand(0); 9745 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9746 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9747 return SDValue(); 9748 9749 SDValue Vec3 = FMAOp1.getOperand(0); 9750 SDValue Vec4 = FMAOp2.getOperand(0); 9751 SDValue Idx2 = FMAOp1.getOperand(1); 9752 9753 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9754 // Idx1 and Idx2 cannot be the same. 9755 Idx1 == Idx2) 9756 return SDValue(); 9757 9758 if (Vec1 == Vec2 || Vec3 == Vec4) 9759 return SDValue(); 9760 9761 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9762 return SDValue(); 9763 9764 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9765 (Vec1 == Vec4 && Vec2 == Vec3)) { 9766 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9767 DAG.getTargetConstant(0, SL, MVT::i1)); 9768 } 9769 } 9770 return SDValue(); 9771 } 9772 9773 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9774 DAGCombinerInfo &DCI) const { 9775 SelectionDAG &DAG = DCI.DAG; 9776 SDLoc SL(N); 9777 9778 SDValue LHS = N->getOperand(0); 9779 SDValue RHS = N->getOperand(1); 9780 EVT VT = LHS.getValueType(); 9781 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9782 9783 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9784 if (!CRHS) { 9785 CRHS = dyn_cast<ConstantSDNode>(LHS); 9786 if (CRHS) { 9787 std::swap(LHS, RHS); 9788 CC = getSetCCSwappedOperands(CC); 9789 } 9790 } 9791 9792 if (CRHS) { 9793 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9794 isBoolSGPR(LHS.getOperand(0))) { 9795 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9796 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9797 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9798 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9799 if ((CRHS->isAllOnesValue() && 9800 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9801 (CRHS->isNullValue() && 9802 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9803 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9804 DAG.getConstant(-1, SL, MVT::i1)); 9805 if ((CRHS->isAllOnesValue() && 9806 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9807 (CRHS->isNullValue() && 9808 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9809 return LHS.getOperand(0); 9810 } 9811 9812 uint64_t CRHSVal = CRHS->getZExtValue(); 9813 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9814 LHS.getOpcode() == ISD::SELECT && 9815 isa<ConstantSDNode>(LHS.getOperand(1)) && 9816 isa<ConstantSDNode>(LHS.getOperand(2)) && 9817 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9818 isBoolSGPR(LHS.getOperand(0))) { 9819 // Given CT != FT: 9820 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9821 // setcc (select cc, CT, CF), CF, ne => cc 9822 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9823 // setcc (select cc, CT, CF), CT, eq => cc 9824 uint64_t CT = LHS.getConstantOperandVal(1); 9825 uint64_t CF = LHS.getConstantOperandVal(2); 9826 9827 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9828 (CT == CRHSVal && CC == ISD::SETNE)) 9829 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9830 DAG.getConstant(-1, SL, MVT::i1)); 9831 if ((CF == CRHSVal && CC == ISD::SETNE) || 9832 (CT == CRHSVal && CC == ISD::SETEQ)) 9833 return LHS.getOperand(0); 9834 } 9835 } 9836 9837 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9838 VT != MVT::f16)) 9839 return SDValue(); 9840 9841 // Match isinf/isfinite pattern 9842 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9843 // (fcmp one (fabs x), inf) -> (fp_class x, 9844 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9845 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9846 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9847 if (!CRHS) 9848 return SDValue(); 9849 9850 const APFloat &APF = CRHS->getValueAPF(); 9851 if (APF.isInfinity() && !APF.isNegative()) { 9852 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9853 SIInstrFlags::N_INFINITY; 9854 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9855 SIInstrFlags::P_ZERO | 9856 SIInstrFlags::N_NORMAL | 9857 SIInstrFlags::P_NORMAL | 9858 SIInstrFlags::N_SUBNORMAL | 9859 SIInstrFlags::P_SUBNORMAL; 9860 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9861 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9862 DAG.getConstant(Mask, SL, MVT::i32)); 9863 } 9864 } 9865 9866 return SDValue(); 9867 } 9868 9869 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9870 DAGCombinerInfo &DCI) const { 9871 SelectionDAG &DAG = DCI.DAG; 9872 SDLoc SL(N); 9873 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9874 9875 SDValue Src = N->getOperand(0); 9876 SDValue Srl = N->getOperand(0); 9877 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9878 Srl = Srl.getOperand(0); 9879 9880 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9881 if (Srl.getOpcode() == ISD::SRL) { 9882 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9883 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9884 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9885 9886 if (const ConstantSDNode *C = 9887 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9888 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9889 EVT(MVT::i32)); 9890 9891 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9892 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9893 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9894 MVT::f32, Srl); 9895 } 9896 } 9897 } 9898 9899 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9900 9901 KnownBits Known; 9902 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9903 !DCI.isBeforeLegalizeOps()); 9904 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9905 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9906 DCI.CommitTargetLoweringOpt(TLO); 9907 } 9908 9909 return SDValue(); 9910 } 9911 9912 SDValue SITargetLowering::performClampCombine(SDNode *N, 9913 DAGCombinerInfo &DCI) const { 9914 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9915 if (!CSrc) 9916 return SDValue(); 9917 9918 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9919 const APFloat &F = CSrc->getValueAPF(); 9920 APFloat Zero = APFloat::getZero(F.getSemantics()); 9921 APFloat::cmpResult Cmp0 = F.compare(Zero); 9922 if (Cmp0 == APFloat::cmpLessThan || 9923 (Cmp0 == APFloat::cmpUnordered && 9924 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9925 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9926 } 9927 9928 APFloat One(F.getSemantics(), "1.0"); 9929 APFloat::cmpResult Cmp1 = F.compare(One); 9930 if (Cmp1 == APFloat::cmpGreaterThan) 9931 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9932 9933 return SDValue(CSrc, 0); 9934 } 9935 9936 9937 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9938 DAGCombinerInfo &DCI) const { 9939 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9940 return SDValue(); 9941 switch (N->getOpcode()) { 9942 default: 9943 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9944 case ISD::ADD: 9945 return performAddCombine(N, DCI); 9946 case ISD::SUB: 9947 return performSubCombine(N, DCI); 9948 case ISD::ADDCARRY: 9949 case ISD::SUBCARRY: 9950 return performAddCarrySubCarryCombine(N, DCI); 9951 case ISD::FADD: 9952 return performFAddCombine(N, DCI); 9953 case ISD::FSUB: 9954 return performFSubCombine(N, DCI); 9955 case ISD::SETCC: 9956 return performSetCCCombine(N, DCI); 9957 case ISD::FMAXNUM: 9958 case ISD::FMINNUM: 9959 case ISD::FMAXNUM_IEEE: 9960 case ISD::FMINNUM_IEEE: 9961 case ISD::SMAX: 9962 case ISD::SMIN: 9963 case ISD::UMAX: 9964 case ISD::UMIN: 9965 case AMDGPUISD::FMIN_LEGACY: 9966 case AMDGPUISD::FMAX_LEGACY: 9967 return performMinMaxCombine(N, DCI); 9968 case ISD::FMA: 9969 return performFMACombine(N, DCI); 9970 case ISD::LOAD: { 9971 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9972 return Widended; 9973 LLVM_FALLTHROUGH; 9974 } 9975 case ISD::STORE: 9976 case ISD::ATOMIC_LOAD: 9977 case ISD::ATOMIC_STORE: 9978 case ISD::ATOMIC_CMP_SWAP: 9979 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9980 case ISD::ATOMIC_SWAP: 9981 case ISD::ATOMIC_LOAD_ADD: 9982 case ISD::ATOMIC_LOAD_SUB: 9983 case ISD::ATOMIC_LOAD_AND: 9984 case ISD::ATOMIC_LOAD_OR: 9985 case ISD::ATOMIC_LOAD_XOR: 9986 case ISD::ATOMIC_LOAD_NAND: 9987 case ISD::ATOMIC_LOAD_MIN: 9988 case ISD::ATOMIC_LOAD_MAX: 9989 case ISD::ATOMIC_LOAD_UMIN: 9990 case ISD::ATOMIC_LOAD_UMAX: 9991 case ISD::ATOMIC_LOAD_FADD: 9992 case AMDGPUISD::ATOMIC_INC: 9993 case AMDGPUISD::ATOMIC_DEC: 9994 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9995 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9996 if (DCI.isBeforeLegalize()) 9997 break; 9998 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9999 case ISD::AND: 10000 return performAndCombine(N, DCI); 10001 case ISD::OR: 10002 return performOrCombine(N, DCI); 10003 case ISD::XOR: 10004 return performXorCombine(N, DCI); 10005 case ISD::ZERO_EXTEND: 10006 return performZeroExtendCombine(N, DCI); 10007 case ISD::SIGN_EXTEND_INREG: 10008 return performSignExtendInRegCombine(N , DCI); 10009 case AMDGPUISD::FP_CLASS: 10010 return performClassCombine(N, DCI); 10011 case ISD::FCANONICALIZE: 10012 return performFCanonicalizeCombine(N, DCI); 10013 case AMDGPUISD::RCP: 10014 return performRcpCombine(N, DCI); 10015 case AMDGPUISD::FRACT: 10016 case AMDGPUISD::RSQ: 10017 case AMDGPUISD::RCP_LEGACY: 10018 case AMDGPUISD::RSQ_LEGACY: 10019 case AMDGPUISD::RCP_IFLAG: 10020 case AMDGPUISD::RSQ_CLAMP: 10021 case AMDGPUISD::LDEXP: { 10022 SDValue Src = N->getOperand(0); 10023 if (Src.isUndef()) 10024 return Src; 10025 break; 10026 } 10027 case ISD::SINT_TO_FP: 10028 case ISD::UINT_TO_FP: 10029 return performUCharToFloatCombine(N, DCI); 10030 case AMDGPUISD::CVT_F32_UBYTE0: 10031 case AMDGPUISD::CVT_F32_UBYTE1: 10032 case AMDGPUISD::CVT_F32_UBYTE2: 10033 case AMDGPUISD::CVT_F32_UBYTE3: 10034 return performCvtF32UByteNCombine(N, DCI); 10035 case AMDGPUISD::FMED3: 10036 return performFMed3Combine(N, DCI); 10037 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10038 return performCvtPkRTZCombine(N, DCI); 10039 case AMDGPUISD::CLAMP: 10040 return performClampCombine(N, DCI); 10041 case ISD::SCALAR_TO_VECTOR: { 10042 SelectionDAG &DAG = DCI.DAG; 10043 EVT VT = N->getValueType(0); 10044 10045 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10046 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10047 SDLoc SL(N); 10048 SDValue Src = N->getOperand(0); 10049 EVT EltVT = Src.getValueType(); 10050 if (EltVT == MVT::f16) 10051 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10052 10053 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10054 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10055 } 10056 10057 break; 10058 } 10059 case ISD::EXTRACT_VECTOR_ELT: 10060 return performExtractVectorEltCombine(N, DCI); 10061 case ISD::INSERT_VECTOR_ELT: 10062 return performInsertVectorEltCombine(N, DCI); 10063 } 10064 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10065 } 10066 10067 /// Helper function for adjustWritemask 10068 static unsigned SubIdx2Lane(unsigned Idx) { 10069 switch (Idx) { 10070 default: return 0; 10071 case AMDGPU::sub0: return 0; 10072 case AMDGPU::sub1: return 1; 10073 case AMDGPU::sub2: return 2; 10074 case AMDGPU::sub3: return 3; 10075 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10076 } 10077 } 10078 10079 /// Adjust the writemask of MIMG instructions 10080 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10081 SelectionDAG &DAG) const { 10082 unsigned Opcode = Node->getMachineOpcode(); 10083 10084 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10085 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10086 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10087 return Node; // not implemented for D16 10088 10089 SDNode *Users[5] = { nullptr }; 10090 unsigned Lane = 0; 10091 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10092 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10093 unsigned NewDmask = 0; 10094 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10095 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10096 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10097 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10098 unsigned TFCLane = 0; 10099 bool HasChain = Node->getNumValues() > 1; 10100 10101 if (OldDmask == 0) { 10102 // These are folded out, but on the chance it happens don't assert. 10103 return Node; 10104 } 10105 10106 unsigned OldBitsSet = countPopulation(OldDmask); 10107 // Work out which is the TFE/LWE lane if that is enabled. 10108 if (UsesTFC) { 10109 TFCLane = OldBitsSet; 10110 } 10111 10112 // Try to figure out the used register components 10113 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10114 I != E; ++I) { 10115 10116 // Don't look at users of the chain. 10117 if (I.getUse().getResNo() != 0) 10118 continue; 10119 10120 // Abort if we can't understand the usage 10121 if (!I->isMachineOpcode() || 10122 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10123 return Node; 10124 10125 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10126 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10127 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10128 // set, etc. 10129 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10130 10131 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10132 if (UsesTFC && Lane == TFCLane) { 10133 Users[Lane] = *I; 10134 } else { 10135 // Set which texture component corresponds to the lane. 10136 unsigned Comp; 10137 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10138 Comp = countTrailingZeros(Dmask); 10139 Dmask &= ~(1 << Comp); 10140 } 10141 10142 // Abort if we have more than one user per component. 10143 if (Users[Lane]) 10144 return Node; 10145 10146 Users[Lane] = *I; 10147 NewDmask |= 1 << Comp; 10148 } 10149 } 10150 10151 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10152 bool NoChannels = !NewDmask; 10153 if (NoChannels) { 10154 if (!UsesTFC) { 10155 // No uses of the result and not using TFC. Then do nothing. 10156 return Node; 10157 } 10158 // If the original dmask has one channel - then nothing to do 10159 if (OldBitsSet == 1) 10160 return Node; 10161 // Use an arbitrary dmask - required for the instruction to work 10162 NewDmask = 1; 10163 } 10164 // Abort if there's no change 10165 if (NewDmask == OldDmask) 10166 return Node; 10167 10168 unsigned BitsSet = countPopulation(NewDmask); 10169 10170 // Check for TFE or LWE - increase the number of channels by one to account 10171 // for the extra return value 10172 // This will need adjustment for D16 if this is also included in 10173 // adjustWriteMask (this function) but at present D16 are excluded. 10174 unsigned NewChannels = BitsSet + UsesTFC; 10175 10176 int NewOpcode = 10177 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10178 assert(NewOpcode != -1 && 10179 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10180 "failed to find equivalent MIMG op"); 10181 10182 // Adjust the writemask in the node 10183 SmallVector<SDValue, 12> Ops; 10184 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10185 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10186 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10187 10188 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10189 10190 MVT ResultVT = NewChannels == 1 ? 10191 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10192 NewChannels == 5 ? 8 : NewChannels); 10193 SDVTList NewVTList = HasChain ? 10194 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10195 10196 10197 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10198 NewVTList, Ops); 10199 10200 if (HasChain) { 10201 // Update chain. 10202 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10203 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10204 } 10205 10206 if (NewChannels == 1) { 10207 assert(Node->hasNUsesOfValue(1, 0)); 10208 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10209 SDLoc(Node), Users[Lane]->getValueType(0), 10210 SDValue(NewNode, 0)); 10211 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10212 return nullptr; 10213 } 10214 10215 // Update the users of the node with the new indices 10216 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10217 SDNode *User = Users[i]; 10218 if (!User) { 10219 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10220 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10221 if (i || !NoChannels) 10222 continue; 10223 } else { 10224 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10225 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10226 } 10227 10228 switch (Idx) { 10229 default: break; 10230 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10231 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10232 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10233 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10234 } 10235 } 10236 10237 DAG.RemoveDeadNode(Node); 10238 return nullptr; 10239 } 10240 10241 static bool isFrameIndexOp(SDValue Op) { 10242 if (Op.getOpcode() == ISD::AssertZext) 10243 Op = Op.getOperand(0); 10244 10245 return isa<FrameIndexSDNode>(Op); 10246 } 10247 10248 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10249 /// with frame index operands. 10250 /// LLVM assumes that inputs are to these instructions are registers. 10251 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10252 SelectionDAG &DAG) const { 10253 if (Node->getOpcode() == ISD::CopyToReg) { 10254 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10255 SDValue SrcVal = Node->getOperand(2); 10256 10257 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10258 // to try understanding copies to physical registers. 10259 if (SrcVal.getValueType() == MVT::i1 && 10260 Register::isPhysicalRegister(DestReg->getReg())) { 10261 SDLoc SL(Node); 10262 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10263 SDValue VReg = DAG.getRegister( 10264 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10265 10266 SDNode *Glued = Node->getGluedNode(); 10267 SDValue ToVReg 10268 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10269 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10270 SDValue ToResultReg 10271 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10272 VReg, ToVReg.getValue(1)); 10273 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10274 DAG.RemoveDeadNode(Node); 10275 return ToResultReg.getNode(); 10276 } 10277 } 10278 10279 SmallVector<SDValue, 8> Ops; 10280 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10281 if (!isFrameIndexOp(Node->getOperand(i))) { 10282 Ops.push_back(Node->getOperand(i)); 10283 continue; 10284 } 10285 10286 SDLoc DL(Node); 10287 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10288 Node->getOperand(i).getValueType(), 10289 Node->getOperand(i)), 0)); 10290 } 10291 10292 return DAG.UpdateNodeOperands(Node, Ops); 10293 } 10294 10295 /// Fold the instructions after selecting them. 10296 /// Returns null if users were already updated. 10297 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10298 SelectionDAG &DAG) const { 10299 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10300 unsigned Opcode = Node->getMachineOpcode(); 10301 10302 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10303 !TII->isGather4(Opcode)) { 10304 return adjustWritemask(Node, DAG); 10305 } 10306 10307 if (Opcode == AMDGPU::INSERT_SUBREG || 10308 Opcode == AMDGPU::REG_SEQUENCE) { 10309 legalizeTargetIndependentNode(Node, DAG); 10310 return Node; 10311 } 10312 10313 switch (Opcode) { 10314 case AMDGPU::V_DIV_SCALE_F32: 10315 case AMDGPU::V_DIV_SCALE_F64: { 10316 // Satisfy the operand register constraint when one of the inputs is 10317 // undefined. Ordinarily each undef value will have its own implicit_def of 10318 // a vreg, so force these to use a single register. 10319 SDValue Src0 = Node->getOperand(0); 10320 SDValue Src1 = Node->getOperand(1); 10321 SDValue Src2 = Node->getOperand(2); 10322 10323 if ((Src0.isMachineOpcode() && 10324 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10325 (Src0 == Src1 || Src0 == Src2)) 10326 break; 10327 10328 MVT VT = Src0.getValueType().getSimpleVT(); 10329 const TargetRegisterClass *RC = 10330 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10331 10332 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10333 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10334 10335 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10336 UndefReg, Src0, SDValue()); 10337 10338 // src0 must be the same register as src1 or src2, even if the value is 10339 // undefined, so make sure we don't violate this constraint. 10340 if (Src0.isMachineOpcode() && 10341 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10342 if (Src1.isMachineOpcode() && 10343 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10344 Src0 = Src1; 10345 else if (Src2.isMachineOpcode() && 10346 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10347 Src0 = Src2; 10348 else { 10349 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10350 Src0 = UndefReg; 10351 Src1 = UndefReg; 10352 } 10353 } else 10354 break; 10355 10356 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10357 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10358 Ops.push_back(Node->getOperand(I)); 10359 10360 Ops.push_back(ImpDef.getValue(1)); 10361 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10362 } 10363 default: 10364 break; 10365 } 10366 10367 return Node; 10368 } 10369 10370 /// Assign the register class depending on the number of 10371 /// bits set in the writemask 10372 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10373 SDNode *Node) const { 10374 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10375 10376 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10377 10378 if (TII->isVOP3(MI.getOpcode())) { 10379 // Make sure constant bus requirements are respected. 10380 TII->legalizeOperandsVOP3(MRI, MI); 10381 10382 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10383 // This saves a chain-copy of registers and better ballance register 10384 // use between vgpr and agpr as agpr tuples tend to be big. 10385 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10386 unsigned Opc = MI.getOpcode(); 10387 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10388 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10389 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10390 if (I == -1) 10391 break; 10392 MachineOperand &Op = MI.getOperand(I); 10393 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10394 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10395 !Register::isVirtualRegister(Op.getReg()) || 10396 !TRI->isAGPR(MRI, Op.getReg())) 10397 continue; 10398 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10399 if (!Src || !Src->isCopy() || 10400 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10401 continue; 10402 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10403 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10404 // All uses of agpr64 and agpr32 can also accept vgpr except for 10405 // v_accvgpr_read, but we do not produce agpr reads during selection, 10406 // so no use checks are needed. 10407 MRI.setRegClass(Op.getReg(), NewRC); 10408 } 10409 } 10410 10411 return; 10412 } 10413 10414 // Replace unused atomics with the no return version. 10415 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10416 if (NoRetAtomicOp != -1) { 10417 if (!Node->hasAnyUseOfValue(0)) { 10418 MI.setDesc(TII->get(NoRetAtomicOp)); 10419 MI.RemoveOperand(0); 10420 return; 10421 } 10422 10423 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10424 // instruction, because the return type of these instructions is a vec2 of 10425 // the memory type, so it can be tied to the input operand. 10426 // This means these instructions always have a use, so we need to add a 10427 // special case to check if the atomic has only one extract_subreg use, 10428 // which itself has no uses. 10429 if ((Node->hasNUsesOfValue(1, 0) && 10430 Node->use_begin()->isMachineOpcode() && 10431 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10432 !Node->use_begin()->hasAnyUseOfValue(0))) { 10433 Register Def = MI.getOperand(0).getReg(); 10434 10435 // Change this into a noret atomic. 10436 MI.setDesc(TII->get(NoRetAtomicOp)); 10437 MI.RemoveOperand(0); 10438 10439 // If we only remove the def operand from the atomic instruction, the 10440 // extract_subreg will be left with a use of a vreg without a def. 10441 // So we need to insert an implicit_def to avoid machine verifier 10442 // errors. 10443 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10444 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10445 } 10446 return; 10447 } 10448 } 10449 10450 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10451 uint64_t Val) { 10452 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10453 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10454 } 10455 10456 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10457 const SDLoc &DL, 10458 SDValue Ptr) const { 10459 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10460 10461 // Build the half of the subregister with the constants before building the 10462 // full 128-bit register. If we are building multiple resource descriptors, 10463 // this will allow CSEing of the 2-component register. 10464 const SDValue Ops0[] = { 10465 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10466 buildSMovImm32(DAG, DL, 0), 10467 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10468 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10469 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10470 }; 10471 10472 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10473 MVT::v2i32, Ops0), 0); 10474 10475 // Combine the constants and the pointer. 10476 const SDValue Ops1[] = { 10477 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10478 Ptr, 10479 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10480 SubRegHi, 10481 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10482 }; 10483 10484 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10485 } 10486 10487 /// Return a resource descriptor with the 'Add TID' bit enabled 10488 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10489 /// of the resource descriptor) to create an offset, which is added to 10490 /// the resource pointer. 10491 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10492 SDValue Ptr, uint32_t RsrcDword1, 10493 uint64_t RsrcDword2And3) const { 10494 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10495 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10496 if (RsrcDword1) { 10497 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10498 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10499 0); 10500 } 10501 10502 SDValue DataLo = buildSMovImm32(DAG, DL, 10503 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10504 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10505 10506 const SDValue Ops[] = { 10507 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10508 PtrLo, 10509 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10510 PtrHi, 10511 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10512 DataLo, 10513 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10514 DataHi, 10515 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10516 }; 10517 10518 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10519 } 10520 10521 //===----------------------------------------------------------------------===// 10522 // SI Inline Assembly Support 10523 //===----------------------------------------------------------------------===// 10524 10525 std::pair<unsigned, const TargetRegisterClass *> 10526 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10527 StringRef Constraint, 10528 MVT VT) const { 10529 const TargetRegisterClass *RC = nullptr; 10530 if (Constraint.size() == 1) { 10531 switch (Constraint[0]) { 10532 default: 10533 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10534 case 's': 10535 case 'r': 10536 switch (VT.getSizeInBits()) { 10537 default: 10538 return std::make_pair(0U, nullptr); 10539 case 32: 10540 case 16: 10541 RC = &AMDGPU::SReg_32RegClass; 10542 break; 10543 case 64: 10544 RC = &AMDGPU::SGPR_64RegClass; 10545 break; 10546 case 96: 10547 RC = &AMDGPU::SReg_96RegClass; 10548 break; 10549 case 128: 10550 RC = &AMDGPU::SGPR_128RegClass; 10551 break; 10552 case 160: 10553 RC = &AMDGPU::SReg_160RegClass; 10554 break; 10555 case 256: 10556 RC = &AMDGPU::SReg_256RegClass; 10557 break; 10558 case 512: 10559 RC = &AMDGPU::SReg_512RegClass; 10560 break; 10561 } 10562 break; 10563 case 'v': 10564 switch (VT.getSizeInBits()) { 10565 default: 10566 return std::make_pair(0U, nullptr); 10567 case 32: 10568 case 16: 10569 RC = &AMDGPU::VGPR_32RegClass; 10570 break; 10571 case 64: 10572 RC = &AMDGPU::VReg_64RegClass; 10573 break; 10574 case 96: 10575 RC = &AMDGPU::VReg_96RegClass; 10576 break; 10577 case 128: 10578 RC = &AMDGPU::VReg_128RegClass; 10579 break; 10580 case 160: 10581 RC = &AMDGPU::VReg_160RegClass; 10582 break; 10583 case 256: 10584 RC = &AMDGPU::VReg_256RegClass; 10585 break; 10586 case 512: 10587 RC = &AMDGPU::VReg_512RegClass; 10588 break; 10589 } 10590 break; 10591 case 'a': 10592 if (!Subtarget->hasMAIInsts()) 10593 break; 10594 switch (VT.getSizeInBits()) { 10595 default: 10596 return std::make_pair(0U, nullptr); 10597 case 32: 10598 case 16: 10599 RC = &AMDGPU::AGPR_32RegClass; 10600 break; 10601 case 64: 10602 RC = &AMDGPU::AReg_64RegClass; 10603 break; 10604 case 128: 10605 RC = &AMDGPU::AReg_128RegClass; 10606 break; 10607 case 512: 10608 RC = &AMDGPU::AReg_512RegClass; 10609 break; 10610 case 1024: 10611 RC = &AMDGPU::AReg_1024RegClass; 10612 // v32 types are not legal but we support them here. 10613 return std::make_pair(0U, RC); 10614 } 10615 break; 10616 } 10617 // We actually support i128, i16 and f16 as inline parameters 10618 // even if they are not reported as legal 10619 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10620 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10621 return std::make_pair(0U, RC); 10622 } 10623 10624 if (Constraint.size() > 1) { 10625 if (Constraint[1] == 'v') { 10626 RC = &AMDGPU::VGPR_32RegClass; 10627 } else if (Constraint[1] == 's') { 10628 RC = &AMDGPU::SGPR_32RegClass; 10629 } else if (Constraint[1] == 'a') { 10630 RC = &AMDGPU::AGPR_32RegClass; 10631 } 10632 10633 if (RC) { 10634 uint32_t Idx; 10635 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10636 if (!Failed && Idx < RC->getNumRegs()) 10637 return std::make_pair(RC->getRegister(Idx), RC); 10638 } 10639 } 10640 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10641 } 10642 10643 SITargetLowering::ConstraintType 10644 SITargetLowering::getConstraintType(StringRef Constraint) const { 10645 if (Constraint.size() == 1) { 10646 switch (Constraint[0]) { 10647 default: break; 10648 case 's': 10649 case 'v': 10650 case 'a': 10651 return C_RegisterClass; 10652 } 10653 } 10654 return TargetLowering::getConstraintType(Constraint); 10655 } 10656 10657 // Figure out which registers should be reserved for stack access. Only after 10658 // the function is legalized do we know all of the non-spill stack objects or if 10659 // calls are present. 10660 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10661 MachineRegisterInfo &MRI = MF.getRegInfo(); 10662 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10663 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10664 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10665 10666 if (Info->isEntryFunction()) { 10667 // Callable functions have fixed registers used for stack access. 10668 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10669 } 10670 10671 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10672 Info->getStackPtrOffsetReg())); 10673 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10674 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10675 10676 // We need to worry about replacing the default register with itself in case 10677 // of MIR testcases missing the MFI. 10678 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10679 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10680 10681 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10682 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10683 10684 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10685 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10686 Info->getScratchWaveOffsetReg()); 10687 } 10688 10689 Info->limitOccupancy(MF); 10690 10691 if (ST.isWave32() && !MF.empty()) { 10692 // Add VCC_HI def because many instructions marked as imp-use VCC where 10693 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10694 // having a use of undef. 10695 10696 const SIInstrInfo *TII = ST.getInstrInfo(); 10697 DebugLoc DL; 10698 10699 MachineBasicBlock &MBB = MF.front(); 10700 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10701 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10702 10703 for (auto &MBB : MF) { 10704 for (auto &MI : MBB) { 10705 TII->fixImplicitOperands(MI); 10706 } 10707 } 10708 } 10709 10710 TargetLoweringBase::finalizeLowering(MF); 10711 } 10712 10713 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10714 KnownBits &Known, 10715 const APInt &DemandedElts, 10716 const SelectionDAG &DAG, 10717 unsigned Depth) const { 10718 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10719 DAG, Depth); 10720 10721 // Set the high bits to zero based on the maximum allowed scratch size per 10722 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10723 // calculation won't overflow, so assume the sign bit is never set. 10724 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10725 } 10726 10727 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10728 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10729 const Align CacheLineAlign = Align(64); 10730 10731 // Pre-GFX10 target did not benefit from loop alignment 10732 if (!ML || DisableLoopAlignment || 10733 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10734 getSubtarget()->hasInstFwdPrefetchBug()) 10735 return PrefAlign; 10736 10737 // On GFX10 I$ is 4 x 64 bytes cache lines. 10738 // By default prefetcher keeps one cache line behind and reads two ahead. 10739 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10740 // behind and one ahead. 10741 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10742 // If loop fits 64 bytes it always spans no more than two cache lines and 10743 // does not need an alignment. 10744 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10745 // Else if loop is less or equal 192 bytes we need two lines behind. 10746 10747 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10748 const MachineBasicBlock *Header = ML->getHeader(); 10749 if (Header->getAlignment() != PrefAlign) 10750 return Header->getAlignment(); // Already processed. 10751 10752 unsigned LoopSize = 0; 10753 for (const MachineBasicBlock *MBB : ML->blocks()) { 10754 // If inner loop block is aligned assume in average half of the alignment 10755 // size to be added as nops. 10756 if (MBB != Header) 10757 LoopSize += MBB->getAlignment().value() / 2; 10758 10759 for (const MachineInstr &MI : *MBB) { 10760 LoopSize += TII->getInstSizeInBytes(MI); 10761 if (LoopSize > 192) 10762 return PrefAlign; 10763 } 10764 } 10765 10766 if (LoopSize <= 64) 10767 return PrefAlign; 10768 10769 if (LoopSize <= 128) 10770 return CacheLineAlign; 10771 10772 // If any of parent loops is surrounded by prefetch instructions do not 10773 // insert new for inner loop, which would reset parent's settings. 10774 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10775 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10776 auto I = Exit->getFirstNonDebugInstr(); 10777 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10778 return CacheLineAlign; 10779 } 10780 } 10781 10782 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10783 MachineBasicBlock *Exit = ML->getExitBlock(); 10784 10785 if (Pre && Exit) { 10786 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10787 TII->get(AMDGPU::S_INST_PREFETCH)) 10788 .addImm(1); // prefetch 2 lines behind PC 10789 10790 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10791 TII->get(AMDGPU::S_INST_PREFETCH)) 10792 .addImm(2); // prefetch 1 line behind PC 10793 } 10794 10795 return CacheLineAlign; 10796 } 10797 10798 LLVM_ATTRIBUTE_UNUSED 10799 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10800 assert(N->getOpcode() == ISD::CopyFromReg); 10801 do { 10802 // Follow the chain until we find an INLINEASM node. 10803 N = N->getOperand(0).getNode(); 10804 if (N->getOpcode() == ISD::INLINEASM || 10805 N->getOpcode() == ISD::INLINEASM_BR) 10806 return true; 10807 } while (N->getOpcode() == ISD::CopyFromReg); 10808 return false; 10809 } 10810 10811 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10812 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10813 { 10814 switch (N->getOpcode()) { 10815 case ISD::CopyFromReg: 10816 { 10817 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10818 const MachineFunction * MF = FLI->MF; 10819 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10820 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10821 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10822 unsigned Reg = R->getReg(); 10823 if (Register::isPhysicalRegister(Reg)) 10824 return !TRI.isSGPRReg(MRI, Reg); 10825 10826 if (MRI.isLiveIn(Reg)) { 10827 // workitem.id.x workitem.id.y workitem.id.z 10828 // Any VGPR formal argument is also considered divergent 10829 if (!TRI.isSGPRReg(MRI, Reg)) 10830 return true; 10831 // Formal arguments of non-entry functions 10832 // are conservatively considered divergent 10833 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10834 return true; 10835 return false; 10836 } 10837 const Value *V = FLI->getValueFromVirtualReg(Reg); 10838 if (V) 10839 return KDA->isDivergent(V); 10840 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10841 return !TRI.isSGPRReg(MRI, Reg); 10842 } 10843 break; 10844 case ISD::LOAD: { 10845 const LoadSDNode *L = cast<LoadSDNode>(N); 10846 unsigned AS = L->getAddressSpace(); 10847 // A flat load may access private memory. 10848 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10849 } break; 10850 case ISD::CALLSEQ_END: 10851 return true; 10852 break; 10853 case ISD::INTRINSIC_WO_CHAIN: 10854 { 10855 10856 } 10857 return AMDGPU::isIntrinsicSourceOfDivergence( 10858 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10859 case ISD::INTRINSIC_W_CHAIN: 10860 return AMDGPU::isIntrinsicSourceOfDivergence( 10861 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10862 } 10863 return false; 10864 } 10865 10866 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10867 EVT VT) const { 10868 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10869 case MVT::f32: 10870 return hasFP32Denormals(DAG.getMachineFunction()); 10871 case MVT::f64: 10872 case MVT::f16: 10873 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10874 default: 10875 return false; 10876 } 10877 } 10878 10879 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10880 const SelectionDAG &DAG, 10881 bool SNaN, 10882 unsigned Depth) const { 10883 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10884 const MachineFunction &MF = DAG.getMachineFunction(); 10885 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10886 10887 if (Info->getMode().DX10Clamp) 10888 return true; // Clamped to 0. 10889 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10890 } 10891 10892 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10893 SNaN, Depth); 10894 } 10895 10896 TargetLowering::AtomicExpansionKind 10897 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10898 switch (RMW->getOperation()) { 10899 case AtomicRMWInst::FAdd: { 10900 Type *Ty = RMW->getType(); 10901 10902 // We don't have a way to support 16-bit atomics now, so just leave them 10903 // as-is. 10904 if (Ty->isHalfTy()) 10905 return AtomicExpansionKind::None; 10906 10907 if (!Ty->isFloatTy()) 10908 return AtomicExpansionKind::CmpXChg; 10909 10910 // TODO: Do have these for flat. Older targets also had them for buffers. 10911 unsigned AS = RMW->getPointerAddressSpace(); 10912 10913 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10914 return RMW->use_empty() ? AtomicExpansionKind::None : 10915 AtomicExpansionKind::CmpXChg; 10916 } 10917 10918 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10919 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10920 } 10921 default: 10922 break; 10923 } 10924 10925 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10926 } 10927 10928 const TargetRegisterClass * 10929 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10930 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10931 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10932 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10933 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10934 : &AMDGPU::SReg_32RegClass; 10935 if (!TRI->isSGPRClass(RC) && !isDivergent) 10936 return TRI->getEquivalentSGPRClass(RC); 10937 else if (TRI->isSGPRClass(RC) && isDivergent) 10938 return TRI->getEquivalentVGPRClass(RC); 10939 10940 return RC; 10941 } 10942 10943 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) { 10944 if (!isa<Instruction>(V)) 10945 return false; 10946 if (!Visited.insert(V).second) 10947 return false; 10948 bool Result = false; 10949 for (auto U : V->users()) { 10950 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10951 if (V == U->getOperand(1)) { 10952 switch (Intrinsic->getIntrinsicID()) { 10953 default: 10954 Result = false; 10955 break; 10956 case Intrinsic::amdgcn_if_break: 10957 case Intrinsic::amdgcn_if: 10958 case Intrinsic::amdgcn_else: 10959 Result = true; 10960 break; 10961 } 10962 } 10963 if (V == U->getOperand(0)) { 10964 switch (Intrinsic->getIntrinsicID()) { 10965 default: 10966 Result = false; 10967 break; 10968 case Intrinsic::amdgcn_end_cf: 10969 case Intrinsic::amdgcn_loop: 10970 Result = true; 10971 break; 10972 } 10973 } 10974 } else { 10975 Result = hasCFUser(U, Visited); 10976 } 10977 if (Result) 10978 break; 10979 } 10980 return Result; 10981 } 10982 10983 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 10984 const Value *V) const { 10985 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 10986 switch (Intrinsic->getIntrinsicID()) { 10987 default: 10988 return false; 10989 case Intrinsic::amdgcn_if_break: 10990 return true; 10991 } 10992 } 10993 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 10994 if (const IntrinsicInst *Intrinsic = 10995 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 10996 switch (Intrinsic->getIntrinsicID()) { 10997 default: 10998 return false; 10999 case Intrinsic::amdgcn_if: 11000 case Intrinsic::amdgcn_else: { 11001 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 11002 if (Indices.size() == 1 && Indices[0] == 1) { 11003 return true; 11004 } 11005 } 11006 } 11007 } 11008 } 11009 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11010 if (isa<InlineAsm>(CI->getCalledValue())) { 11011 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11012 ImmutableCallSite CS(CI); 11013 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11014 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 11015 for (auto &TC : TargetConstraints) { 11016 if (TC.Type == InlineAsm::isOutput) { 11017 ComputeConstraintToUse(TC, SDValue()); 11018 unsigned AssignedReg; 11019 const TargetRegisterClass *RC; 11020 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11021 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11022 if (RC) { 11023 MachineRegisterInfo &MRI = MF.getRegInfo(); 11024 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11025 return true; 11026 else if (SIRI->isSGPRClass(RC)) 11027 return true; 11028 } 11029 } 11030 } 11031 } 11032 } 11033 SmallPtrSet<const Value *, 16> Visited; 11034 return hasCFUser(V, Visited); 11035 } 11036