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 getMOVRELDPseudo(const SIRegisterInfo &TRI, 3469 const TargetRegisterClass *VecRC) { 3470 switch (TRI.getRegSizeInBits(*VecRC)) { 3471 case 32: // 4 bytes 3472 return AMDGPU::V_MOVRELD_B32_V1; 3473 case 64: // 8 bytes 3474 return AMDGPU::V_MOVRELD_B32_V2; 3475 case 128: // 16 bytes 3476 return AMDGPU::V_MOVRELD_B32_V4; 3477 case 256: // 32 bytes 3478 return AMDGPU::V_MOVRELD_B32_V8; 3479 case 512: // 64 bytes 3480 return AMDGPU::V_MOVRELD_B32_V16; 3481 default: 3482 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3483 } 3484 } 3485 3486 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3487 MachineBasicBlock &MBB, 3488 const GCNSubtarget &ST) { 3489 const SIInstrInfo *TII = ST.getInstrInfo(); 3490 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3491 MachineFunction *MF = MBB.getParent(); 3492 MachineRegisterInfo &MRI = MF->getRegInfo(); 3493 3494 Register Dst = MI.getOperand(0).getReg(); 3495 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3496 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3497 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3498 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3499 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3500 3501 // This can be an immediate, but will be folded later. 3502 assert(Val->getReg()); 3503 3504 unsigned SubReg; 3505 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3506 SrcVec->getReg(), 3507 Offset); 3508 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3509 3510 if (Idx->getReg() == AMDGPU::NoRegister) { 3511 MachineBasicBlock::iterator I(&MI); 3512 const DebugLoc &DL = MI.getDebugLoc(); 3513 3514 assert(Offset == 0); 3515 3516 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3517 .add(*SrcVec) 3518 .add(*Val) 3519 .addImm(SubReg); 3520 3521 MI.eraseFromParent(); 3522 return &MBB; 3523 } 3524 3525 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3526 MachineBasicBlock::iterator I(&MI); 3527 const DebugLoc &DL = MI.getDebugLoc(); 3528 3529 if (UseGPRIdxMode) { 3530 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3531 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3532 .add(*Val) 3533 .addReg(Dst, RegState::ImplicitDefine) 3534 .addReg(SrcVec->getReg(), RegState::Implicit) 3535 .addReg(AMDGPU::M0, RegState::Implicit); 3536 3537 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3538 } else { 3539 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3540 3541 BuildMI(MBB, I, DL, MovRelDesc) 3542 .addReg(Dst, RegState::Define) 3543 .addReg(SrcVec->getReg()) 3544 .add(*Val) 3545 .addImm(SubReg - AMDGPU::sub0); 3546 } 3547 3548 MI.eraseFromParent(); 3549 return &MBB; 3550 } 3551 3552 if (Val->isReg()) 3553 MRI.clearKillFlags(Val->getReg()); 3554 3555 const DebugLoc &DL = MI.getDebugLoc(); 3556 3557 Register PhiReg = MRI.createVirtualRegister(VecRC); 3558 3559 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3560 Offset, UseGPRIdxMode, false); 3561 MachineBasicBlock *LoopBB = InsPt->getParent(); 3562 3563 if (UseGPRIdxMode) { 3564 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3565 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3566 .add(*Val) // src0 3567 .addReg(Dst, RegState::ImplicitDefine) 3568 .addReg(PhiReg, RegState::Implicit) 3569 .addReg(AMDGPU::M0, RegState::Implicit); 3570 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3571 } else { 3572 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3573 3574 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3575 .addReg(Dst, RegState::Define) 3576 .addReg(PhiReg) 3577 .add(*Val) 3578 .addImm(SubReg - AMDGPU::sub0); 3579 } 3580 3581 MI.eraseFromParent(); 3582 3583 return LoopBB; 3584 } 3585 3586 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3587 MachineInstr &MI, MachineBasicBlock *BB) const { 3588 3589 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3590 MachineFunction *MF = BB->getParent(); 3591 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3592 3593 if (TII->isMIMG(MI)) { 3594 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3595 report_fatal_error("missing mem operand from MIMG instruction"); 3596 } 3597 // Add a memoperand for mimg instructions so that they aren't assumed to 3598 // be ordered memory instuctions. 3599 3600 return BB; 3601 } 3602 3603 switch (MI.getOpcode()) { 3604 case AMDGPU::S_ADD_U64_PSEUDO: 3605 case AMDGPU::S_SUB_U64_PSEUDO: { 3606 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3607 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3608 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3609 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3610 const DebugLoc &DL = MI.getDebugLoc(); 3611 3612 MachineOperand &Dest = MI.getOperand(0); 3613 MachineOperand &Src0 = MI.getOperand(1); 3614 MachineOperand &Src1 = MI.getOperand(2); 3615 3616 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3617 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3618 3619 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3620 Src0, BoolRC, AMDGPU::sub0, 3621 &AMDGPU::SReg_32RegClass); 3622 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3623 Src0, BoolRC, AMDGPU::sub1, 3624 &AMDGPU::SReg_32RegClass); 3625 3626 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3627 Src1, BoolRC, AMDGPU::sub0, 3628 &AMDGPU::SReg_32RegClass); 3629 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3630 Src1, BoolRC, AMDGPU::sub1, 3631 &AMDGPU::SReg_32RegClass); 3632 3633 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3634 3635 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3636 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3637 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3638 .add(Src0Sub0) 3639 .add(Src1Sub0); 3640 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3641 .add(Src0Sub1) 3642 .add(Src1Sub1); 3643 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3644 .addReg(DestSub0) 3645 .addImm(AMDGPU::sub0) 3646 .addReg(DestSub1) 3647 .addImm(AMDGPU::sub1); 3648 MI.eraseFromParent(); 3649 return BB; 3650 } 3651 case AMDGPU::SI_INIT_M0: { 3652 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3653 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3654 .add(MI.getOperand(0)); 3655 MI.eraseFromParent(); 3656 return BB; 3657 } 3658 case AMDGPU::SI_INIT_EXEC: 3659 // This should be before all vector instructions. 3660 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3661 AMDGPU::EXEC) 3662 .addImm(MI.getOperand(0).getImm()); 3663 MI.eraseFromParent(); 3664 return BB; 3665 3666 case AMDGPU::SI_INIT_EXEC_LO: 3667 // This should be before all vector instructions. 3668 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3669 AMDGPU::EXEC_LO) 3670 .addImm(MI.getOperand(0).getImm()); 3671 MI.eraseFromParent(); 3672 return BB; 3673 3674 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3675 // Extract the thread count from an SGPR input and set EXEC accordingly. 3676 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3677 // 3678 // S_BFE_U32 count, input, {shift, 7} 3679 // S_BFM_B64 exec, count, 0 3680 // S_CMP_EQ_U32 count, 64 3681 // S_CMOV_B64 exec, -1 3682 MachineInstr *FirstMI = &*BB->begin(); 3683 MachineRegisterInfo &MRI = MF->getRegInfo(); 3684 Register InputReg = MI.getOperand(0).getReg(); 3685 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3686 bool Found = false; 3687 3688 // Move the COPY of the input reg to the beginning, so that we can use it. 3689 for (auto I = BB->begin(); I != &MI; I++) { 3690 if (I->getOpcode() != TargetOpcode::COPY || 3691 I->getOperand(0).getReg() != InputReg) 3692 continue; 3693 3694 if (I == FirstMI) { 3695 FirstMI = &*++BB->begin(); 3696 } else { 3697 I->removeFromParent(); 3698 BB->insert(FirstMI, &*I); 3699 } 3700 Found = true; 3701 break; 3702 } 3703 assert(Found); 3704 (void)Found; 3705 3706 // This should be before all vector instructions. 3707 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3708 bool isWave32 = getSubtarget()->isWave32(); 3709 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3710 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3711 .addReg(InputReg) 3712 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3713 BuildMI(*BB, FirstMI, DebugLoc(), 3714 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3715 Exec) 3716 .addReg(CountReg) 3717 .addImm(0); 3718 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3719 .addReg(CountReg, RegState::Kill) 3720 .addImm(getSubtarget()->getWavefrontSize()); 3721 BuildMI(*BB, FirstMI, DebugLoc(), 3722 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3723 Exec) 3724 .addImm(-1); 3725 MI.eraseFromParent(); 3726 return BB; 3727 } 3728 3729 case AMDGPU::GET_GROUPSTATICSIZE: { 3730 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3731 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3732 DebugLoc DL = MI.getDebugLoc(); 3733 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3734 .add(MI.getOperand(0)) 3735 .addImm(MFI->getLDSSize()); 3736 MI.eraseFromParent(); 3737 return BB; 3738 } 3739 case AMDGPU::SI_INDIRECT_SRC_V1: 3740 case AMDGPU::SI_INDIRECT_SRC_V2: 3741 case AMDGPU::SI_INDIRECT_SRC_V4: 3742 case AMDGPU::SI_INDIRECT_SRC_V8: 3743 case AMDGPU::SI_INDIRECT_SRC_V16: 3744 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3745 case AMDGPU::SI_INDIRECT_DST_V1: 3746 case AMDGPU::SI_INDIRECT_DST_V2: 3747 case AMDGPU::SI_INDIRECT_DST_V4: 3748 case AMDGPU::SI_INDIRECT_DST_V8: 3749 case AMDGPU::SI_INDIRECT_DST_V16: 3750 return emitIndirectDst(MI, *BB, *getSubtarget()); 3751 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3752 case AMDGPU::SI_KILL_I1_PSEUDO: 3753 return splitKillBlock(MI, BB); 3754 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3755 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3756 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3757 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3758 3759 Register Dst = MI.getOperand(0).getReg(); 3760 Register Src0 = MI.getOperand(1).getReg(); 3761 Register Src1 = MI.getOperand(2).getReg(); 3762 const DebugLoc &DL = MI.getDebugLoc(); 3763 Register SrcCond = MI.getOperand(3).getReg(); 3764 3765 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3766 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3767 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3768 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3769 3770 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3771 .addReg(SrcCond); 3772 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3773 .addImm(0) 3774 .addReg(Src0, 0, AMDGPU::sub0) 3775 .addImm(0) 3776 .addReg(Src1, 0, AMDGPU::sub0) 3777 .addReg(SrcCondCopy); 3778 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3779 .addImm(0) 3780 .addReg(Src0, 0, AMDGPU::sub1) 3781 .addImm(0) 3782 .addReg(Src1, 0, AMDGPU::sub1) 3783 .addReg(SrcCondCopy); 3784 3785 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3786 .addReg(DstLo) 3787 .addImm(AMDGPU::sub0) 3788 .addReg(DstHi) 3789 .addImm(AMDGPU::sub1); 3790 MI.eraseFromParent(); 3791 return BB; 3792 } 3793 case AMDGPU::SI_BR_UNDEF: { 3794 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3795 const DebugLoc &DL = MI.getDebugLoc(); 3796 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3797 .add(MI.getOperand(0)); 3798 Br->getOperand(1).setIsUndef(true); // read undef SCC 3799 MI.eraseFromParent(); 3800 return BB; 3801 } 3802 case AMDGPU::ADJCALLSTACKUP: 3803 case AMDGPU::ADJCALLSTACKDOWN: { 3804 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3805 MachineInstrBuilder MIB(*MF, &MI); 3806 3807 // Add an implicit use of the frame offset reg to prevent the restore copy 3808 // inserted after the call from being reorderd after stack operations in the 3809 // the caller's frame. 3810 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3811 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3812 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3813 return BB; 3814 } 3815 case AMDGPU::SI_CALL_ISEL: { 3816 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3817 const DebugLoc &DL = MI.getDebugLoc(); 3818 3819 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3820 3821 MachineInstrBuilder MIB; 3822 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3823 3824 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3825 MIB.add(MI.getOperand(I)); 3826 3827 MIB.cloneMemRefs(MI); 3828 MI.eraseFromParent(); 3829 return BB; 3830 } 3831 case AMDGPU::V_ADD_I32_e32: 3832 case AMDGPU::V_SUB_I32_e32: 3833 case AMDGPU::V_SUBREV_I32_e32: { 3834 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3835 const DebugLoc &DL = MI.getDebugLoc(); 3836 unsigned Opc = MI.getOpcode(); 3837 3838 bool NeedClampOperand = false; 3839 if (TII->pseudoToMCOpcode(Opc) == -1) { 3840 Opc = AMDGPU::getVOPe64(Opc); 3841 NeedClampOperand = true; 3842 } 3843 3844 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3845 if (TII->isVOP3(*I)) { 3846 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3847 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3848 I.addReg(TRI->getVCC(), RegState::Define); 3849 } 3850 I.add(MI.getOperand(1)) 3851 .add(MI.getOperand(2)); 3852 if (NeedClampOperand) 3853 I.addImm(0); // clamp bit for e64 encoding 3854 3855 TII->legalizeOperands(*I); 3856 3857 MI.eraseFromParent(); 3858 return BB; 3859 } 3860 case AMDGPU::DS_GWS_INIT: 3861 case AMDGPU::DS_GWS_SEMA_V: 3862 case AMDGPU::DS_GWS_SEMA_BR: 3863 case AMDGPU::DS_GWS_SEMA_P: 3864 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3865 case AMDGPU::DS_GWS_BARRIER: 3866 // A s_waitcnt 0 is required to be the instruction immediately following. 3867 if (getSubtarget()->hasGWSAutoReplay()) { 3868 bundleInstWithWaitcnt(MI); 3869 return BB; 3870 } 3871 3872 return emitGWSMemViolTestLoop(MI, BB); 3873 default: 3874 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3875 } 3876 } 3877 3878 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3879 return isTypeLegal(VT.getScalarType()); 3880 } 3881 3882 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3883 // This currently forces unfolding various combinations of fsub into fma with 3884 // free fneg'd operands. As long as we have fast FMA (controlled by 3885 // isFMAFasterThanFMulAndFAdd), we should perform these. 3886 3887 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3888 // most of these combines appear to be cycle neutral but save on instruction 3889 // count / code size. 3890 return true; 3891 } 3892 3893 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3894 EVT VT) const { 3895 if (!VT.isVector()) { 3896 return MVT::i1; 3897 } 3898 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3899 } 3900 3901 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3902 // TODO: Should i16 be used always if legal? For now it would force VALU 3903 // shifts. 3904 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3905 } 3906 3907 // Answering this is somewhat tricky and depends on the specific device which 3908 // have different rates for fma or all f64 operations. 3909 // 3910 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3911 // regardless of which device (although the number of cycles differs between 3912 // devices), so it is always profitable for f64. 3913 // 3914 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3915 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3916 // which we can always do even without fused FP ops since it returns the same 3917 // result as the separate operations and since it is always full 3918 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3919 // however does not support denormals, so we do report fma as faster if we have 3920 // a fast fma device and require denormals. 3921 // 3922 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3923 EVT VT) const { 3924 VT = VT.getScalarType(); 3925 3926 switch (VT.getSimpleVT().SimpleTy) { 3927 case MVT::f32: { 3928 // This is as fast on some subtargets. However, we always have full rate f32 3929 // mad available which returns the same result as the separate operations 3930 // which we should prefer over fma. We can't use this if we want to support 3931 // denormals, so only report this in these cases. 3932 if (hasFP32Denormals(MF)) 3933 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3934 3935 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3936 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3937 } 3938 case MVT::f64: 3939 return true; 3940 case MVT::f16: 3941 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3942 default: 3943 break; 3944 } 3945 3946 return false; 3947 } 3948 3949 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3950 const SDNode *N) const { 3951 // TODO: Check future ftz flag 3952 // v_mad_f32/v_mac_f32 do not support denormals. 3953 EVT VT = N->getValueType(0); 3954 if (VT == MVT::f32) 3955 return !hasFP32Denormals(DAG.getMachineFunction()); 3956 if (VT == MVT::f16) { 3957 return Subtarget->hasMadF16() && 3958 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3959 } 3960 3961 return false; 3962 } 3963 3964 //===----------------------------------------------------------------------===// 3965 // Custom DAG Lowering Operations 3966 //===----------------------------------------------------------------------===// 3967 3968 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3969 // wider vector type is legal. 3970 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3971 SelectionDAG &DAG) const { 3972 unsigned Opc = Op.getOpcode(); 3973 EVT VT = Op.getValueType(); 3974 assert(VT == MVT::v4f16); 3975 3976 SDValue Lo, Hi; 3977 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3978 3979 SDLoc SL(Op); 3980 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3981 Op->getFlags()); 3982 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3983 Op->getFlags()); 3984 3985 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3986 } 3987 3988 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3989 // wider vector type is legal. 3990 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3991 SelectionDAG &DAG) const { 3992 unsigned Opc = Op.getOpcode(); 3993 EVT VT = Op.getValueType(); 3994 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3995 3996 SDValue Lo0, Hi0; 3997 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3998 SDValue Lo1, Hi1; 3999 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4000 4001 SDLoc SL(Op); 4002 4003 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4004 Op->getFlags()); 4005 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4006 Op->getFlags()); 4007 4008 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4009 } 4010 4011 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4012 SelectionDAG &DAG) const { 4013 unsigned Opc = Op.getOpcode(); 4014 EVT VT = Op.getValueType(); 4015 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4016 4017 SDValue Lo0, Hi0; 4018 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4019 SDValue Lo1, Hi1; 4020 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4021 SDValue Lo2, Hi2; 4022 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4023 4024 SDLoc SL(Op); 4025 4026 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4027 Op->getFlags()); 4028 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4029 Op->getFlags()); 4030 4031 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4032 } 4033 4034 4035 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4036 switch (Op.getOpcode()) { 4037 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4038 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4039 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4040 case ISD::LOAD: { 4041 SDValue Result = LowerLOAD(Op, DAG); 4042 assert((!Result.getNode() || 4043 Result.getNode()->getNumValues() == 2) && 4044 "Load should return a value and a chain"); 4045 return Result; 4046 } 4047 4048 case ISD::FSIN: 4049 case ISD::FCOS: 4050 return LowerTrig(Op, DAG); 4051 case ISD::SELECT: return LowerSELECT(Op, DAG); 4052 case ISD::FDIV: return LowerFDIV(Op, DAG); 4053 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4054 case ISD::STORE: return LowerSTORE(Op, DAG); 4055 case ISD::GlobalAddress: { 4056 MachineFunction &MF = DAG.getMachineFunction(); 4057 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4058 return LowerGlobalAddress(MFI, Op, DAG); 4059 } 4060 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4061 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4062 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4063 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4064 case ISD::INSERT_SUBVECTOR: 4065 return lowerINSERT_SUBVECTOR(Op, DAG); 4066 case ISD::INSERT_VECTOR_ELT: 4067 return lowerINSERT_VECTOR_ELT(Op, DAG); 4068 case ISD::EXTRACT_VECTOR_ELT: 4069 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4070 case ISD::VECTOR_SHUFFLE: 4071 return lowerVECTOR_SHUFFLE(Op, DAG); 4072 case ISD::BUILD_VECTOR: 4073 return lowerBUILD_VECTOR(Op, DAG); 4074 case ISD::FP_ROUND: 4075 return lowerFP_ROUND(Op, DAG); 4076 case ISD::TRAP: 4077 return lowerTRAP(Op, DAG); 4078 case ISD::DEBUGTRAP: 4079 return lowerDEBUGTRAP(Op, DAG); 4080 case ISD::FABS: 4081 case ISD::FNEG: 4082 case ISD::FCANONICALIZE: 4083 return splitUnaryVectorOp(Op, DAG); 4084 case ISD::FMINNUM: 4085 case ISD::FMAXNUM: 4086 return lowerFMINNUM_FMAXNUM(Op, DAG); 4087 case ISD::FMA: 4088 return splitTernaryVectorOp(Op, DAG); 4089 case ISD::SHL: 4090 case ISD::SRA: 4091 case ISD::SRL: 4092 case ISD::ADD: 4093 case ISD::SUB: 4094 case ISD::MUL: 4095 case ISD::SMIN: 4096 case ISD::SMAX: 4097 case ISD::UMIN: 4098 case ISD::UMAX: 4099 case ISD::FADD: 4100 case ISD::FMUL: 4101 case ISD::FMINNUM_IEEE: 4102 case ISD::FMAXNUM_IEEE: 4103 return splitBinaryVectorOp(Op, DAG); 4104 } 4105 return SDValue(); 4106 } 4107 4108 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4109 const SDLoc &DL, 4110 SelectionDAG &DAG, bool Unpacked) { 4111 if (!LoadVT.isVector()) 4112 return Result; 4113 4114 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4115 // Truncate to v2i16/v4i16. 4116 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4117 4118 // Workaround legalizer not scalarizing truncate after vector op 4119 // legalization byt not creating intermediate vector trunc. 4120 SmallVector<SDValue, 4> Elts; 4121 DAG.ExtractVectorElements(Result, Elts); 4122 for (SDValue &Elt : Elts) 4123 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4124 4125 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4126 4127 // Bitcast to original type (v2f16/v4f16). 4128 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4129 } 4130 4131 // Cast back to the original packed type. 4132 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4133 } 4134 4135 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4136 MemSDNode *M, 4137 SelectionDAG &DAG, 4138 ArrayRef<SDValue> Ops, 4139 bool IsIntrinsic) const { 4140 SDLoc DL(M); 4141 4142 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4143 EVT LoadVT = M->getValueType(0); 4144 4145 EVT EquivLoadVT = LoadVT; 4146 if (Unpacked && LoadVT.isVector()) { 4147 EquivLoadVT = LoadVT.isVector() ? 4148 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4149 LoadVT.getVectorNumElements()) : LoadVT; 4150 } 4151 4152 // Change from v4f16/v2f16 to EquivLoadVT. 4153 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4154 4155 SDValue Load 4156 = DAG.getMemIntrinsicNode( 4157 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4158 VTList, Ops, M->getMemoryVT(), 4159 M->getMemOperand()); 4160 if (!Unpacked) // Just adjusted the opcode. 4161 return Load; 4162 4163 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4164 4165 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4166 } 4167 4168 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4169 SelectionDAG &DAG, 4170 ArrayRef<SDValue> Ops) const { 4171 SDLoc DL(M); 4172 EVT LoadVT = M->getValueType(0); 4173 EVT EltType = LoadVT.getScalarType(); 4174 EVT IntVT = LoadVT.changeTypeToInteger(); 4175 4176 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4177 4178 unsigned Opc = 4179 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4180 4181 if (IsD16) { 4182 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4183 } 4184 4185 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4186 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4187 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4188 4189 if (isTypeLegal(LoadVT)) { 4190 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4191 M->getMemOperand(), DAG); 4192 } 4193 4194 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4195 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4196 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4197 M->getMemOperand(), DAG); 4198 return DAG.getMergeValues( 4199 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4200 DL); 4201 } 4202 4203 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4204 SDNode *N, SelectionDAG &DAG) { 4205 EVT VT = N->getValueType(0); 4206 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4207 int CondCode = CD->getSExtValue(); 4208 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4209 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4210 return DAG.getUNDEF(VT); 4211 4212 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4213 4214 SDValue LHS = N->getOperand(1); 4215 SDValue RHS = N->getOperand(2); 4216 4217 SDLoc DL(N); 4218 4219 EVT CmpVT = LHS.getValueType(); 4220 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4221 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4222 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4223 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4224 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4225 } 4226 4227 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4228 4229 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4230 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4231 4232 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4233 DAG.getCondCode(CCOpcode)); 4234 if (VT.bitsEq(CCVT)) 4235 return SetCC; 4236 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4237 } 4238 4239 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4240 SDNode *N, SelectionDAG &DAG) { 4241 EVT VT = N->getValueType(0); 4242 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4243 4244 int CondCode = CD->getSExtValue(); 4245 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4246 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4247 return DAG.getUNDEF(VT); 4248 } 4249 4250 SDValue Src0 = N->getOperand(1); 4251 SDValue Src1 = N->getOperand(2); 4252 EVT CmpVT = Src0.getValueType(); 4253 SDLoc SL(N); 4254 4255 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4256 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4257 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4258 } 4259 4260 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4261 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4262 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4263 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4264 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4265 Src1, DAG.getCondCode(CCOpcode)); 4266 if (VT.bitsEq(CCVT)) 4267 return SetCC; 4268 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4269 } 4270 4271 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4272 SmallVectorImpl<SDValue> &Results, 4273 SelectionDAG &DAG) const { 4274 switch (N->getOpcode()) { 4275 case ISD::INSERT_VECTOR_ELT: { 4276 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4277 Results.push_back(Res); 4278 return; 4279 } 4280 case ISD::EXTRACT_VECTOR_ELT: { 4281 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4282 Results.push_back(Res); 4283 return; 4284 } 4285 case ISD::INTRINSIC_WO_CHAIN: { 4286 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4287 switch (IID) { 4288 case Intrinsic::amdgcn_cvt_pkrtz: { 4289 SDValue Src0 = N->getOperand(1); 4290 SDValue Src1 = N->getOperand(2); 4291 SDLoc SL(N); 4292 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4293 Src0, Src1); 4294 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4295 return; 4296 } 4297 case Intrinsic::amdgcn_cvt_pknorm_i16: 4298 case Intrinsic::amdgcn_cvt_pknorm_u16: 4299 case Intrinsic::amdgcn_cvt_pk_i16: 4300 case Intrinsic::amdgcn_cvt_pk_u16: { 4301 SDValue Src0 = N->getOperand(1); 4302 SDValue Src1 = N->getOperand(2); 4303 SDLoc SL(N); 4304 unsigned Opcode; 4305 4306 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4307 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4308 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4309 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4310 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4311 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4312 else 4313 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4314 4315 EVT VT = N->getValueType(0); 4316 if (isTypeLegal(VT)) 4317 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4318 else { 4319 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4320 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4321 } 4322 return; 4323 } 4324 } 4325 break; 4326 } 4327 case ISD::INTRINSIC_W_CHAIN: { 4328 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4329 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4330 // FIXME: Hacky 4331 Results.push_back(Res.getOperand(0)); 4332 Results.push_back(Res.getOperand(1)); 4333 } else { 4334 Results.push_back(Res); 4335 Results.push_back(Res.getValue(1)); 4336 } 4337 return; 4338 } 4339 4340 break; 4341 } 4342 case ISD::SELECT: { 4343 SDLoc SL(N); 4344 EVT VT = N->getValueType(0); 4345 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4346 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4347 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4348 4349 EVT SelectVT = NewVT; 4350 if (NewVT.bitsLT(MVT::i32)) { 4351 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4352 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4353 SelectVT = MVT::i32; 4354 } 4355 4356 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4357 N->getOperand(0), LHS, RHS); 4358 4359 if (NewVT != SelectVT) 4360 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4361 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4362 return; 4363 } 4364 case ISD::FNEG: { 4365 if (N->getValueType(0) != MVT::v2f16) 4366 break; 4367 4368 SDLoc SL(N); 4369 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4370 4371 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4372 BC, 4373 DAG.getConstant(0x80008000, SL, MVT::i32)); 4374 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4375 return; 4376 } 4377 case ISD::FABS: { 4378 if (N->getValueType(0) != MVT::v2f16) 4379 break; 4380 4381 SDLoc SL(N); 4382 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4383 4384 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4385 BC, 4386 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4387 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4388 return; 4389 } 4390 default: 4391 break; 4392 } 4393 } 4394 4395 /// Helper function for LowerBRCOND 4396 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4397 4398 SDNode *Parent = Value.getNode(); 4399 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4400 I != E; ++I) { 4401 4402 if (I.getUse().get() != Value) 4403 continue; 4404 4405 if (I->getOpcode() == Opcode) 4406 return *I; 4407 } 4408 return nullptr; 4409 } 4410 4411 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4412 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4413 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4414 case Intrinsic::amdgcn_if: 4415 return AMDGPUISD::IF; 4416 case Intrinsic::amdgcn_else: 4417 return AMDGPUISD::ELSE; 4418 case Intrinsic::amdgcn_loop: 4419 return AMDGPUISD::LOOP; 4420 case Intrinsic::amdgcn_end_cf: 4421 llvm_unreachable("should not occur"); 4422 default: 4423 return 0; 4424 } 4425 } 4426 4427 // break, if_break, else_break are all only used as inputs to loop, not 4428 // directly as branch conditions. 4429 return 0; 4430 } 4431 4432 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4433 const Triple &TT = getTargetMachine().getTargetTriple(); 4434 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4435 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4436 AMDGPU::shouldEmitConstantsToTextSection(TT); 4437 } 4438 4439 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4440 // FIXME: Either avoid relying on address space here or change the default 4441 // address space for functions to avoid the explicit check. 4442 return (GV->getValueType()->isFunctionTy() || 4443 GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4444 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4445 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4446 !shouldEmitFixup(GV) && 4447 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4448 } 4449 4450 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4451 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4452 } 4453 4454 /// This transforms the control flow intrinsics to get the branch destination as 4455 /// last parameter, also switches branch target with BR if the need arise 4456 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4457 SelectionDAG &DAG) const { 4458 SDLoc DL(BRCOND); 4459 4460 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4461 SDValue Target = BRCOND.getOperand(2); 4462 SDNode *BR = nullptr; 4463 SDNode *SetCC = nullptr; 4464 4465 if (Intr->getOpcode() == ISD::SETCC) { 4466 // As long as we negate the condition everything is fine 4467 SetCC = Intr; 4468 Intr = SetCC->getOperand(0).getNode(); 4469 4470 } else { 4471 // Get the target from BR if we don't negate the condition 4472 BR = findUser(BRCOND, ISD::BR); 4473 Target = BR->getOperand(1); 4474 } 4475 4476 // FIXME: This changes the types of the intrinsics instead of introducing new 4477 // nodes with the correct types. 4478 // e.g. llvm.amdgcn.loop 4479 4480 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4481 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4482 4483 unsigned CFNode = isCFIntrinsic(Intr); 4484 if (CFNode == 0) { 4485 // This is a uniform branch so we don't need to legalize. 4486 return BRCOND; 4487 } 4488 4489 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4490 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4491 4492 assert(!SetCC || 4493 (SetCC->getConstantOperandVal(1) == 1 && 4494 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4495 ISD::SETNE)); 4496 4497 // operands of the new intrinsic call 4498 SmallVector<SDValue, 4> Ops; 4499 if (HaveChain) 4500 Ops.push_back(BRCOND.getOperand(0)); 4501 4502 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4503 Ops.push_back(Target); 4504 4505 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4506 4507 // build the new intrinsic call 4508 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4509 4510 if (!HaveChain) { 4511 SDValue Ops[] = { 4512 SDValue(Result, 0), 4513 BRCOND.getOperand(0) 4514 }; 4515 4516 Result = DAG.getMergeValues(Ops, DL).getNode(); 4517 } 4518 4519 if (BR) { 4520 // Give the branch instruction our target 4521 SDValue Ops[] = { 4522 BR->getOperand(0), 4523 BRCOND.getOperand(2) 4524 }; 4525 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4526 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4527 BR = NewBR.getNode(); 4528 } 4529 4530 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4531 4532 // Copy the intrinsic results to registers 4533 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4534 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4535 if (!CopyToReg) 4536 continue; 4537 4538 Chain = DAG.getCopyToReg( 4539 Chain, DL, 4540 CopyToReg->getOperand(1), 4541 SDValue(Result, i - 1), 4542 SDValue()); 4543 4544 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4545 } 4546 4547 // Remove the old intrinsic from the chain 4548 DAG.ReplaceAllUsesOfValueWith( 4549 SDValue(Intr, Intr->getNumValues() - 1), 4550 Intr->getOperand(0)); 4551 4552 return Chain; 4553 } 4554 4555 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4556 SelectionDAG &DAG) const { 4557 MVT VT = Op.getSimpleValueType(); 4558 SDLoc DL(Op); 4559 // Checking the depth 4560 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4561 return DAG.getConstant(0, DL, VT); 4562 4563 MachineFunction &MF = DAG.getMachineFunction(); 4564 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4565 // Check for kernel and shader functions 4566 if (Info->isEntryFunction()) 4567 return DAG.getConstant(0, DL, VT); 4568 4569 MachineFrameInfo &MFI = MF.getFrameInfo(); 4570 // There is a call to @llvm.returnaddress in this function 4571 MFI.setReturnAddressIsTaken(true); 4572 4573 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4574 // Get the return address reg and mark it as an implicit live-in 4575 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4576 4577 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4578 } 4579 4580 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4581 SDValue Op, 4582 const SDLoc &DL, 4583 EVT VT) const { 4584 return Op.getValueType().bitsLE(VT) ? 4585 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4586 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4587 } 4588 4589 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4590 assert(Op.getValueType() == MVT::f16 && 4591 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4592 4593 SDValue Src = Op.getOperand(0); 4594 EVT SrcVT = Src.getValueType(); 4595 if (SrcVT != MVT::f64) 4596 return Op; 4597 4598 SDLoc DL(Op); 4599 4600 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4601 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4602 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4603 } 4604 4605 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4606 SelectionDAG &DAG) const { 4607 EVT VT = Op.getValueType(); 4608 const MachineFunction &MF = DAG.getMachineFunction(); 4609 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4610 bool IsIEEEMode = Info->getMode().IEEE; 4611 4612 // FIXME: Assert during eslection that this is only selected for 4613 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4614 // mode functions, but this happens to be OK since it's only done in cases 4615 // where there is known no sNaN. 4616 if (IsIEEEMode) 4617 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4618 4619 if (VT == MVT::v4f16) 4620 return splitBinaryVectorOp(Op, DAG); 4621 return Op; 4622 } 4623 4624 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4625 SDLoc SL(Op); 4626 SDValue Chain = Op.getOperand(0); 4627 4628 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4629 !Subtarget->isTrapHandlerEnabled()) 4630 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4631 4632 MachineFunction &MF = DAG.getMachineFunction(); 4633 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4634 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4635 assert(UserSGPR != AMDGPU::NoRegister); 4636 SDValue QueuePtr = CreateLiveInRegister( 4637 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4638 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4639 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4640 QueuePtr, SDValue()); 4641 SDValue Ops[] = { 4642 ToReg, 4643 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4644 SGPR01, 4645 ToReg.getValue(1) 4646 }; 4647 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4648 } 4649 4650 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4651 SDLoc SL(Op); 4652 SDValue Chain = Op.getOperand(0); 4653 MachineFunction &MF = DAG.getMachineFunction(); 4654 4655 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4656 !Subtarget->isTrapHandlerEnabled()) { 4657 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4658 "debugtrap handler not supported", 4659 Op.getDebugLoc(), 4660 DS_Warning); 4661 LLVMContext &Ctx = MF.getFunction().getContext(); 4662 Ctx.diagnose(NoTrap); 4663 return Chain; 4664 } 4665 4666 SDValue Ops[] = { 4667 Chain, 4668 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4669 }; 4670 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4671 } 4672 4673 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4674 SelectionDAG &DAG) const { 4675 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4676 if (Subtarget->hasApertureRegs()) { 4677 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4678 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4679 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4680 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4681 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4682 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4683 unsigned Encoding = 4684 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4685 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4686 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4687 4688 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4689 SDValue ApertureReg = SDValue( 4690 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4691 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4692 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4693 } 4694 4695 MachineFunction &MF = DAG.getMachineFunction(); 4696 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4697 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4698 assert(UserSGPR != AMDGPU::NoRegister); 4699 4700 SDValue QueuePtr = CreateLiveInRegister( 4701 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4702 4703 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4704 // private_segment_aperture_base_hi. 4705 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4706 4707 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4708 4709 // TODO: Use custom target PseudoSourceValue. 4710 // TODO: We should use the value from the IR intrinsic call, but it might not 4711 // be available and how do we get it? 4712 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4713 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4714 MinAlign(64, StructOffset), 4715 MachineMemOperand::MODereferenceable | 4716 MachineMemOperand::MOInvariant); 4717 } 4718 4719 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4720 SelectionDAG &DAG) const { 4721 SDLoc SL(Op); 4722 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4723 4724 SDValue Src = ASC->getOperand(0); 4725 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4726 4727 const AMDGPUTargetMachine &TM = 4728 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4729 4730 // flat -> local/private 4731 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4732 unsigned DestAS = ASC->getDestAddressSpace(); 4733 4734 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4735 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4736 unsigned NullVal = TM.getNullPointerValue(DestAS); 4737 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4738 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4739 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4740 4741 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4742 NonNull, Ptr, SegmentNullPtr); 4743 } 4744 } 4745 4746 // local/private -> flat 4747 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4748 unsigned SrcAS = ASC->getSrcAddressSpace(); 4749 4750 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4751 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4752 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4753 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4754 4755 SDValue NonNull 4756 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4757 4758 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4759 SDValue CvtPtr 4760 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4761 4762 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4763 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4764 FlatNullPtr); 4765 } 4766 } 4767 4768 // global <-> flat are no-ops and never emitted. 4769 4770 const MachineFunction &MF = DAG.getMachineFunction(); 4771 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4772 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4773 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4774 4775 return DAG.getUNDEF(ASC->getValueType(0)); 4776 } 4777 4778 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4779 // the small vector and inserting them into the big vector. That is better than 4780 // the default expansion of doing it via a stack slot. Even though the use of 4781 // the stack slot would be optimized away afterwards, the stack slot itself 4782 // remains. 4783 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4784 SelectionDAG &DAG) const { 4785 SDValue Vec = Op.getOperand(0); 4786 SDValue Ins = Op.getOperand(1); 4787 SDValue Idx = Op.getOperand(2); 4788 EVT VecVT = Vec.getValueType(); 4789 EVT InsVT = Ins.getValueType(); 4790 EVT EltVT = VecVT.getVectorElementType(); 4791 unsigned InsNumElts = InsVT.getVectorNumElements(); 4792 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4793 SDLoc SL(Op); 4794 4795 for (unsigned I = 0; I != InsNumElts; ++I) { 4796 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4797 DAG.getConstant(I, SL, MVT::i32)); 4798 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4799 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4800 } 4801 return Vec; 4802 } 4803 4804 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4805 SelectionDAG &DAG) const { 4806 SDValue Vec = Op.getOperand(0); 4807 SDValue InsVal = Op.getOperand(1); 4808 SDValue Idx = Op.getOperand(2); 4809 EVT VecVT = Vec.getValueType(); 4810 EVT EltVT = VecVT.getVectorElementType(); 4811 unsigned VecSize = VecVT.getSizeInBits(); 4812 unsigned EltSize = EltVT.getSizeInBits(); 4813 4814 4815 assert(VecSize <= 64); 4816 4817 unsigned NumElts = VecVT.getVectorNumElements(); 4818 SDLoc SL(Op); 4819 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4820 4821 if (NumElts == 4 && EltSize == 16 && KIdx) { 4822 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4823 4824 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4825 DAG.getConstant(0, SL, MVT::i32)); 4826 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4827 DAG.getConstant(1, SL, MVT::i32)); 4828 4829 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4830 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4831 4832 unsigned Idx = KIdx->getZExtValue(); 4833 bool InsertLo = Idx < 2; 4834 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4835 InsertLo ? LoVec : HiVec, 4836 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4837 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4838 4839 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4840 4841 SDValue Concat = InsertLo ? 4842 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4843 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4844 4845 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4846 } 4847 4848 if (isa<ConstantSDNode>(Idx)) 4849 return SDValue(); 4850 4851 MVT IntVT = MVT::getIntegerVT(VecSize); 4852 4853 // Avoid stack access for dynamic indexing. 4854 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4855 4856 // Create a congruent vector with the target value in each element so that 4857 // the required element can be masked and ORed into the target vector. 4858 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4859 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4860 4861 assert(isPowerOf2_32(EltSize)); 4862 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4863 4864 // Convert vector index to bit-index. 4865 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4866 4867 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4868 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4869 DAG.getConstant(0xffff, SL, IntVT), 4870 ScaledIdx); 4871 4872 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4873 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4874 DAG.getNOT(SL, BFM, IntVT), BCVec); 4875 4876 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4877 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4878 } 4879 4880 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4881 SelectionDAG &DAG) const { 4882 SDLoc SL(Op); 4883 4884 EVT ResultVT = Op.getValueType(); 4885 SDValue Vec = Op.getOperand(0); 4886 SDValue Idx = Op.getOperand(1); 4887 EVT VecVT = Vec.getValueType(); 4888 unsigned VecSize = VecVT.getSizeInBits(); 4889 EVT EltVT = VecVT.getVectorElementType(); 4890 assert(VecSize <= 64); 4891 4892 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4893 4894 // Make sure we do any optimizations that will make it easier to fold 4895 // source modifiers before obscuring it with bit operations. 4896 4897 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4898 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4899 return Combined; 4900 4901 unsigned EltSize = EltVT.getSizeInBits(); 4902 assert(isPowerOf2_32(EltSize)); 4903 4904 MVT IntVT = MVT::getIntegerVT(VecSize); 4905 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4906 4907 // Convert vector index to bit-index (* EltSize) 4908 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4909 4910 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4911 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4912 4913 if (ResultVT == MVT::f16) { 4914 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4915 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4916 } 4917 4918 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4919 } 4920 4921 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4922 assert(Elt % 2 == 0); 4923 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4924 } 4925 4926 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4927 SelectionDAG &DAG) const { 4928 SDLoc SL(Op); 4929 EVT ResultVT = Op.getValueType(); 4930 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4931 4932 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4933 EVT EltVT = PackVT.getVectorElementType(); 4934 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4935 4936 // vector_shuffle <0,1,6,7> lhs, rhs 4937 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4938 // 4939 // vector_shuffle <6,7,2,3> lhs, rhs 4940 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4941 // 4942 // vector_shuffle <6,7,0,1> lhs, rhs 4943 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4944 4945 // Avoid scalarizing when both halves are reading from consecutive elements. 4946 SmallVector<SDValue, 4> Pieces; 4947 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4948 if (elementPairIsContiguous(SVN->getMask(), I)) { 4949 const int Idx = SVN->getMaskElt(I); 4950 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4951 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4952 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4953 PackVT, SVN->getOperand(VecIdx), 4954 DAG.getConstant(EltIdx, SL, MVT::i32)); 4955 Pieces.push_back(SubVec); 4956 } else { 4957 const int Idx0 = SVN->getMaskElt(I); 4958 const int Idx1 = SVN->getMaskElt(I + 1); 4959 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4960 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4961 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4962 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4963 4964 SDValue Vec0 = SVN->getOperand(VecIdx0); 4965 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4966 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4967 4968 SDValue Vec1 = SVN->getOperand(VecIdx1); 4969 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4970 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4971 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4972 } 4973 } 4974 4975 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4976 } 4977 4978 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4979 SelectionDAG &DAG) const { 4980 SDLoc SL(Op); 4981 EVT VT = Op.getValueType(); 4982 4983 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4984 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4985 4986 // Turn into pair of packed build_vectors. 4987 // TODO: Special case for constants that can be materialized with s_mov_b64. 4988 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4989 { Op.getOperand(0), Op.getOperand(1) }); 4990 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4991 { Op.getOperand(2), Op.getOperand(3) }); 4992 4993 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4994 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4995 4996 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4997 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4998 } 4999 5000 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5001 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5002 5003 SDValue Lo = Op.getOperand(0); 5004 SDValue Hi = Op.getOperand(1); 5005 5006 // Avoid adding defined bits with the zero_extend. 5007 if (Hi.isUndef()) { 5008 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5009 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5010 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5011 } 5012 5013 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5014 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5015 5016 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5017 DAG.getConstant(16, SL, MVT::i32)); 5018 if (Lo.isUndef()) 5019 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5020 5021 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5022 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5023 5024 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5025 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5026 } 5027 5028 bool 5029 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5030 // We can fold offsets for anything that doesn't require a GOT relocation. 5031 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5032 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5033 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5034 !shouldEmitGOTReloc(GA->getGlobal()); 5035 } 5036 5037 static SDValue 5038 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5039 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5040 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5041 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5042 // lowered to the following code sequence: 5043 // 5044 // For constant address space: 5045 // s_getpc_b64 s[0:1] 5046 // s_add_u32 s0, s0, $symbol 5047 // s_addc_u32 s1, s1, 0 5048 // 5049 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5050 // a fixup or relocation is emitted to replace $symbol with a literal 5051 // constant, which is a pc-relative offset from the encoding of the $symbol 5052 // operand to the global variable. 5053 // 5054 // For global address space: 5055 // s_getpc_b64 s[0:1] 5056 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5057 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5058 // 5059 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5060 // fixups or relocations are emitted to replace $symbol@*@lo and 5061 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5062 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5063 // operand to the global variable. 5064 // 5065 // What we want here is an offset from the value returned by s_getpc 5066 // (which is the address of the s_add_u32 instruction) to the global 5067 // variable, but since the encoding of $symbol starts 4 bytes after the start 5068 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5069 // small. This requires us to add 4 to the global variable offset in order to 5070 // compute the correct address. 5071 SDValue PtrLo = 5072 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5073 SDValue PtrHi; 5074 if (GAFlags == SIInstrInfo::MO_NONE) { 5075 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5076 } else { 5077 PtrHi = 5078 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5079 } 5080 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5081 } 5082 5083 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5084 SDValue Op, 5085 SelectionDAG &DAG) const { 5086 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5087 const GlobalValue *GV = GSD->getGlobal(); 5088 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5089 (!GV->hasExternalLinkage() || 5090 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 5091 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 5092 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5093 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5094 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5095 5096 SDLoc DL(GSD); 5097 EVT PtrVT = Op.getValueType(); 5098 5099 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5100 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5101 SIInstrInfo::MO_ABS32_LO); 5102 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5103 } 5104 5105 if (shouldEmitFixup(GV)) 5106 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5107 else if (shouldEmitPCReloc(GV)) 5108 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5109 SIInstrInfo::MO_REL32); 5110 5111 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5112 SIInstrInfo::MO_GOTPCREL32); 5113 5114 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5115 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5116 const DataLayout &DataLayout = DAG.getDataLayout(); 5117 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5118 MachinePointerInfo PtrInfo 5119 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5120 5121 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5122 MachineMemOperand::MODereferenceable | 5123 MachineMemOperand::MOInvariant); 5124 } 5125 5126 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5127 const SDLoc &DL, SDValue V) const { 5128 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5129 // the destination register. 5130 // 5131 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5132 // so we will end up with redundant moves to m0. 5133 // 5134 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5135 5136 // A Null SDValue creates a glue result. 5137 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5138 V, Chain); 5139 return SDValue(M0, 0); 5140 } 5141 5142 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5143 SDValue Op, 5144 MVT VT, 5145 unsigned Offset) const { 5146 SDLoc SL(Op); 5147 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5148 DAG.getEntryNode(), Offset, 4, false); 5149 // The local size values will have the hi 16-bits as zero. 5150 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5151 DAG.getValueType(VT)); 5152 } 5153 5154 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5155 EVT VT) { 5156 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5157 "non-hsa intrinsic with hsa target", 5158 DL.getDebugLoc()); 5159 DAG.getContext()->diagnose(BadIntrin); 5160 return DAG.getUNDEF(VT); 5161 } 5162 5163 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5164 EVT VT) { 5165 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5166 "intrinsic not supported on subtarget", 5167 DL.getDebugLoc()); 5168 DAG.getContext()->diagnose(BadIntrin); 5169 return DAG.getUNDEF(VT); 5170 } 5171 5172 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5173 ArrayRef<SDValue> Elts) { 5174 assert(!Elts.empty()); 5175 MVT Type; 5176 unsigned NumElts; 5177 5178 if (Elts.size() == 1) { 5179 Type = MVT::f32; 5180 NumElts = 1; 5181 } else if (Elts.size() == 2) { 5182 Type = MVT::v2f32; 5183 NumElts = 2; 5184 } else if (Elts.size() <= 4) { 5185 Type = MVT::v4f32; 5186 NumElts = 4; 5187 } else if (Elts.size() <= 8) { 5188 Type = MVT::v8f32; 5189 NumElts = 8; 5190 } else { 5191 assert(Elts.size() <= 16); 5192 Type = MVT::v16f32; 5193 NumElts = 16; 5194 } 5195 5196 SmallVector<SDValue, 16> VecElts(NumElts); 5197 for (unsigned i = 0; i < Elts.size(); ++i) { 5198 SDValue Elt = Elts[i]; 5199 if (Elt.getValueType() != MVT::f32) 5200 Elt = DAG.getBitcast(MVT::f32, Elt); 5201 VecElts[i] = Elt; 5202 } 5203 for (unsigned i = Elts.size(); i < NumElts; ++i) 5204 VecElts[i] = DAG.getUNDEF(MVT::f32); 5205 5206 if (NumElts == 1) 5207 return VecElts[0]; 5208 return DAG.getBuildVector(Type, DL, VecElts); 5209 } 5210 5211 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5212 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5213 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5214 5215 uint64_t Value = CachePolicyConst->getZExtValue(); 5216 SDLoc DL(CachePolicy); 5217 if (GLC) { 5218 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5219 Value &= ~(uint64_t)0x1; 5220 } 5221 if (SLC) { 5222 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5223 Value &= ~(uint64_t)0x2; 5224 } 5225 if (DLC) { 5226 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5227 Value &= ~(uint64_t)0x4; 5228 } 5229 5230 return Value == 0; 5231 } 5232 5233 // Re-construct the required return value for a image load intrinsic. 5234 // This is more complicated due to the optional use TexFailCtrl which means the required 5235 // return type is an aggregate 5236 static SDValue constructRetValue(SelectionDAG &DAG, 5237 MachineSDNode *Result, 5238 ArrayRef<EVT> ResultTypes, 5239 bool IsTexFail, bool Unpacked, bool IsD16, 5240 int DMaskPop, int NumVDataDwords, 5241 const SDLoc &DL, LLVMContext &Context) { 5242 // Determine the required return type. This is the same regardless of IsTexFail flag 5243 EVT ReqRetVT = ResultTypes[0]; 5244 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5245 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5246 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5247 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5248 : AdjEltVT 5249 : ReqRetVT; 5250 5251 // Extract data part of the result 5252 // Bitcast the result to the same type as the required return type 5253 int NumElts; 5254 if (IsD16 && !Unpacked) 5255 NumElts = NumVDataDwords << 1; 5256 else 5257 NumElts = NumVDataDwords; 5258 5259 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5260 : AdjEltVT; 5261 5262 // Special case for v6f16. Rather than add support for this, use v3i32 to 5263 // extract the data elements 5264 bool V6F16Special = false; 5265 if (NumElts == 6) { 5266 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5267 DMaskPop >>= 1; 5268 ReqRetNumElts >>= 1; 5269 V6F16Special = true; 5270 AdjVT = MVT::v2i32; 5271 } 5272 5273 SDValue N = SDValue(Result, 0); 5274 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5275 5276 // Iterate over the result 5277 SmallVector<SDValue, 4> BVElts; 5278 5279 if (CastVT.isVector()) { 5280 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5281 } else { 5282 BVElts.push_back(CastRes); 5283 } 5284 int ExtraElts = ReqRetNumElts - DMaskPop; 5285 while(ExtraElts--) 5286 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5287 5288 SDValue PreTFCRes; 5289 if (ReqRetNumElts > 1) { 5290 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5291 if (IsD16 && Unpacked) 5292 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5293 else 5294 PreTFCRes = NewVec; 5295 } else { 5296 PreTFCRes = BVElts[0]; 5297 } 5298 5299 if (V6F16Special) 5300 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5301 5302 if (!IsTexFail) { 5303 if (Result->getNumValues() > 1) 5304 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5305 else 5306 return PreTFCRes; 5307 } 5308 5309 // Extract the TexFail result and insert into aggregate return 5310 SmallVector<SDValue, 1> TFCElt; 5311 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5312 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5313 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5314 } 5315 5316 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5317 SDValue *LWE, bool &IsTexFail) { 5318 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5319 5320 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5321 if (Value) { 5322 IsTexFail = true; 5323 } 5324 5325 SDLoc DL(TexFailCtrlConst); 5326 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5327 Value &= ~(uint64_t)0x1; 5328 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5329 Value &= ~(uint64_t)0x2; 5330 5331 return Value == 0; 5332 } 5333 5334 SDValue SITargetLowering::lowerImage(SDValue Op, 5335 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5336 SelectionDAG &DAG) const { 5337 SDLoc DL(Op); 5338 MachineFunction &MF = DAG.getMachineFunction(); 5339 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5340 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5341 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5342 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5343 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5344 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5345 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5346 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5347 unsigned IntrOpcode = Intr->BaseOpcode; 5348 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5349 5350 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5351 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5352 bool IsD16 = false; 5353 bool IsA16 = false; 5354 SDValue VData; 5355 int NumVDataDwords; 5356 bool AdjustRetType = false; 5357 5358 unsigned AddrIdx; // Index of first address argument 5359 unsigned DMask; 5360 unsigned DMaskLanes = 0; 5361 5362 if (BaseOpcode->Atomic) { 5363 VData = Op.getOperand(2); 5364 5365 bool Is64Bit = VData.getValueType() == MVT::i64; 5366 if (BaseOpcode->AtomicX2) { 5367 SDValue VData2 = Op.getOperand(3); 5368 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5369 {VData, VData2}); 5370 if (Is64Bit) 5371 VData = DAG.getBitcast(MVT::v4i32, VData); 5372 5373 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5374 DMask = Is64Bit ? 0xf : 0x3; 5375 NumVDataDwords = Is64Bit ? 4 : 2; 5376 AddrIdx = 4; 5377 } else { 5378 DMask = Is64Bit ? 0x3 : 0x1; 5379 NumVDataDwords = Is64Bit ? 2 : 1; 5380 AddrIdx = 3; 5381 } 5382 } else { 5383 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5384 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5385 DMask = DMaskConst->getZExtValue(); 5386 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5387 5388 if (BaseOpcode->Store) { 5389 VData = Op.getOperand(2); 5390 5391 MVT StoreVT = VData.getSimpleValueType(); 5392 if (StoreVT.getScalarType() == MVT::f16) { 5393 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5394 return Op; // D16 is unsupported for this instruction 5395 5396 IsD16 = true; 5397 VData = handleD16VData(VData, DAG); 5398 } 5399 5400 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5401 } else { 5402 // Work out the num dwords based on the dmask popcount and underlying type 5403 // and whether packing is supported. 5404 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5405 if (LoadVT.getScalarType() == MVT::f16) { 5406 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5407 return Op; // D16 is unsupported for this instruction 5408 5409 IsD16 = true; 5410 } 5411 5412 // Confirm that the return type is large enough for the dmask specified 5413 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5414 (!LoadVT.isVector() && DMaskLanes > 1)) 5415 return Op; 5416 5417 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5418 NumVDataDwords = (DMaskLanes + 1) / 2; 5419 else 5420 NumVDataDwords = DMaskLanes; 5421 5422 AdjustRetType = true; 5423 } 5424 5425 AddrIdx = DMaskIdx + 1; 5426 } 5427 5428 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5429 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5430 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5431 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5432 NumCoords + NumLCM; 5433 unsigned NumMIVAddrs = NumVAddrs; 5434 5435 SmallVector<SDValue, 4> VAddrs; 5436 5437 // Optimize _L to _LZ when _L is zero 5438 if (LZMappingInfo) { 5439 if (auto ConstantLod = 5440 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5441 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5442 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5443 NumMIVAddrs--; // remove 'lod' 5444 } 5445 } 5446 } 5447 5448 // Optimize _mip away, when 'lod' is zero 5449 if (MIPMappingInfo) { 5450 if (auto ConstantLod = 5451 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5452 if (ConstantLod->isNullValue()) { 5453 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5454 NumMIVAddrs--; // remove 'lod' 5455 } 5456 } 5457 } 5458 5459 // Check for 16 bit addresses and pack if true. 5460 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5461 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5462 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5463 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5464 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5465 IsA16 = true; 5466 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5467 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5468 SDValue AddrLo, AddrHi; 5469 // Push back extra arguments. 5470 if (i < DimIdx) { 5471 AddrLo = Op.getOperand(i); 5472 } else { 5473 AddrLo = Op.getOperand(i); 5474 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5475 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5476 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5477 ((NumGradients / 2) % 2 == 1 && 5478 (i == DimIdx + (NumGradients / 2) - 1 || 5479 i == DimIdx + NumGradients - 1))) { 5480 AddrHi = DAG.getUNDEF(MVT::f16); 5481 } else { 5482 AddrHi = Op.getOperand(i + 1); 5483 i++; 5484 } 5485 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5486 {AddrLo, AddrHi}); 5487 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5488 } 5489 VAddrs.push_back(AddrLo); 5490 } 5491 } else { 5492 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5493 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5494 } 5495 5496 // If the register allocator cannot place the address registers contiguously 5497 // without introducing moves, then using the non-sequential address encoding 5498 // is always preferable, since it saves VALU instructions and is usually a 5499 // wash in terms of code size or even better. 5500 // 5501 // However, we currently have no way of hinting to the register allocator that 5502 // MIMG addresses should be placed contiguously when it is possible to do so, 5503 // so force non-NSA for the common 2-address case as a heuristic. 5504 // 5505 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5506 // allocation when possible. 5507 bool UseNSA = 5508 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5509 SDValue VAddr; 5510 if (!UseNSA) 5511 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5512 5513 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5514 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5515 unsigned CtrlIdx; // Index of texfailctrl argument 5516 SDValue Unorm; 5517 if (!BaseOpcode->Sampler) { 5518 Unorm = True; 5519 CtrlIdx = AddrIdx + NumVAddrs + 1; 5520 } else { 5521 auto UnormConst = 5522 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5523 5524 Unorm = UnormConst->getZExtValue() ? True : False; 5525 CtrlIdx = AddrIdx + NumVAddrs + 3; 5526 } 5527 5528 SDValue TFE; 5529 SDValue LWE; 5530 SDValue TexFail = Op.getOperand(CtrlIdx); 5531 bool IsTexFail = false; 5532 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5533 return Op; 5534 5535 if (IsTexFail) { 5536 if (!DMaskLanes) { 5537 // Expecting to get an error flag since TFC is on - and dmask is 0 5538 // Force dmask to be at least 1 otherwise the instruction will fail 5539 DMask = 0x1; 5540 DMaskLanes = 1; 5541 NumVDataDwords = 1; 5542 } 5543 NumVDataDwords += 1; 5544 AdjustRetType = true; 5545 } 5546 5547 // Has something earlier tagged that the return type needs adjusting 5548 // This happens if the instruction is a load or has set TexFailCtrl flags 5549 if (AdjustRetType) { 5550 // NumVDataDwords reflects the true number of dwords required in the return type 5551 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5552 // This is a no-op load. This can be eliminated 5553 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5554 if (isa<MemSDNode>(Op)) 5555 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5556 return Undef; 5557 } 5558 5559 EVT NewVT = NumVDataDwords > 1 ? 5560 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5561 : MVT::f32; 5562 5563 ResultTypes[0] = NewVT; 5564 if (ResultTypes.size() == 3) { 5565 // Original result was aggregate type used for TexFailCtrl results 5566 // The actual instruction returns as a vector type which has now been 5567 // created. Remove the aggregate result. 5568 ResultTypes.erase(&ResultTypes[1]); 5569 } 5570 } 5571 5572 SDValue GLC; 5573 SDValue SLC; 5574 SDValue DLC; 5575 if (BaseOpcode->Atomic) { 5576 GLC = True; // TODO no-return optimization 5577 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5578 IsGFX10 ? &DLC : nullptr)) 5579 return Op; 5580 } else { 5581 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5582 IsGFX10 ? &DLC : nullptr)) 5583 return Op; 5584 } 5585 5586 SmallVector<SDValue, 26> Ops; 5587 if (BaseOpcode->Store || BaseOpcode->Atomic) 5588 Ops.push_back(VData); // vdata 5589 if (UseNSA) { 5590 for (const SDValue &Addr : VAddrs) 5591 Ops.push_back(Addr); 5592 } else { 5593 Ops.push_back(VAddr); 5594 } 5595 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5596 if (BaseOpcode->Sampler) 5597 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5598 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5599 if (IsGFX10) 5600 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5601 Ops.push_back(Unorm); 5602 if (IsGFX10) 5603 Ops.push_back(DLC); 5604 Ops.push_back(GLC); 5605 Ops.push_back(SLC); 5606 Ops.push_back(IsA16 && // a16 or r128 5607 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5608 Ops.push_back(TFE); // tfe 5609 Ops.push_back(LWE); // lwe 5610 if (!IsGFX10) 5611 Ops.push_back(DimInfo->DA ? True : False); 5612 if (BaseOpcode->HasD16) 5613 Ops.push_back(IsD16 ? True : False); 5614 if (isa<MemSDNode>(Op)) 5615 Ops.push_back(Op.getOperand(0)); // chain 5616 5617 int NumVAddrDwords = 5618 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5619 int Opcode = -1; 5620 5621 if (IsGFX10) { 5622 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5623 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5624 : AMDGPU::MIMGEncGfx10Default, 5625 NumVDataDwords, NumVAddrDwords); 5626 } else { 5627 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5628 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5629 NumVDataDwords, NumVAddrDwords); 5630 if (Opcode == -1) 5631 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5632 NumVDataDwords, NumVAddrDwords); 5633 } 5634 assert(Opcode != -1); 5635 5636 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5637 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5638 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5639 DAG.setNodeMemRefs(NewNode, {MemRef}); 5640 } 5641 5642 if (BaseOpcode->AtomicX2) { 5643 SmallVector<SDValue, 1> Elt; 5644 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5645 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5646 } else if (!BaseOpcode->Store) { 5647 return constructRetValue(DAG, NewNode, 5648 OrigResultTypes, IsTexFail, 5649 Subtarget->hasUnpackedD16VMem(), IsD16, 5650 DMaskLanes, NumVDataDwords, DL, 5651 *DAG.getContext()); 5652 } 5653 5654 return SDValue(NewNode, 0); 5655 } 5656 5657 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5658 SDValue Offset, SDValue GLC, SDValue DLC, 5659 SelectionDAG &DAG) const { 5660 MachineFunction &MF = DAG.getMachineFunction(); 5661 5662 const DataLayout &DataLayout = DAG.getDataLayout(); 5663 unsigned Align = 5664 DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5665 5666 MachineMemOperand *MMO = MF.getMachineMemOperand( 5667 MachinePointerInfo(), 5668 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5669 MachineMemOperand::MOInvariant, 5670 VT.getStoreSize(), Align); 5671 5672 if (!Offset->isDivergent()) { 5673 SDValue Ops[] = { 5674 Rsrc, 5675 Offset, // Offset 5676 GLC, 5677 DLC, 5678 }; 5679 5680 // Widen vec3 load to vec4. 5681 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5682 EVT WidenedVT = 5683 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5684 auto WidenedOp = DAG.getMemIntrinsicNode( 5685 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5686 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5687 auto Subvector = DAG.getNode( 5688 ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5689 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 5690 return Subvector; 5691 } 5692 5693 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5694 DAG.getVTList(VT), Ops, VT, MMO); 5695 } 5696 5697 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5698 // assume that the buffer is unswizzled. 5699 SmallVector<SDValue, 4> Loads; 5700 unsigned NumLoads = 1; 5701 MVT LoadVT = VT.getSimpleVT(); 5702 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5703 assert((LoadVT.getScalarType() == MVT::i32 || 5704 LoadVT.getScalarType() == MVT::f32)); 5705 5706 if (NumElts == 8 || NumElts == 16) { 5707 NumLoads = NumElts / 4; 5708 LoadVT = MVT::v4i32; 5709 } 5710 5711 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5712 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5713 SDValue Ops[] = { 5714 DAG.getEntryNode(), // Chain 5715 Rsrc, // rsrc 5716 DAG.getConstant(0, DL, MVT::i32), // vindex 5717 {}, // voffset 5718 {}, // soffset 5719 {}, // offset 5720 DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5721 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5722 }; 5723 5724 // Use the alignment to ensure that the required offsets will fit into the 5725 // immediate offsets. 5726 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5727 5728 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5729 for (unsigned i = 0; i < NumLoads; ++i) { 5730 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5731 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5732 LoadVT, MMO, DAG)); 5733 } 5734 5735 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5736 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5737 5738 return Loads[0]; 5739 } 5740 5741 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5742 SelectionDAG &DAG) const { 5743 MachineFunction &MF = DAG.getMachineFunction(); 5744 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5745 5746 EVT VT = Op.getValueType(); 5747 SDLoc DL(Op); 5748 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5749 5750 // TODO: Should this propagate fast-math-flags? 5751 5752 switch (IntrinsicID) { 5753 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5754 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5755 return emitNonHSAIntrinsicError(DAG, DL, VT); 5756 return getPreloadedValue(DAG, *MFI, VT, 5757 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5758 } 5759 case Intrinsic::amdgcn_dispatch_ptr: 5760 case Intrinsic::amdgcn_queue_ptr: { 5761 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5762 DiagnosticInfoUnsupported BadIntrin( 5763 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5764 DL.getDebugLoc()); 5765 DAG.getContext()->diagnose(BadIntrin); 5766 return DAG.getUNDEF(VT); 5767 } 5768 5769 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5770 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5771 return getPreloadedValue(DAG, *MFI, VT, RegID); 5772 } 5773 case Intrinsic::amdgcn_implicitarg_ptr: { 5774 if (MFI->isEntryFunction()) 5775 return getImplicitArgPtr(DAG, DL); 5776 return getPreloadedValue(DAG, *MFI, VT, 5777 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5778 } 5779 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5780 return getPreloadedValue(DAG, *MFI, VT, 5781 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5782 } 5783 case Intrinsic::amdgcn_dispatch_id: { 5784 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5785 } 5786 case Intrinsic::amdgcn_rcp: 5787 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5788 case Intrinsic::amdgcn_rsq: 5789 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5790 case Intrinsic::amdgcn_rsq_legacy: 5791 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5792 return emitRemovedIntrinsicError(DAG, DL, VT); 5793 5794 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5795 case Intrinsic::amdgcn_rcp_legacy: 5796 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5797 return emitRemovedIntrinsicError(DAG, DL, VT); 5798 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5799 case Intrinsic::amdgcn_rsq_clamp: { 5800 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5801 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5802 5803 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5804 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5805 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5806 5807 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5808 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5809 DAG.getConstantFP(Max, DL, VT)); 5810 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5811 DAG.getConstantFP(Min, DL, VT)); 5812 } 5813 case Intrinsic::r600_read_ngroups_x: 5814 if (Subtarget->isAmdHsaOS()) 5815 return emitNonHSAIntrinsicError(DAG, DL, VT); 5816 5817 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5818 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5819 case Intrinsic::r600_read_ngroups_y: 5820 if (Subtarget->isAmdHsaOS()) 5821 return emitNonHSAIntrinsicError(DAG, DL, VT); 5822 5823 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5824 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5825 case Intrinsic::r600_read_ngroups_z: 5826 if (Subtarget->isAmdHsaOS()) 5827 return emitNonHSAIntrinsicError(DAG, DL, VT); 5828 5829 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5830 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5831 case Intrinsic::r600_read_global_size_x: 5832 if (Subtarget->isAmdHsaOS()) 5833 return emitNonHSAIntrinsicError(DAG, DL, VT); 5834 5835 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5836 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5837 case Intrinsic::r600_read_global_size_y: 5838 if (Subtarget->isAmdHsaOS()) 5839 return emitNonHSAIntrinsicError(DAG, DL, VT); 5840 5841 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5842 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5843 case Intrinsic::r600_read_global_size_z: 5844 if (Subtarget->isAmdHsaOS()) 5845 return emitNonHSAIntrinsicError(DAG, DL, VT); 5846 5847 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5848 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5849 case Intrinsic::r600_read_local_size_x: 5850 if (Subtarget->isAmdHsaOS()) 5851 return emitNonHSAIntrinsicError(DAG, DL, VT); 5852 5853 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5854 SI::KernelInputOffsets::LOCAL_SIZE_X); 5855 case Intrinsic::r600_read_local_size_y: 5856 if (Subtarget->isAmdHsaOS()) 5857 return emitNonHSAIntrinsicError(DAG, DL, VT); 5858 5859 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5860 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5861 case Intrinsic::r600_read_local_size_z: 5862 if (Subtarget->isAmdHsaOS()) 5863 return emitNonHSAIntrinsicError(DAG, DL, VT); 5864 5865 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5866 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5867 case Intrinsic::amdgcn_workgroup_id_x: 5868 case Intrinsic::r600_read_tgid_x: 5869 return getPreloadedValue(DAG, *MFI, VT, 5870 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5871 case Intrinsic::amdgcn_workgroup_id_y: 5872 case Intrinsic::r600_read_tgid_y: 5873 return getPreloadedValue(DAG, *MFI, VT, 5874 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5875 case Intrinsic::amdgcn_workgroup_id_z: 5876 case Intrinsic::r600_read_tgid_z: 5877 return getPreloadedValue(DAG, *MFI, VT, 5878 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5879 case Intrinsic::amdgcn_workitem_id_x: 5880 case Intrinsic::r600_read_tidig_x: 5881 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5882 SDLoc(DAG.getEntryNode()), 5883 MFI->getArgInfo().WorkItemIDX); 5884 case Intrinsic::amdgcn_workitem_id_y: 5885 case Intrinsic::r600_read_tidig_y: 5886 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5887 SDLoc(DAG.getEntryNode()), 5888 MFI->getArgInfo().WorkItemIDY); 5889 case Intrinsic::amdgcn_workitem_id_z: 5890 case Intrinsic::r600_read_tidig_z: 5891 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5892 SDLoc(DAG.getEntryNode()), 5893 MFI->getArgInfo().WorkItemIDZ); 5894 case Intrinsic::amdgcn_wavefrontsize: 5895 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5896 SDLoc(Op), MVT::i32); 5897 case Intrinsic::amdgcn_s_buffer_load: { 5898 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5899 SDValue GLC; 5900 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5901 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5902 IsGFX10 ? &DLC : nullptr)) 5903 return Op; 5904 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5905 DAG); 5906 } 5907 case Intrinsic::amdgcn_fdiv_fast: 5908 return lowerFDIV_FAST(Op, DAG); 5909 case Intrinsic::amdgcn_interp_p1_f16: { 5910 if (getSubtarget()->getLDSBankCount() == 16) { 5911 // 16 bank LDS 5912 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0, 5913 Op.getOperand(5), SDValue()); 5914 5915 // FIXME: This implicitly will insert a second CopyToReg to M0. 5916 SDValue S = DAG.getNode( 5917 ISD::INTRINSIC_WO_CHAIN, DL, MVT::f32, 5918 DAG.getTargetConstant(Intrinsic::amdgcn_interp_mov, DL, MVT::i32), 5919 DAG.getConstant(2, DL, MVT::i32), // P0 5920 Op.getOperand(2), // Attrchan 5921 Op.getOperand(3), // Attr 5922 Op.getOperand(5)); // m0 5923 5924 SDValue Ops[] = { 5925 Op.getOperand(1), // Src0 5926 Op.getOperand(2), // Attrchan 5927 Op.getOperand(3), // Attr 5928 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5929 S, // Src2 - holds two f16 values selected by high 5930 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5931 Op.getOperand(4), // high 5932 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5933 DAG.getTargetConstant(0, DL, MVT::i32), // $omod 5934 ToM0.getValue(1) 5935 }; 5936 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5937 } 5938 5939 return SDValue(); 5940 } 5941 case Intrinsic::amdgcn_sin: 5942 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5943 5944 case Intrinsic::amdgcn_cos: 5945 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5946 5947 case Intrinsic::amdgcn_mul_u24: 5948 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5949 case Intrinsic::amdgcn_mul_i24: 5950 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5951 5952 case Intrinsic::amdgcn_log_clamp: { 5953 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5954 return SDValue(); 5955 5956 DiagnosticInfoUnsupported BadIntrin( 5957 MF.getFunction(), "intrinsic not supported on subtarget", 5958 DL.getDebugLoc()); 5959 DAG.getContext()->diagnose(BadIntrin); 5960 return DAG.getUNDEF(VT); 5961 } 5962 case Intrinsic::amdgcn_ldexp: 5963 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5964 Op.getOperand(1), Op.getOperand(2)); 5965 5966 case Intrinsic::amdgcn_fract: 5967 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5968 5969 case Intrinsic::amdgcn_class: 5970 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5971 Op.getOperand(1), Op.getOperand(2)); 5972 case Intrinsic::amdgcn_div_fmas: 5973 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5974 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5975 Op.getOperand(4)); 5976 5977 case Intrinsic::amdgcn_div_fixup: 5978 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5979 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5980 5981 case Intrinsic::amdgcn_trig_preop: 5982 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5983 Op.getOperand(1), Op.getOperand(2)); 5984 case Intrinsic::amdgcn_div_scale: { 5985 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5986 5987 // Translate to the operands expected by the machine instruction. The 5988 // first parameter must be the same as the first instruction. 5989 SDValue Numerator = Op.getOperand(1); 5990 SDValue Denominator = Op.getOperand(2); 5991 5992 // Note this order is opposite of the machine instruction's operations, 5993 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5994 // intrinsic has the numerator as the first operand to match a normal 5995 // division operation. 5996 5997 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5998 5999 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6000 Denominator, Numerator); 6001 } 6002 case Intrinsic::amdgcn_icmp: { 6003 // There is a Pat that handles this variant, so return it as-is. 6004 if (Op.getOperand(1).getValueType() == MVT::i1 && 6005 Op.getConstantOperandVal(2) == 0 && 6006 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6007 return Op; 6008 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6009 } 6010 case Intrinsic::amdgcn_fcmp: { 6011 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6012 } 6013 case Intrinsic::amdgcn_fmed3: 6014 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6015 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6016 case Intrinsic::amdgcn_fdot2: 6017 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6018 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6019 Op.getOperand(4)); 6020 case Intrinsic::amdgcn_fmul_legacy: 6021 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6022 Op.getOperand(1), Op.getOperand(2)); 6023 case Intrinsic::amdgcn_sffbh: 6024 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6025 case Intrinsic::amdgcn_sbfe: 6026 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6027 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6028 case Intrinsic::amdgcn_ubfe: 6029 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6030 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6031 case Intrinsic::amdgcn_cvt_pkrtz: 6032 case Intrinsic::amdgcn_cvt_pknorm_i16: 6033 case Intrinsic::amdgcn_cvt_pknorm_u16: 6034 case Intrinsic::amdgcn_cvt_pk_i16: 6035 case Intrinsic::amdgcn_cvt_pk_u16: { 6036 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6037 EVT VT = Op.getValueType(); 6038 unsigned Opcode; 6039 6040 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6041 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6042 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6043 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6044 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6045 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6046 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6047 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6048 else 6049 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6050 6051 if (isTypeLegal(VT)) 6052 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6053 6054 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6055 Op.getOperand(1), Op.getOperand(2)); 6056 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6057 } 6058 case Intrinsic::amdgcn_fmad_ftz: 6059 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6060 Op.getOperand(2), Op.getOperand(3)); 6061 6062 case Intrinsic::amdgcn_if_break: 6063 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6064 Op->getOperand(1), Op->getOperand(2)), 0); 6065 6066 case Intrinsic::amdgcn_groupstaticsize: { 6067 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6068 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6069 return Op; 6070 6071 const Module *M = MF.getFunction().getParent(); 6072 const GlobalValue *GV = 6073 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6074 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6075 SIInstrInfo::MO_ABS32_LO); 6076 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6077 } 6078 case Intrinsic::amdgcn_is_shared: 6079 case Intrinsic::amdgcn_is_private: { 6080 SDLoc SL(Op); 6081 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6082 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6083 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6084 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6085 Op.getOperand(1)); 6086 6087 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6088 DAG.getConstant(1, SL, MVT::i32)); 6089 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6090 } 6091 default: 6092 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6093 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6094 return lowerImage(Op, ImageDimIntr, DAG); 6095 6096 return Op; 6097 } 6098 } 6099 6100 // This function computes an appropriate offset to pass to 6101 // MachineMemOperand::setOffset() based on the offset inputs to 6102 // an intrinsic. If any of the offsets are non-contstant or 6103 // if VIndex is non-zero then this function returns 0. Otherwise, 6104 // it returns the sum of VOffset, SOffset, and Offset. 6105 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6106 SDValue SOffset, 6107 SDValue Offset, 6108 SDValue VIndex = SDValue()) { 6109 6110 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6111 !isa<ConstantSDNode>(Offset)) 6112 return 0; 6113 6114 if (VIndex) { 6115 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6116 return 0; 6117 } 6118 6119 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6120 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6121 cast<ConstantSDNode>(Offset)->getSExtValue(); 6122 } 6123 6124 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6125 SelectionDAG &DAG) const { 6126 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6127 SDLoc DL(Op); 6128 6129 switch (IntrID) { 6130 case Intrinsic::amdgcn_ds_ordered_add: 6131 case Intrinsic::amdgcn_ds_ordered_swap: { 6132 MemSDNode *M = cast<MemSDNode>(Op); 6133 SDValue Chain = M->getOperand(0); 6134 SDValue M0 = M->getOperand(2); 6135 SDValue Value = M->getOperand(3); 6136 unsigned IndexOperand = M->getConstantOperandVal(7); 6137 unsigned WaveRelease = M->getConstantOperandVal(8); 6138 unsigned WaveDone = M->getConstantOperandVal(9); 6139 unsigned ShaderType; 6140 unsigned Instruction; 6141 6142 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6143 IndexOperand &= ~0x3f; 6144 unsigned CountDw = 0; 6145 6146 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6147 CountDw = (IndexOperand >> 24) & 0xf; 6148 IndexOperand &= ~(0xf << 24); 6149 6150 if (CountDw < 1 || CountDw > 4) { 6151 report_fatal_error( 6152 "ds_ordered_count: dword count must be between 1 and 4"); 6153 } 6154 } 6155 6156 if (IndexOperand) 6157 report_fatal_error("ds_ordered_count: bad index operand"); 6158 6159 switch (IntrID) { 6160 case Intrinsic::amdgcn_ds_ordered_add: 6161 Instruction = 0; 6162 break; 6163 case Intrinsic::amdgcn_ds_ordered_swap: 6164 Instruction = 1; 6165 break; 6166 } 6167 6168 if (WaveDone && !WaveRelease) 6169 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6170 6171 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6172 case CallingConv::AMDGPU_CS: 6173 case CallingConv::AMDGPU_KERNEL: 6174 ShaderType = 0; 6175 break; 6176 case CallingConv::AMDGPU_PS: 6177 ShaderType = 1; 6178 break; 6179 case CallingConv::AMDGPU_VS: 6180 ShaderType = 2; 6181 break; 6182 case CallingConv::AMDGPU_GS: 6183 ShaderType = 3; 6184 break; 6185 default: 6186 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6187 } 6188 6189 unsigned Offset0 = OrderedCountIndex << 2; 6190 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6191 (Instruction << 4); 6192 6193 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6194 Offset1 |= (CountDw - 1) << 6; 6195 6196 unsigned Offset = Offset0 | (Offset1 << 8); 6197 6198 SDValue Ops[] = { 6199 Chain, 6200 Value, 6201 DAG.getTargetConstant(Offset, DL, MVT::i16), 6202 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6203 }; 6204 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6205 M->getVTList(), Ops, M->getMemoryVT(), 6206 M->getMemOperand()); 6207 } 6208 case Intrinsic::amdgcn_ds_fadd: { 6209 MemSDNode *M = cast<MemSDNode>(Op); 6210 unsigned Opc; 6211 switch (IntrID) { 6212 case Intrinsic::amdgcn_ds_fadd: 6213 Opc = ISD::ATOMIC_LOAD_FADD; 6214 break; 6215 } 6216 6217 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6218 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6219 M->getMemOperand()); 6220 } 6221 case Intrinsic::amdgcn_atomic_inc: 6222 case Intrinsic::amdgcn_atomic_dec: 6223 case Intrinsic::amdgcn_ds_fmin: 6224 case Intrinsic::amdgcn_ds_fmax: { 6225 MemSDNode *M = cast<MemSDNode>(Op); 6226 unsigned Opc; 6227 switch (IntrID) { 6228 case Intrinsic::amdgcn_atomic_inc: 6229 Opc = AMDGPUISD::ATOMIC_INC; 6230 break; 6231 case Intrinsic::amdgcn_atomic_dec: 6232 Opc = AMDGPUISD::ATOMIC_DEC; 6233 break; 6234 case Intrinsic::amdgcn_ds_fmin: 6235 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6236 break; 6237 case Intrinsic::amdgcn_ds_fmax: 6238 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6239 break; 6240 default: 6241 llvm_unreachable("Unknown intrinsic!"); 6242 } 6243 SDValue Ops[] = { 6244 M->getOperand(0), // Chain 6245 M->getOperand(2), // Ptr 6246 M->getOperand(3) // Value 6247 }; 6248 6249 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6250 M->getMemoryVT(), M->getMemOperand()); 6251 } 6252 case Intrinsic::amdgcn_buffer_load: 6253 case Intrinsic::amdgcn_buffer_load_format: { 6254 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6255 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6256 unsigned IdxEn = 1; 6257 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6258 IdxEn = Idx->getZExtValue() != 0; 6259 SDValue Ops[] = { 6260 Op.getOperand(0), // Chain 6261 Op.getOperand(2), // rsrc 6262 Op.getOperand(3), // vindex 6263 SDValue(), // voffset -- will be set by setBufferOffsets 6264 SDValue(), // soffset -- will be set by setBufferOffsets 6265 SDValue(), // offset -- will be set by setBufferOffsets 6266 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6267 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6268 }; 6269 6270 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6271 // We don't know the offset if vindex is non-zero, so clear it. 6272 if (IdxEn) 6273 Offset = 0; 6274 6275 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6276 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6277 6278 EVT VT = Op.getValueType(); 6279 EVT IntVT = VT.changeTypeToInteger(); 6280 auto *M = cast<MemSDNode>(Op); 6281 M->getMemOperand()->setOffset(Offset); 6282 EVT LoadVT = Op.getValueType(); 6283 6284 if (LoadVT.getScalarType() == MVT::f16) 6285 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6286 M, DAG, Ops); 6287 6288 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6289 if (LoadVT.getScalarType() == MVT::i8 || 6290 LoadVT.getScalarType() == MVT::i16) 6291 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6292 6293 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6294 M->getMemOperand(), DAG); 6295 } 6296 case Intrinsic::amdgcn_raw_buffer_load: 6297 case Intrinsic::amdgcn_raw_buffer_load_format: { 6298 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6299 6300 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6301 SDValue Ops[] = { 6302 Op.getOperand(0), // Chain 6303 Op.getOperand(2), // rsrc 6304 DAG.getConstant(0, DL, MVT::i32), // vindex 6305 Offsets.first, // voffset 6306 Op.getOperand(4), // soffset 6307 Offsets.second, // offset 6308 Op.getOperand(5), // cachepolicy, swizzled buffer 6309 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6310 }; 6311 6312 auto *M = cast<MemSDNode>(Op); 6313 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6314 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6315 } 6316 case Intrinsic::amdgcn_struct_buffer_load: 6317 case Intrinsic::amdgcn_struct_buffer_load_format: { 6318 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6319 6320 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6321 SDValue Ops[] = { 6322 Op.getOperand(0), // Chain 6323 Op.getOperand(2), // rsrc 6324 Op.getOperand(3), // vindex 6325 Offsets.first, // voffset 6326 Op.getOperand(5), // soffset 6327 Offsets.second, // offset 6328 Op.getOperand(6), // cachepolicy, swizzled buffer 6329 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6330 }; 6331 6332 auto *M = cast<MemSDNode>(Op); 6333 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6334 Ops[2])); 6335 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6336 } 6337 case Intrinsic::amdgcn_tbuffer_load: { 6338 MemSDNode *M = cast<MemSDNode>(Op); 6339 EVT LoadVT = Op.getValueType(); 6340 6341 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6342 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6343 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6344 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6345 unsigned IdxEn = 1; 6346 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6347 IdxEn = Idx->getZExtValue() != 0; 6348 SDValue Ops[] = { 6349 Op.getOperand(0), // Chain 6350 Op.getOperand(2), // rsrc 6351 Op.getOperand(3), // vindex 6352 Op.getOperand(4), // voffset 6353 Op.getOperand(5), // soffset 6354 Op.getOperand(6), // offset 6355 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6356 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6357 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6358 }; 6359 6360 if (LoadVT.getScalarType() == MVT::f16) 6361 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6362 M, DAG, Ops); 6363 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6364 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6365 DAG); 6366 } 6367 case Intrinsic::amdgcn_raw_tbuffer_load: { 6368 MemSDNode *M = cast<MemSDNode>(Op); 6369 EVT LoadVT = Op.getValueType(); 6370 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6371 6372 SDValue Ops[] = { 6373 Op.getOperand(0), // Chain 6374 Op.getOperand(2), // rsrc 6375 DAG.getConstant(0, DL, MVT::i32), // vindex 6376 Offsets.first, // voffset 6377 Op.getOperand(4), // soffset 6378 Offsets.second, // offset 6379 Op.getOperand(5), // format 6380 Op.getOperand(6), // cachepolicy, swizzled buffer 6381 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6382 }; 6383 6384 if (LoadVT.getScalarType() == MVT::f16) 6385 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6386 M, DAG, Ops); 6387 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6388 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6389 DAG); 6390 } 6391 case Intrinsic::amdgcn_struct_tbuffer_load: { 6392 MemSDNode *M = cast<MemSDNode>(Op); 6393 EVT LoadVT = Op.getValueType(); 6394 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6395 6396 SDValue Ops[] = { 6397 Op.getOperand(0), // Chain 6398 Op.getOperand(2), // rsrc 6399 Op.getOperand(3), // vindex 6400 Offsets.first, // voffset 6401 Op.getOperand(5), // soffset 6402 Offsets.second, // offset 6403 Op.getOperand(6), // format 6404 Op.getOperand(7), // cachepolicy, swizzled buffer 6405 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6406 }; 6407 6408 if (LoadVT.getScalarType() == MVT::f16) 6409 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6410 M, DAG, Ops); 6411 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6412 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6413 DAG); 6414 } 6415 case Intrinsic::amdgcn_buffer_atomic_swap: 6416 case Intrinsic::amdgcn_buffer_atomic_add: 6417 case Intrinsic::amdgcn_buffer_atomic_sub: 6418 case Intrinsic::amdgcn_buffer_atomic_smin: 6419 case Intrinsic::amdgcn_buffer_atomic_umin: 6420 case Intrinsic::amdgcn_buffer_atomic_smax: 6421 case Intrinsic::amdgcn_buffer_atomic_umax: 6422 case Intrinsic::amdgcn_buffer_atomic_and: 6423 case Intrinsic::amdgcn_buffer_atomic_or: 6424 case Intrinsic::amdgcn_buffer_atomic_xor: { 6425 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6426 unsigned IdxEn = 1; 6427 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6428 IdxEn = Idx->getZExtValue() != 0; 6429 SDValue Ops[] = { 6430 Op.getOperand(0), // Chain 6431 Op.getOperand(2), // vdata 6432 Op.getOperand(3), // rsrc 6433 Op.getOperand(4), // vindex 6434 SDValue(), // voffset -- will be set by setBufferOffsets 6435 SDValue(), // soffset -- will be set by setBufferOffsets 6436 SDValue(), // offset -- will be set by setBufferOffsets 6437 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6438 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6439 }; 6440 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6441 // We don't know the offset if vindex is non-zero, so clear it. 6442 if (IdxEn) 6443 Offset = 0; 6444 EVT VT = Op.getValueType(); 6445 6446 auto *M = cast<MemSDNode>(Op); 6447 M->getMemOperand()->setOffset(Offset); 6448 unsigned Opcode = 0; 6449 6450 switch (IntrID) { 6451 case Intrinsic::amdgcn_buffer_atomic_swap: 6452 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6453 break; 6454 case Intrinsic::amdgcn_buffer_atomic_add: 6455 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6456 break; 6457 case Intrinsic::amdgcn_buffer_atomic_sub: 6458 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6459 break; 6460 case Intrinsic::amdgcn_buffer_atomic_smin: 6461 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6462 break; 6463 case Intrinsic::amdgcn_buffer_atomic_umin: 6464 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6465 break; 6466 case Intrinsic::amdgcn_buffer_atomic_smax: 6467 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6468 break; 6469 case Intrinsic::amdgcn_buffer_atomic_umax: 6470 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6471 break; 6472 case Intrinsic::amdgcn_buffer_atomic_and: 6473 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6474 break; 6475 case Intrinsic::amdgcn_buffer_atomic_or: 6476 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6477 break; 6478 case Intrinsic::amdgcn_buffer_atomic_xor: 6479 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6480 break; 6481 default: 6482 llvm_unreachable("unhandled atomic opcode"); 6483 } 6484 6485 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6486 M->getMemOperand()); 6487 } 6488 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6489 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6490 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6491 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6492 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6493 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6494 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6495 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6496 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6497 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6498 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6499 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6500 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6501 SDValue Ops[] = { 6502 Op.getOperand(0), // Chain 6503 Op.getOperand(2), // vdata 6504 Op.getOperand(3), // rsrc 6505 DAG.getConstant(0, DL, MVT::i32), // vindex 6506 Offsets.first, // voffset 6507 Op.getOperand(5), // soffset 6508 Offsets.second, // offset 6509 Op.getOperand(6), // cachepolicy 6510 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6511 }; 6512 EVT VT = Op.getValueType(); 6513 6514 auto *M = cast<MemSDNode>(Op); 6515 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6516 unsigned Opcode = 0; 6517 6518 switch (IntrID) { 6519 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6520 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6521 break; 6522 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6523 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6524 break; 6525 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6526 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6527 break; 6528 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6529 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6530 break; 6531 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6532 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6533 break; 6534 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6535 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6536 break; 6537 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6538 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6539 break; 6540 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6541 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6542 break; 6543 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6544 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6545 break; 6546 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6547 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6548 break; 6549 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6550 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6551 break; 6552 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6553 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6554 break; 6555 default: 6556 llvm_unreachable("unhandled atomic opcode"); 6557 } 6558 6559 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6560 M->getMemOperand()); 6561 } 6562 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6563 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6564 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6565 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6566 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6567 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6568 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6569 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6570 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6571 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6572 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6573 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6574 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6575 SDValue Ops[] = { 6576 Op.getOperand(0), // Chain 6577 Op.getOperand(2), // vdata 6578 Op.getOperand(3), // rsrc 6579 Op.getOperand(4), // vindex 6580 Offsets.first, // voffset 6581 Op.getOperand(6), // soffset 6582 Offsets.second, // offset 6583 Op.getOperand(7), // cachepolicy 6584 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6585 }; 6586 EVT VT = Op.getValueType(); 6587 6588 auto *M = cast<MemSDNode>(Op); 6589 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6590 Ops[3])); 6591 unsigned Opcode = 0; 6592 6593 switch (IntrID) { 6594 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6595 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6596 break; 6597 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6598 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6599 break; 6600 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6601 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6602 break; 6603 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6604 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6605 break; 6606 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6607 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6608 break; 6609 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6610 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6611 break; 6612 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6613 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6614 break; 6615 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6616 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6617 break; 6618 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6619 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6620 break; 6621 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6622 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6623 break; 6624 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6625 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6626 break; 6627 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6628 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6629 break; 6630 default: 6631 llvm_unreachable("unhandled atomic opcode"); 6632 } 6633 6634 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6635 M->getMemOperand()); 6636 } 6637 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6638 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6639 unsigned IdxEn = 1; 6640 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6641 IdxEn = Idx->getZExtValue() != 0; 6642 SDValue Ops[] = { 6643 Op.getOperand(0), // Chain 6644 Op.getOperand(2), // src 6645 Op.getOperand(3), // cmp 6646 Op.getOperand(4), // rsrc 6647 Op.getOperand(5), // vindex 6648 SDValue(), // voffset -- will be set by setBufferOffsets 6649 SDValue(), // soffset -- will be set by setBufferOffsets 6650 SDValue(), // offset -- will be set by setBufferOffsets 6651 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6652 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6653 }; 6654 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6655 // We don't know the offset if vindex is non-zero, so clear it. 6656 if (IdxEn) 6657 Offset = 0; 6658 EVT VT = Op.getValueType(); 6659 auto *M = cast<MemSDNode>(Op); 6660 M->getMemOperand()->setOffset(Offset); 6661 6662 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6663 Op->getVTList(), Ops, VT, M->getMemOperand()); 6664 } 6665 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6666 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6667 SDValue Ops[] = { 6668 Op.getOperand(0), // Chain 6669 Op.getOperand(2), // src 6670 Op.getOperand(3), // cmp 6671 Op.getOperand(4), // rsrc 6672 DAG.getConstant(0, DL, MVT::i32), // vindex 6673 Offsets.first, // voffset 6674 Op.getOperand(6), // soffset 6675 Offsets.second, // offset 6676 Op.getOperand(7), // cachepolicy 6677 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6678 }; 6679 EVT VT = Op.getValueType(); 6680 auto *M = cast<MemSDNode>(Op); 6681 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6682 6683 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6684 Op->getVTList(), Ops, VT, M->getMemOperand()); 6685 } 6686 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6687 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6688 SDValue Ops[] = { 6689 Op.getOperand(0), // Chain 6690 Op.getOperand(2), // src 6691 Op.getOperand(3), // cmp 6692 Op.getOperand(4), // rsrc 6693 Op.getOperand(5), // vindex 6694 Offsets.first, // voffset 6695 Op.getOperand(7), // soffset 6696 Offsets.second, // offset 6697 Op.getOperand(8), // cachepolicy 6698 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6699 }; 6700 EVT VT = Op.getValueType(); 6701 auto *M = cast<MemSDNode>(Op); 6702 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6703 Ops[4])); 6704 6705 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6706 Op->getVTList(), Ops, VT, M->getMemOperand()); 6707 } 6708 6709 default: 6710 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6711 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6712 return lowerImage(Op, ImageDimIntr, DAG); 6713 6714 return SDValue(); 6715 } 6716 } 6717 6718 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6719 // dwordx4 if on SI. 6720 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6721 SDVTList VTList, 6722 ArrayRef<SDValue> Ops, EVT MemVT, 6723 MachineMemOperand *MMO, 6724 SelectionDAG &DAG) const { 6725 EVT VT = VTList.VTs[0]; 6726 EVT WidenedVT = VT; 6727 EVT WidenedMemVT = MemVT; 6728 if (!Subtarget->hasDwordx3LoadStores() && 6729 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6730 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6731 WidenedVT.getVectorElementType(), 4); 6732 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6733 WidenedMemVT.getVectorElementType(), 4); 6734 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6735 } 6736 6737 assert(VTList.NumVTs == 2); 6738 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6739 6740 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6741 WidenedMemVT, MMO); 6742 if (WidenedVT != VT) { 6743 auto Extract = DAG.getNode( 6744 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6745 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6746 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6747 } 6748 return NewOp; 6749 } 6750 6751 SDValue SITargetLowering::handleD16VData(SDValue VData, 6752 SelectionDAG &DAG) const { 6753 EVT StoreVT = VData.getValueType(); 6754 6755 // No change for f16 and legal vector D16 types. 6756 if (!StoreVT.isVector()) 6757 return VData; 6758 6759 SDLoc DL(VData); 6760 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6761 6762 if (Subtarget->hasUnpackedD16VMem()) { 6763 // We need to unpack the packed data to store. 6764 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6765 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6766 6767 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6768 StoreVT.getVectorNumElements()); 6769 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6770 return DAG.UnrollVectorOp(ZExt.getNode()); 6771 } 6772 6773 assert(isTypeLegal(StoreVT)); 6774 return VData; 6775 } 6776 6777 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6778 SelectionDAG &DAG) const { 6779 SDLoc DL(Op); 6780 SDValue Chain = Op.getOperand(0); 6781 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6782 MachineFunction &MF = DAG.getMachineFunction(); 6783 6784 switch (IntrinsicID) { 6785 case Intrinsic::amdgcn_exp_compr: { 6786 SDValue Src0 = Op.getOperand(4); 6787 SDValue Src1 = Op.getOperand(5); 6788 // Hack around illegal type on SI by directly selecting it. 6789 if (isTypeLegal(Src0.getValueType())) 6790 return SDValue(); 6791 6792 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6793 SDValue Undef = DAG.getUNDEF(MVT::f32); 6794 const SDValue Ops[] = { 6795 Op.getOperand(2), // tgt 6796 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6797 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6798 Undef, // src2 6799 Undef, // src3 6800 Op.getOperand(7), // vm 6801 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6802 Op.getOperand(3), // en 6803 Op.getOperand(0) // Chain 6804 }; 6805 6806 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6807 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6808 } 6809 case Intrinsic::amdgcn_s_barrier: { 6810 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6811 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6812 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6813 if (WGSize <= ST.getWavefrontSize()) 6814 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6815 Op.getOperand(0)), 0); 6816 } 6817 return SDValue(); 6818 }; 6819 case Intrinsic::amdgcn_tbuffer_store: { 6820 SDValue VData = Op.getOperand(2); 6821 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6822 if (IsD16) 6823 VData = handleD16VData(VData, DAG); 6824 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6825 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6826 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6827 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6828 unsigned IdxEn = 1; 6829 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6830 IdxEn = Idx->getZExtValue() != 0; 6831 SDValue Ops[] = { 6832 Chain, 6833 VData, // vdata 6834 Op.getOperand(3), // rsrc 6835 Op.getOperand(4), // vindex 6836 Op.getOperand(5), // voffset 6837 Op.getOperand(6), // soffset 6838 Op.getOperand(7), // offset 6839 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6840 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6841 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6842 }; 6843 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6844 AMDGPUISD::TBUFFER_STORE_FORMAT; 6845 MemSDNode *M = cast<MemSDNode>(Op); 6846 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6847 M->getMemoryVT(), M->getMemOperand()); 6848 } 6849 6850 case Intrinsic::amdgcn_struct_tbuffer_store: { 6851 SDValue VData = Op.getOperand(2); 6852 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6853 if (IsD16) 6854 VData = handleD16VData(VData, DAG); 6855 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6856 SDValue Ops[] = { 6857 Chain, 6858 VData, // vdata 6859 Op.getOperand(3), // rsrc 6860 Op.getOperand(4), // vindex 6861 Offsets.first, // voffset 6862 Op.getOperand(6), // soffset 6863 Offsets.second, // offset 6864 Op.getOperand(7), // format 6865 Op.getOperand(8), // cachepolicy, swizzled buffer 6866 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6867 }; 6868 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6869 AMDGPUISD::TBUFFER_STORE_FORMAT; 6870 MemSDNode *M = cast<MemSDNode>(Op); 6871 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6872 M->getMemoryVT(), M->getMemOperand()); 6873 } 6874 6875 case Intrinsic::amdgcn_raw_tbuffer_store: { 6876 SDValue VData = Op.getOperand(2); 6877 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6878 if (IsD16) 6879 VData = handleD16VData(VData, DAG); 6880 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6881 SDValue Ops[] = { 6882 Chain, 6883 VData, // vdata 6884 Op.getOperand(3), // rsrc 6885 DAG.getConstant(0, DL, MVT::i32), // vindex 6886 Offsets.first, // voffset 6887 Op.getOperand(5), // soffset 6888 Offsets.second, // offset 6889 Op.getOperand(6), // format 6890 Op.getOperand(7), // cachepolicy, swizzled buffer 6891 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6892 }; 6893 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6894 AMDGPUISD::TBUFFER_STORE_FORMAT; 6895 MemSDNode *M = cast<MemSDNode>(Op); 6896 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6897 M->getMemoryVT(), M->getMemOperand()); 6898 } 6899 6900 case Intrinsic::amdgcn_buffer_store: 6901 case Intrinsic::amdgcn_buffer_store_format: { 6902 SDValue VData = Op.getOperand(2); 6903 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6904 if (IsD16) 6905 VData = handleD16VData(VData, DAG); 6906 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6907 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6908 unsigned IdxEn = 1; 6909 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6910 IdxEn = Idx->getZExtValue() != 0; 6911 SDValue Ops[] = { 6912 Chain, 6913 VData, 6914 Op.getOperand(3), // rsrc 6915 Op.getOperand(4), // vindex 6916 SDValue(), // voffset -- will be set by setBufferOffsets 6917 SDValue(), // soffset -- will be set by setBufferOffsets 6918 SDValue(), // offset -- will be set by setBufferOffsets 6919 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6920 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6921 }; 6922 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6923 // We don't know the offset if vindex is non-zero, so clear it. 6924 if (IdxEn) 6925 Offset = 0; 6926 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6927 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6928 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6929 MemSDNode *M = cast<MemSDNode>(Op); 6930 M->getMemOperand()->setOffset(Offset); 6931 6932 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6933 EVT VDataType = VData.getValueType().getScalarType(); 6934 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6935 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6936 6937 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6938 M->getMemoryVT(), M->getMemOperand()); 6939 } 6940 6941 case Intrinsic::amdgcn_raw_buffer_store: 6942 case Intrinsic::amdgcn_raw_buffer_store_format: { 6943 const bool IsFormat = 6944 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6945 6946 SDValue VData = Op.getOperand(2); 6947 EVT VDataVT = VData.getValueType(); 6948 EVT EltType = VDataVT.getScalarType(); 6949 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6950 if (IsD16) 6951 VData = handleD16VData(VData, DAG); 6952 6953 if (!isTypeLegal(VDataVT)) { 6954 VData = 6955 DAG.getNode(ISD::BITCAST, DL, 6956 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6957 } 6958 6959 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6960 SDValue Ops[] = { 6961 Chain, 6962 VData, 6963 Op.getOperand(3), // rsrc 6964 DAG.getConstant(0, DL, MVT::i32), // vindex 6965 Offsets.first, // voffset 6966 Op.getOperand(5), // soffset 6967 Offsets.second, // offset 6968 Op.getOperand(6), // cachepolicy, swizzled buffer 6969 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6970 }; 6971 unsigned Opc = 6972 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6973 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6974 MemSDNode *M = cast<MemSDNode>(Op); 6975 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6976 6977 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6978 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6979 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 6980 6981 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6982 M->getMemoryVT(), M->getMemOperand()); 6983 } 6984 6985 case Intrinsic::amdgcn_struct_buffer_store: 6986 case Intrinsic::amdgcn_struct_buffer_store_format: { 6987 const bool IsFormat = 6988 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 6989 6990 SDValue VData = Op.getOperand(2); 6991 EVT VDataVT = VData.getValueType(); 6992 EVT EltType = VDataVT.getScalarType(); 6993 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6994 6995 if (IsD16) 6996 VData = handleD16VData(VData, DAG); 6997 6998 if (!isTypeLegal(VDataVT)) { 6999 VData = 7000 DAG.getNode(ISD::BITCAST, DL, 7001 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7002 } 7003 7004 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7005 SDValue Ops[] = { 7006 Chain, 7007 VData, 7008 Op.getOperand(3), // rsrc 7009 Op.getOperand(4), // vindex 7010 Offsets.first, // voffset 7011 Op.getOperand(6), // soffset 7012 Offsets.second, // offset 7013 Op.getOperand(7), // cachepolicy, swizzled buffer 7014 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7015 }; 7016 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7017 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7018 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7019 MemSDNode *M = cast<MemSDNode>(Op); 7020 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7021 Ops[3])); 7022 7023 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7024 EVT VDataType = VData.getValueType().getScalarType(); 7025 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7026 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7027 7028 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7029 M->getMemoryVT(), M->getMemOperand()); 7030 } 7031 7032 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7033 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7034 unsigned IdxEn = 1; 7035 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7036 IdxEn = Idx->getZExtValue() != 0; 7037 SDValue Ops[] = { 7038 Chain, 7039 Op.getOperand(2), // vdata 7040 Op.getOperand(3), // rsrc 7041 Op.getOperand(4), // vindex 7042 SDValue(), // voffset -- will be set by setBufferOffsets 7043 SDValue(), // soffset -- will be set by setBufferOffsets 7044 SDValue(), // offset -- will be set by setBufferOffsets 7045 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7046 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7047 }; 7048 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7049 // We don't know the offset if vindex is non-zero, so clear it. 7050 if (IdxEn) 7051 Offset = 0; 7052 EVT VT = Op.getOperand(2).getValueType(); 7053 7054 auto *M = cast<MemSDNode>(Op); 7055 M->getMemOperand()->setOffset(Offset); 7056 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7057 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7058 7059 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7060 M->getMemOperand()); 7061 } 7062 7063 case Intrinsic::amdgcn_global_atomic_fadd: { 7064 SDValue Ops[] = { 7065 Chain, 7066 Op.getOperand(2), // ptr 7067 Op.getOperand(3) // vdata 7068 }; 7069 EVT VT = Op.getOperand(3).getValueType(); 7070 7071 auto *M = cast<MemSDNode>(Op); 7072 if (VT.isVector()) { 7073 return DAG.getMemIntrinsicNode( 7074 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7075 M->getMemOperand()); 7076 } 7077 7078 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7079 DAG.getVTList(VT, MVT::Other), Ops, 7080 M->getMemOperand()).getValue(1); 7081 } 7082 case Intrinsic::amdgcn_end_cf: 7083 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7084 Op->getOperand(2), Chain), 0); 7085 7086 default: { 7087 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7088 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7089 return lowerImage(Op, ImageDimIntr, DAG); 7090 7091 return Op; 7092 } 7093 } 7094 } 7095 7096 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7097 // offset (the offset that is included in bounds checking and swizzling, to be 7098 // split between the instruction's voffset and immoffset fields) and soffset 7099 // (the offset that is excluded from bounds checking and swizzling, to go in 7100 // the instruction's soffset field). This function takes the first kind of 7101 // offset and figures out how to split it between voffset and immoffset. 7102 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7103 SDValue Offset, SelectionDAG &DAG) const { 7104 SDLoc DL(Offset); 7105 const unsigned MaxImm = 4095; 7106 SDValue N0 = Offset; 7107 ConstantSDNode *C1 = nullptr; 7108 7109 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7110 N0 = SDValue(); 7111 else if (DAG.isBaseWithConstantOffset(N0)) { 7112 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7113 N0 = N0.getOperand(0); 7114 } 7115 7116 if (C1) { 7117 unsigned ImmOffset = C1->getZExtValue(); 7118 // If the immediate value is too big for the immoffset field, put the value 7119 // and -4096 into the immoffset field so that the value that is copied/added 7120 // for the voffset field is a multiple of 4096, and it stands more chance 7121 // of being CSEd with the copy/add for another similar load/store. 7122 // However, do not do that rounding down to a multiple of 4096 if that is a 7123 // negative number, as it appears to be illegal to have a negative offset 7124 // in the vgpr, even if adding the immediate offset makes it positive. 7125 unsigned Overflow = ImmOffset & ~MaxImm; 7126 ImmOffset -= Overflow; 7127 if ((int32_t)Overflow < 0) { 7128 Overflow += ImmOffset; 7129 ImmOffset = 0; 7130 } 7131 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7132 if (Overflow) { 7133 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7134 if (!N0) 7135 N0 = OverflowVal; 7136 else { 7137 SDValue Ops[] = { N0, OverflowVal }; 7138 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7139 } 7140 } 7141 } 7142 if (!N0) 7143 N0 = DAG.getConstant(0, DL, MVT::i32); 7144 if (!C1) 7145 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7146 return {N0, SDValue(C1, 0)}; 7147 } 7148 7149 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7150 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7151 // pointed to by Offsets. 7152 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7153 SelectionDAG &DAG, SDValue *Offsets, 7154 unsigned Align) const { 7155 SDLoc DL(CombinedOffset); 7156 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7157 uint32_t Imm = C->getZExtValue(); 7158 uint32_t SOffset, ImmOffset; 7159 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7160 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7161 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7162 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7163 return SOffset + ImmOffset; 7164 } 7165 } 7166 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7167 SDValue N0 = CombinedOffset.getOperand(0); 7168 SDValue N1 = CombinedOffset.getOperand(1); 7169 uint32_t SOffset, ImmOffset; 7170 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7171 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7172 Subtarget, Align)) { 7173 Offsets[0] = N0; 7174 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7175 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7176 return 0; 7177 } 7178 } 7179 Offsets[0] = CombinedOffset; 7180 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7181 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7182 return 0; 7183 } 7184 7185 // Handle 8 bit and 16 bit buffer loads 7186 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7187 EVT LoadVT, SDLoc DL, 7188 ArrayRef<SDValue> Ops, 7189 MemSDNode *M) const { 7190 EVT IntVT = LoadVT.changeTypeToInteger(); 7191 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7192 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7193 7194 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7195 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7196 Ops, IntVT, 7197 M->getMemOperand()); 7198 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7199 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7200 7201 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7202 } 7203 7204 // Handle 8 bit and 16 bit buffer stores 7205 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7206 EVT VDataType, SDLoc DL, 7207 SDValue Ops[], 7208 MemSDNode *M) const { 7209 if (VDataType == MVT::f16) 7210 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7211 7212 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7213 Ops[1] = BufferStoreExt; 7214 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7215 AMDGPUISD::BUFFER_STORE_SHORT; 7216 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7217 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7218 M->getMemOperand()); 7219 } 7220 7221 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7222 ISD::LoadExtType ExtType, SDValue Op, 7223 const SDLoc &SL, EVT VT) { 7224 if (VT.bitsLT(Op.getValueType())) 7225 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7226 7227 switch (ExtType) { 7228 case ISD::SEXTLOAD: 7229 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7230 case ISD::ZEXTLOAD: 7231 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7232 case ISD::EXTLOAD: 7233 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7234 case ISD::NON_EXTLOAD: 7235 return Op; 7236 } 7237 7238 llvm_unreachable("invalid ext type"); 7239 } 7240 7241 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7242 SelectionDAG &DAG = DCI.DAG; 7243 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7244 return SDValue(); 7245 7246 // FIXME: Constant loads should all be marked invariant. 7247 unsigned AS = Ld->getAddressSpace(); 7248 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7249 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7250 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7251 return SDValue(); 7252 7253 // Don't do this early, since it may interfere with adjacent load merging for 7254 // illegal types. We can avoid losing alignment information for exotic types 7255 // pre-legalize. 7256 EVT MemVT = Ld->getMemoryVT(); 7257 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7258 MemVT.getSizeInBits() >= 32) 7259 return SDValue(); 7260 7261 SDLoc SL(Ld); 7262 7263 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7264 "unexpected vector extload"); 7265 7266 // TODO: Drop only high part of range. 7267 SDValue Ptr = Ld->getBasePtr(); 7268 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7269 MVT::i32, SL, Ld->getChain(), Ptr, 7270 Ld->getOffset(), 7271 Ld->getPointerInfo(), MVT::i32, 7272 Ld->getAlignment(), 7273 Ld->getMemOperand()->getFlags(), 7274 Ld->getAAInfo(), 7275 nullptr); // Drop ranges 7276 7277 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7278 if (MemVT.isFloatingPoint()) { 7279 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7280 "unexpected fp extload"); 7281 TruncVT = MemVT.changeTypeToInteger(); 7282 } 7283 7284 SDValue Cvt = NewLoad; 7285 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7286 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7287 DAG.getValueType(TruncVT)); 7288 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7289 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7290 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7291 } else { 7292 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7293 } 7294 7295 EVT VT = Ld->getValueType(0); 7296 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7297 7298 DCI.AddToWorklist(Cvt.getNode()); 7299 7300 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7301 // the appropriate extension from the 32-bit load. 7302 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7303 DCI.AddToWorklist(Cvt.getNode()); 7304 7305 // Handle conversion back to floating point if necessary. 7306 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7307 7308 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7309 } 7310 7311 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7312 SDLoc DL(Op); 7313 LoadSDNode *Load = cast<LoadSDNode>(Op); 7314 ISD::LoadExtType ExtType = Load->getExtensionType(); 7315 EVT MemVT = Load->getMemoryVT(); 7316 7317 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7318 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7319 return SDValue(); 7320 7321 // FIXME: Copied from PPC 7322 // First, load into 32 bits, then truncate to 1 bit. 7323 7324 SDValue Chain = Load->getChain(); 7325 SDValue BasePtr = Load->getBasePtr(); 7326 MachineMemOperand *MMO = Load->getMemOperand(); 7327 7328 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7329 7330 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7331 BasePtr, RealMemVT, MMO); 7332 7333 if (!MemVT.isVector()) { 7334 SDValue Ops[] = { 7335 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7336 NewLD.getValue(1) 7337 }; 7338 7339 return DAG.getMergeValues(Ops, DL); 7340 } 7341 7342 SmallVector<SDValue, 3> Elts; 7343 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7344 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7345 DAG.getConstant(I, DL, MVT::i32)); 7346 7347 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7348 } 7349 7350 SDValue Ops[] = { 7351 DAG.getBuildVector(MemVT, DL, Elts), 7352 NewLD.getValue(1) 7353 }; 7354 7355 return DAG.getMergeValues(Ops, DL); 7356 } 7357 7358 if (!MemVT.isVector()) 7359 return SDValue(); 7360 7361 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7362 "Custom lowering for non-i32 vectors hasn't been implemented."); 7363 7364 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7365 MemVT, *Load->getMemOperand())) { 7366 SDValue Ops[2]; 7367 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7368 return DAG.getMergeValues(Ops, DL); 7369 } 7370 7371 unsigned Alignment = Load->getAlignment(); 7372 unsigned AS = Load->getAddressSpace(); 7373 if (Subtarget->hasLDSMisalignedBug() && 7374 AS == AMDGPUAS::FLAT_ADDRESS && 7375 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7376 return SplitVectorLoad(Op, DAG); 7377 } 7378 7379 MachineFunction &MF = DAG.getMachineFunction(); 7380 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7381 // If there is a possibilty that flat instruction access scratch memory 7382 // then we need to use the same legalization rules we use for private. 7383 if (AS == AMDGPUAS::FLAT_ADDRESS) 7384 AS = MFI->hasFlatScratchInit() ? 7385 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7386 7387 unsigned NumElements = MemVT.getVectorNumElements(); 7388 7389 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7390 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7391 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7392 if (MemVT.isPow2VectorType()) 7393 return SDValue(); 7394 if (NumElements == 3) 7395 return WidenVectorLoad(Op, DAG); 7396 return SplitVectorLoad(Op, DAG); 7397 } 7398 // Non-uniform loads will be selected to MUBUF instructions, so they 7399 // have the same legalization requirements as global and private 7400 // loads. 7401 // 7402 } 7403 7404 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7405 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7406 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7407 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7408 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7409 Alignment >= 4 && NumElements < 32) { 7410 if (MemVT.isPow2VectorType()) 7411 return SDValue(); 7412 if (NumElements == 3) 7413 return WidenVectorLoad(Op, DAG); 7414 return SplitVectorLoad(Op, DAG); 7415 } 7416 // Non-uniform loads will be selected to MUBUF instructions, so they 7417 // have the same legalization requirements as global and private 7418 // loads. 7419 // 7420 } 7421 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7422 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7423 AS == AMDGPUAS::GLOBAL_ADDRESS || 7424 AS == AMDGPUAS::FLAT_ADDRESS) { 7425 if (NumElements > 4) 7426 return SplitVectorLoad(Op, DAG); 7427 // v3 loads not supported on SI. 7428 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7429 return WidenVectorLoad(Op, DAG); 7430 // v3 and v4 loads are supported for private and global memory. 7431 return SDValue(); 7432 } 7433 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7434 // Depending on the setting of the private_element_size field in the 7435 // resource descriptor, we can only make private accesses up to a certain 7436 // size. 7437 switch (Subtarget->getMaxPrivateElementSize()) { 7438 case 4: { 7439 SDValue Ops[2]; 7440 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7441 return DAG.getMergeValues(Ops, DL); 7442 } 7443 case 8: 7444 if (NumElements > 2) 7445 return SplitVectorLoad(Op, DAG); 7446 return SDValue(); 7447 case 16: 7448 // Same as global/flat 7449 if (NumElements > 4) 7450 return SplitVectorLoad(Op, DAG); 7451 // v3 loads not supported on SI. 7452 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7453 return WidenVectorLoad(Op, DAG); 7454 return SDValue(); 7455 default: 7456 llvm_unreachable("unsupported private_element_size"); 7457 } 7458 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7459 // Use ds_read_b128 if possible. 7460 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7461 MemVT.getStoreSize() == 16) 7462 return SDValue(); 7463 7464 if (NumElements > 2) 7465 return SplitVectorLoad(Op, DAG); 7466 7467 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7468 // address is negative, then the instruction is incorrectly treated as 7469 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7470 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7471 // load later in the SILoadStoreOptimizer. 7472 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7473 NumElements == 2 && MemVT.getStoreSize() == 8 && 7474 Load->getAlignment() < 8) { 7475 return SplitVectorLoad(Op, DAG); 7476 } 7477 } 7478 return SDValue(); 7479 } 7480 7481 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7482 EVT VT = Op.getValueType(); 7483 assert(VT.getSizeInBits() == 64); 7484 7485 SDLoc DL(Op); 7486 SDValue Cond = Op.getOperand(0); 7487 7488 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7489 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7490 7491 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7492 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7493 7494 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7495 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7496 7497 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7498 7499 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7500 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7501 7502 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7503 7504 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7505 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7506 } 7507 7508 // Catch division cases where we can use shortcuts with rcp and rsq 7509 // instructions. 7510 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7511 SelectionDAG &DAG) const { 7512 SDLoc SL(Op); 7513 SDValue LHS = Op.getOperand(0); 7514 SDValue RHS = Op.getOperand(1); 7515 EVT VT = Op.getValueType(); 7516 const SDNodeFlags Flags = Op->getFlags(); 7517 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7518 7519 if (!Unsafe && VT == MVT::f32 && hasFP32Denormals(DAG.getMachineFunction())) 7520 return SDValue(); 7521 7522 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7523 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7524 if (CLHS->isExactlyValue(1.0)) { 7525 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7526 // the CI documentation has a worst case error of 1 ulp. 7527 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7528 // use it as long as we aren't trying to use denormals. 7529 // 7530 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7531 7532 // 1.0 / sqrt(x) -> rsq(x) 7533 7534 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7535 // error seems really high at 2^29 ULP. 7536 if (RHS.getOpcode() == ISD::FSQRT) 7537 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7538 7539 // 1.0 / x -> rcp(x) 7540 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7541 } 7542 7543 // Same as for 1.0, but expand the sign out of the constant. 7544 if (CLHS->isExactlyValue(-1.0)) { 7545 // -1.0 / x -> rcp (fneg x) 7546 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7547 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7548 } 7549 } 7550 } 7551 7552 if (Unsafe) { 7553 // Turn into multiply by the reciprocal. 7554 // x / y -> x * (1.0 / y) 7555 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7556 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7557 } 7558 7559 return SDValue(); 7560 } 7561 7562 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7563 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7564 if (GlueChain->getNumValues() <= 1) { 7565 return DAG.getNode(Opcode, SL, VT, A, B); 7566 } 7567 7568 assert(GlueChain->getNumValues() == 3); 7569 7570 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7571 switch (Opcode) { 7572 default: llvm_unreachable("no chain equivalent for opcode"); 7573 case ISD::FMUL: 7574 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7575 break; 7576 } 7577 7578 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7579 GlueChain.getValue(2)); 7580 } 7581 7582 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7583 EVT VT, SDValue A, SDValue B, SDValue C, 7584 SDValue GlueChain) { 7585 if (GlueChain->getNumValues() <= 1) { 7586 return DAG.getNode(Opcode, SL, VT, A, B, C); 7587 } 7588 7589 assert(GlueChain->getNumValues() == 3); 7590 7591 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7592 switch (Opcode) { 7593 default: llvm_unreachable("no chain equivalent for opcode"); 7594 case ISD::FMA: 7595 Opcode = AMDGPUISD::FMA_W_CHAIN; 7596 break; 7597 } 7598 7599 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7600 GlueChain.getValue(2)); 7601 } 7602 7603 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7604 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7605 return FastLowered; 7606 7607 SDLoc SL(Op); 7608 SDValue Src0 = Op.getOperand(0); 7609 SDValue Src1 = Op.getOperand(1); 7610 7611 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7612 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7613 7614 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7615 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7616 7617 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7618 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7619 7620 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7621 } 7622 7623 // Faster 2.5 ULP division that does not support denormals. 7624 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7625 SDLoc SL(Op); 7626 SDValue LHS = Op.getOperand(1); 7627 SDValue RHS = Op.getOperand(2); 7628 7629 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7630 7631 const APFloat K0Val(BitsToFloat(0x6f800000)); 7632 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7633 7634 const APFloat K1Val(BitsToFloat(0x2f800000)); 7635 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7636 7637 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7638 7639 EVT SetCCVT = 7640 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7641 7642 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7643 7644 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7645 7646 // TODO: Should this propagate fast-math-flags? 7647 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7648 7649 // rcp does not support denormals. 7650 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7651 7652 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7653 7654 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7655 } 7656 7657 // Returns immediate value for setting the F32 denorm mode when using the 7658 // S_DENORM_MODE instruction. 7659 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7660 const SDLoc &SL, const GCNSubtarget *ST) { 7661 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7662 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7663 ? FP_DENORM_FLUSH_NONE 7664 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7665 7666 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7667 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7668 } 7669 7670 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7671 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7672 return FastLowered; 7673 7674 SDLoc SL(Op); 7675 SDValue LHS = Op.getOperand(0); 7676 SDValue RHS = Op.getOperand(1); 7677 7678 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7679 7680 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7681 7682 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7683 RHS, RHS, LHS); 7684 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7685 LHS, RHS, LHS); 7686 7687 // Denominator is scaled to not be denormal, so using rcp is ok. 7688 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7689 DenominatorScaled); 7690 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7691 DenominatorScaled); 7692 7693 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7694 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7695 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7696 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7697 7698 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7699 7700 if (!HasFP32Denormals) { 7701 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7702 7703 SDValue EnableDenorm; 7704 if (Subtarget->hasDenormModeInst()) { 7705 const SDValue EnableDenormValue = 7706 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7707 7708 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7709 DAG.getEntryNode(), EnableDenormValue); 7710 } else { 7711 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7712 SL, MVT::i32); 7713 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7714 DAG.getEntryNode(), EnableDenormValue, 7715 BitField); 7716 } 7717 7718 SDValue Ops[3] = { 7719 NegDivScale0, 7720 EnableDenorm.getValue(0), 7721 EnableDenorm.getValue(1) 7722 }; 7723 7724 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7725 } 7726 7727 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7728 ApproxRcp, One, NegDivScale0); 7729 7730 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7731 ApproxRcp, Fma0); 7732 7733 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7734 Fma1, Fma1); 7735 7736 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7737 NumeratorScaled, Mul); 7738 7739 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7740 7741 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7742 NumeratorScaled, Fma3); 7743 7744 if (!HasFP32Denormals) { 7745 SDValue DisableDenorm; 7746 if (Subtarget->hasDenormModeInst()) { 7747 const SDValue DisableDenormValue = 7748 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7749 7750 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7751 Fma4.getValue(1), DisableDenormValue, 7752 Fma4.getValue(2)); 7753 } else { 7754 const SDValue DisableDenormValue = 7755 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7756 7757 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7758 Fma4.getValue(1), DisableDenormValue, 7759 BitField, Fma4.getValue(2)); 7760 } 7761 7762 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7763 DisableDenorm, DAG.getRoot()); 7764 DAG.setRoot(OutputChain); 7765 } 7766 7767 SDValue Scale = NumeratorScaled.getValue(1); 7768 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7769 Fma4, Fma1, Fma3, Scale); 7770 7771 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7772 } 7773 7774 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7775 if (DAG.getTarget().Options.UnsafeFPMath) 7776 return lowerFastUnsafeFDIV(Op, DAG); 7777 7778 SDLoc SL(Op); 7779 SDValue X = Op.getOperand(0); 7780 SDValue Y = Op.getOperand(1); 7781 7782 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7783 7784 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7785 7786 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7787 7788 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7789 7790 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7791 7792 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7793 7794 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7795 7796 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7797 7798 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7799 7800 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7801 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7802 7803 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7804 NegDivScale0, Mul, DivScale1); 7805 7806 SDValue Scale; 7807 7808 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7809 // Workaround a hardware bug on SI where the condition output from div_scale 7810 // is not usable. 7811 7812 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7813 7814 // Figure out if the scale to use for div_fmas. 7815 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7816 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7817 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7818 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7819 7820 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7821 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7822 7823 SDValue Scale0Hi 7824 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7825 SDValue Scale1Hi 7826 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7827 7828 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7829 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7830 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7831 } else { 7832 Scale = DivScale1.getValue(1); 7833 } 7834 7835 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7836 Fma4, Fma3, Mul, Scale); 7837 7838 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7839 } 7840 7841 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7842 EVT VT = Op.getValueType(); 7843 7844 if (VT == MVT::f32) 7845 return LowerFDIV32(Op, DAG); 7846 7847 if (VT == MVT::f64) 7848 return LowerFDIV64(Op, DAG); 7849 7850 if (VT == MVT::f16) 7851 return LowerFDIV16(Op, DAG); 7852 7853 llvm_unreachable("Unexpected type for fdiv"); 7854 } 7855 7856 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7857 SDLoc DL(Op); 7858 StoreSDNode *Store = cast<StoreSDNode>(Op); 7859 EVT VT = Store->getMemoryVT(); 7860 7861 if (VT == MVT::i1) { 7862 return DAG.getTruncStore(Store->getChain(), DL, 7863 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7864 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7865 } 7866 7867 assert(VT.isVector() && 7868 Store->getValue().getValueType().getScalarType() == MVT::i32); 7869 7870 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7871 VT, *Store->getMemOperand())) { 7872 return expandUnalignedStore(Store, DAG); 7873 } 7874 7875 unsigned AS = Store->getAddressSpace(); 7876 if (Subtarget->hasLDSMisalignedBug() && 7877 AS == AMDGPUAS::FLAT_ADDRESS && 7878 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7879 return SplitVectorStore(Op, DAG); 7880 } 7881 7882 MachineFunction &MF = DAG.getMachineFunction(); 7883 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7884 // If there is a possibilty that flat instruction access scratch memory 7885 // then we need to use the same legalization rules we use for private. 7886 if (AS == AMDGPUAS::FLAT_ADDRESS) 7887 AS = MFI->hasFlatScratchInit() ? 7888 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7889 7890 unsigned NumElements = VT.getVectorNumElements(); 7891 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7892 AS == AMDGPUAS::FLAT_ADDRESS) { 7893 if (NumElements > 4) 7894 return SplitVectorStore(Op, DAG); 7895 // v3 stores not supported on SI. 7896 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7897 return SplitVectorStore(Op, DAG); 7898 return SDValue(); 7899 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7900 switch (Subtarget->getMaxPrivateElementSize()) { 7901 case 4: 7902 return scalarizeVectorStore(Store, DAG); 7903 case 8: 7904 if (NumElements > 2) 7905 return SplitVectorStore(Op, DAG); 7906 return SDValue(); 7907 case 16: 7908 if (NumElements > 4 || NumElements == 3) 7909 return SplitVectorStore(Op, DAG); 7910 return SDValue(); 7911 default: 7912 llvm_unreachable("unsupported private_element_size"); 7913 } 7914 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7915 // Use ds_write_b128 if possible. 7916 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7917 VT.getStoreSize() == 16 && NumElements != 3) 7918 return SDValue(); 7919 7920 if (NumElements > 2) 7921 return SplitVectorStore(Op, DAG); 7922 7923 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7924 // address is negative, then the instruction is incorrectly treated as 7925 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7926 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7927 // store later in the SILoadStoreOptimizer. 7928 if (!Subtarget->hasUsableDSOffset() && 7929 NumElements == 2 && VT.getStoreSize() == 8 && 7930 Store->getAlignment() < 8) { 7931 return SplitVectorStore(Op, DAG); 7932 } 7933 7934 return SDValue(); 7935 } else { 7936 llvm_unreachable("unhandled address space"); 7937 } 7938 } 7939 7940 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7941 SDLoc DL(Op); 7942 EVT VT = Op.getValueType(); 7943 SDValue Arg = Op.getOperand(0); 7944 SDValue TrigVal; 7945 7946 // TODO: Should this propagate fast-math-flags? 7947 7948 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7949 7950 if (Subtarget->hasTrigReducedRange()) { 7951 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7952 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7953 } else { 7954 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7955 } 7956 7957 switch (Op.getOpcode()) { 7958 case ISD::FCOS: 7959 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7960 case ISD::FSIN: 7961 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7962 default: 7963 llvm_unreachable("Wrong trig opcode"); 7964 } 7965 } 7966 7967 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7968 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7969 assert(AtomicNode->isCompareAndSwap()); 7970 unsigned AS = AtomicNode->getAddressSpace(); 7971 7972 // No custom lowering required for local address space 7973 if (!isFlatGlobalAddrSpace(AS)) 7974 return Op; 7975 7976 // Non-local address space requires custom lowering for atomic compare 7977 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7978 SDLoc DL(Op); 7979 SDValue ChainIn = Op.getOperand(0); 7980 SDValue Addr = Op.getOperand(1); 7981 SDValue Old = Op.getOperand(2); 7982 SDValue New = Op.getOperand(3); 7983 EVT VT = Op.getValueType(); 7984 MVT SimpleVT = VT.getSimpleVT(); 7985 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7986 7987 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7988 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7989 7990 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7991 Ops, VT, AtomicNode->getMemOperand()); 7992 } 7993 7994 //===----------------------------------------------------------------------===// 7995 // Custom DAG optimizations 7996 //===----------------------------------------------------------------------===// 7997 7998 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7999 DAGCombinerInfo &DCI) const { 8000 EVT VT = N->getValueType(0); 8001 EVT ScalarVT = VT.getScalarType(); 8002 if (ScalarVT != MVT::f32) 8003 return SDValue(); 8004 8005 SelectionDAG &DAG = DCI.DAG; 8006 SDLoc DL(N); 8007 8008 SDValue Src = N->getOperand(0); 8009 EVT SrcVT = Src.getValueType(); 8010 8011 // TODO: We could try to match extracting the higher bytes, which would be 8012 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8013 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8014 // about in practice. 8015 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8016 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8017 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 8018 DCI.AddToWorklist(Cvt.getNode()); 8019 return Cvt; 8020 } 8021 } 8022 8023 return SDValue(); 8024 } 8025 8026 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8027 8028 // This is a variant of 8029 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8030 // 8031 // The normal DAG combiner will do this, but only if the add has one use since 8032 // that would increase the number of instructions. 8033 // 8034 // This prevents us from seeing a constant offset that can be folded into a 8035 // memory instruction's addressing mode. If we know the resulting add offset of 8036 // a pointer can be folded into an addressing offset, we can replace the pointer 8037 // operand with the add of new constant offset. This eliminates one of the uses, 8038 // and may allow the remaining use to also be simplified. 8039 // 8040 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8041 unsigned AddrSpace, 8042 EVT MemVT, 8043 DAGCombinerInfo &DCI) const { 8044 SDValue N0 = N->getOperand(0); 8045 SDValue N1 = N->getOperand(1); 8046 8047 // We only do this to handle cases where it's profitable when there are 8048 // multiple uses of the add, so defer to the standard combine. 8049 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8050 N0->hasOneUse()) 8051 return SDValue(); 8052 8053 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8054 if (!CN1) 8055 return SDValue(); 8056 8057 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8058 if (!CAdd) 8059 return SDValue(); 8060 8061 // If the resulting offset is too large, we can't fold it into the addressing 8062 // mode offset. 8063 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8064 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8065 8066 AddrMode AM; 8067 AM.HasBaseReg = true; 8068 AM.BaseOffs = Offset.getSExtValue(); 8069 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8070 return SDValue(); 8071 8072 SelectionDAG &DAG = DCI.DAG; 8073 SDLoc SL(N); 8074 EVT VT = N->getValueType(0); 8075 8076 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8077 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8078 8079 SDNodeFlags Flags; 8080 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8081 (N0.getOpcode() == ISD::OR || 8082 N0->getFlags().hasNoUnsignedWrap())); 8083 8084 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8085 } 8086 8087 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8088 DAGCombinerInfo &DCI) const { 8089 SDValue Ptr = N->getBasePtr(); 8090 SelectionDAG &DAG = DCI.DAG; 8091 SDLoc SL(N); 8092 8093 // TODO: We could also do this for multiplies. 8094 if (Ptr.getOpcode() == ISD::SHL) { 8095 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8096 N->getMemoryVT(), DCI); 8097 if (NewPtr) { 8098 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8099 8100 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8101 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8102 } 8103 } 8104 8105 return SDValue(); 8106 } 8107 8108 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8109 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8110 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8111 (Opc == ISD::XOR && Val == 0); 8112 } 8113 8114 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8115 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8116 // integer combine opportunities since most 64-bit operations are decomposed 8117 // this way. TODO: We won't want this for SALU especially if it is an inline 8118 // immediate. 8119 SDValue SITargetLowering::splitBinaryBitConstantOp( 8120 DAGCombinerInfo &DCI, 8121 const SDLoc &SL, 8122 unsigned Opc, SDValue LHS, 8123 const ConstantSDNode *CRHS) const { 8124 uint64_t Val = CRHS->getZExtValue(); 8125 uint32_t ValLo = Lo_32(Val); 8126 uint32_t ValHi = Hi_32(Val); 8127 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8128 8129 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8130 bitOpWithConstantIsReducible(Opc, ValHi)) || 8131 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8132 // If we need to materialize a 64-bit immediate, it will be split up later 8133 // anyway. Avoid creating the harder to understand 64-bit immediate 8134 // materialization. 8135 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8136 } 8137 8138 return SDValue(); 8139 } 8140 8141 // Returns true if argument is a boolean value which is not serialized into 8142 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8143 static bool isBoolSGPR(SDValue V) { 8144 if (V.getValueType() != MVT::i1) 8145 return false; 8146 switch (V.getOpcode()) { 8147 default: break; 8148 case ISD::SETCC: 8149 case ISD::AND: 8150 case ISD::OR: 8151 case ISD::XOR: 8152 case AMDGPUISD::FP_CLASS: 8153 return true; 8154 } 8155 return false; 8156 } 8157 8158 // If a constant has all zeroes or all ones within each byte return it. 8159 // Otherwise return 0. 8160 static uint32_t getConstantPermuteMask(uint32_t C) { 8161 // 0xff for any zero byte in the mask 8162 uint32_t ZeroByteMask = 0; 8163 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8164 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8165 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8166 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8167 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8168 if ((NonZeroByteMask & C) != NonZeroByteMask) 8169 return 0; // Partial bytes selected. 8170 return C; 8171 } 8172 8173 // Check if a node selects whole bytes from its operand 0 starting at a byte 8174 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8175 // or -1 if not succeeded. 8176 // Note byte select encoding: 8177 // value 0-3 selects corresponding source byte; 8178 // value 0xc selects zero; 8179 // value 0xff selects 0xff. 8180 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8181 assert(V.getValueSizeInBits() == 32); 8182 8183 if (V.getNumOperands() != 2) 8184 return ~0; 8185 8186 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8187 if (!N1) 8188 return ~0; 8189 8190 uint32_t C = N1->getZExtValue(); 8191 8192 switch (V.getOpcode()) { 8193 default: 8194 break; 8195 case ISD::AND: 8196 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8197 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8198 } 8199 break; 8200 8201 case ISD::OR: 8202 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8203 return (0x03020100 & ~ConstMask) | ConstMask; 8204 } 8205 break; 8206 8207 case ISD::SHL: 8208 if (C % 8) 8209 return ~0; 8210 8211 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8212 8213 case ISD::SRL: 8214 if (C % 8) 8215 return ~0; 8216 8217 return uint32_t(0x0c0c0c0c03020100ull >> C); 8218 } 8219 8220 return ~0; 8221 } 8222 8223 SDValue SITargetLowering::performAndCombine(SDNode *N, 8224 DAGCombinerInfo &DCI) const { 8225 if (DCI.isBeforeLegalize()) 8226 return SDValue(); 8227 8228 SelectionDAG &DAG = DCI.DAG; 8229 EVT VT = N->getValueType(0); 8230 SDValue LHS = N->getOperand(0); 8231 SDValue RHS = N->getOperand(1); 8232 8233 8234 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8235 if (VT == MVT::i64 && CRHS) { 8236 if (SDValue Split 8237 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8238 return Split; 8239 } 8240 8241 if (CRHS && VT == MVT::i32) { 8242 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8243 // nb = number of trailing zeroes in mask 8244 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8245 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8246 uint64_t Mask = CRHS->getZExtValue(); 8247 unsigned Bits = countPopulation(Mask); 8248 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8249 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8250 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8251 unsigned Shift = CShift->getZExtValue(); 8252 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8253 unsigned Offset = NB + Shift; 8254 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8255 SDLoc SL(N); 8256 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8257 LHS->getOperand(0), 8258 DAG.getConstant(Offset, SL, MVT::i32), 8259 DAG.getConstant(Bits, SL, MVT::i32)); 8260 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8261 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8262 DAG.getValueType(NarrowVT)); 8263 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8264 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8265 return Shl; 8266 } 8267 } 8268 } 8269 8270 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8271 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8272 isa<ConstantSDNode>(LHS.getOperand(2))) { 8273 uint32_t Sel = getConstantPermuteMask(Mask); 8274 if (!Sel) 8275 return SDValue(); 8276 8277 // Select 0xc for all zero bytes 8278 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8279 SDLoc DL(N); 8280 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8281 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8282 } 8283 } 8284 8285 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8286 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8287 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8288 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8289 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8290 8291 SDValue X = LHS.getOperand(0); 8292 SDValue Y = RHS.getOperand(0); 8293 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8294 return SDValue(); 8295 8296 if (LCC == ISD::SETO) { 8297 if (X != LHS.getOperand(1)) 8298 return SDValue(); 8299 8300 if (RCC == ISD::SETUNE) { 8301 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8302 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8303 return SDValue(); 8304 8305 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8306 SIInstrFlags::N_SUBNORMAL | 8307 SIInstrFlags::N_ZERO | 8308 SIInstrFlags::P_ZERO | 8309 SIInstrFlags::P_SUBNORMAL | 8310 SIInstrFlags::P_NORMAL; 8311 8312 static_assert(((~(SIInstrFlags::S_NAN | 8313 SIInstrFlags::Q_NAN | 8314 SIInstrFlags::N_INFINITY | 8315 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8316 "mask not equal"); 8317 8318 SDLoc DL(N); 8319 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8320 X, DAG.getConstant(Mask, DL, MVT::i32)); 8321 } 8322 } 8323 } 8324 8325 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8326 std::swap(LHS, RHS); 8327 8328 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8329 RHS.hasOneUse()) { 8330 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8331 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8332 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8333 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8334 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8335 (RHS.getOperand(0) == LHS.getOperand(0) && 8336 LHS.getOperand(0) == LHS.getOperand(1))) { 8337 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8338 unsigned NewMask = LCC == ISD::SETO ? 8339 Mask->getZExtValue() & ~OrdMask : 8340 Mask->getZExtValue() & OrdMask; 8341 8342 SDLoc DL(N); 8343 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8344 DAG.getConstant(NewMask, DL, MVT::i32)); 8345 } 8346 } 8347 8348 if (VT == MVT::i32 && 8349 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8350 // and x, (sext cc from i1) => select cc, x, 0 8351 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8352 std::swap(LHS, RHS); 8353 if (isBoolSGPR(RHS.getOperand(0))) 8354 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8355 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8356 } 8357 8358 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8359 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8360 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8361 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8362 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8363 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8364 if (LHSMask != ~0u && RHSMask != ~0u) { 8365 // Canonicalize the expression in an attempt to have fewer unique masks 8366 // and therefore fewer registers used to hold the masks. 8367 if (LHSMask > RHSMask) { 8368 std::swap(LHSMask, RHSMask); 8369 std::swap(LHS, RHS); 8370 } 8371 8372 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8373 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8374 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8375 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8376 8377 // Check of we need to combine values from two sources within a byte. 8378 if (!(LHSUsedLanes & RHSUsedLanes) && 8379 // If we select high and lower word keep it for SDWA. 8380 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8381 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8382 // Each byte in each mask is either selector mask 0-3, or has higher 8383 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8384 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8385 // mask which is not 0xff wins. By anding both masks we have a correct 8386 // result except that 0x0c shall be corrected to give 0x0c only. 8387 uint32_t Mask = LHSMask & RHSMask; 8388 for (unsigned I = 0; I < 32; I += 8) { 8389 uint32_t ByteSel = 0xff << I; 8390 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8391 Mask &= (0x0c << I) & 0xffffffff; 8392 } 8393 8394 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8395 // or 0x0c. 8396 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8397 SDLoc DL(N); 8398 8399 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8400 LHS.getOperand(0), RHS.getOperand(0), 8401 DAG.getConstant(Sel, DL, MVT::i32)); 8402 } 8403 } 8404 } 8405 8406 return SDValue(); 8407 } 8408 8409 SDValue SITargetLowering::performOrCombine(SDNode *N, 8410 DAGCombinerInfo &DCI) const { 8411 SelectionDAG &DAG = DCI.DAG; 8412 SDValue LHS = N->getOperand(0); 8413 SDValue RHS = N->getOperand(1); 8414 8415 EVT VT = N->getValueType(0); 8416 if (VT == MVT::i1) { 8417 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8418 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8419 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8420 SDValue Src = LHS.getOperand(0); 8421 if (Src != RHS.getOperand(0)) 8422 return SDValue(); 8423 8424 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8425 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8426 if (!CLHS || !CRHS) 8427 return SDValue(); 8428 8429 // Only 10 bits are used. 8430 static const uint32_t MaxMask = 0x3ff; 8431 8432 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8433 SDLoc DL(N); 8434 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8435 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8436 } 8437 8438 return SDValue(); 8439 } 8440 8441 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8442 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8443 LHS.getOpcode() == AMDGPUISD::PERM && 8444 isa<ConstantSDNode>(LHS.getOperand(2))) { 8445 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8446 if (!Sel) 8447 return SDValue(); 8448 8449 Sel |= LHS.getConstantOperandVal(2); 8450 SDLoc DL(N); 8451 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8452 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8453 } 8454 8455 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8456 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8457 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8458 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8459 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8460 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8461 if (LHSMask != ~0u && RHSMask != ~0u) { 8462 // Canonicalize the expression in an attempt to have fewer unique masks 8463 // and therefore fewer registers used to hold the masks. 8464 if (LHSMask > RHSMask) { 8465 std::swap(LHSMask, RHSMask); 8466 std::swap(LHS, RHS); 8467 } 8468 8469 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8470 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8471 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8472 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8473 8474 // Check of we need to combine values from two sources within a byte. 8475 if (!(LHSUsedLanes & RHSUsedLanes) && 8476 // If we select high and lower word keep it for SDWA. 8477 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8478 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8479 // Kill zero bytes selected by other mask. Zero value is 0xc. 8480 LHSMask &= ~RHSUsedLanes; 8481 RHSMask &= ~LHSUsedLanes; 8482 // Add 4 to each active LHS lane 8483 LHSMask |= LHSUsedLanes & 0x04040404; 8484 // Combine masks 8485 uint32_t Sel = LHSMask | RHSMask; 8486 SDLoc DL(N); 8487 8488 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8489 LHS.getOperand(0), RHS.getOperand(0), 8490 DAG.getConstant(Sel, DL, MVT::i32)); 8491 } 8492 } 8493 } 8494 8495 if (VT != MVT::i64) 8496 return SDValue(); 8497 8498 // TODO: This could be a generic combine with a predicate for extracting the 8499 // high half of an integer being free. 8500 8501 // (or i64:x, (zero_extend i32:y)) -> 8502 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8503 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8504 RHS.getOpcode() != ISD::ZERO_EXTEND) 8505 std::swap(LHS, RHS); 8506 8507 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8508 SDValue ExtSrc = RHS.getOperand(0); 8509 EVT SrcVT = ExtSrc.getValueType(); 8510 if (SrcVT == MVT::i32) { 8511 SDLoc SL(N); 8512 SDValue LowLHS, HiBits; 8513 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8514 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8515 8516 DCI.AddToWorklist(LowOr.getNode()); 8517 DCI.AddToWorklist(HiBits.getNode()); 8518 8519 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8520 LowOr, HiBits); 8521 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8522 } 8523 } 8524 8525 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8526 if (CRHS) { 8527 if (SDValue Split 8528 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8529 return Split; 8530 } 8531 8532 return SDValue(); 8533 } 8534 8535 SDValue SITargetLowering::performXorCombine(SDNode *N, 8536 DAGCombinerInfo &DCI) const { 8537 EVT VT = N->getValueType(0); 8538 if (VT != MVT::i64) 8539 return SDValue(); 8540 8541 SDValue LHS = N->getOperand(0); 8542 SDValue RHS = N->getOperand(1); 8543 8544 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8545 if (CRHS) { 8546 if (SDValue Split 8547 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8548 return Split; 8549 } 8550 8551 return SDValue(); 8552 } 8553 8554 // Instructions that will be lowered with a final instruction that zeros the 8555 // high result bits. 8556 // XXX - probably only need to list legal operations. 8557 static bool fp16SrcZerosHighBits(unsigned Opc) { 8558 switch (Opc) { 8559 case ISD::FADD: 8560 case ISD::FSUB: 8561 case ISD::FMUL: 8562 case ISD::FDIV: 8563 case ISD::FREM: 8564 case ISD::FMA: 8565 case ISD::FMAD: 8566 case ISD::FCANONICALIZE: 8567 case ISD::FP_ROUND: 8568 case ISD::UINT_TO_FP: 8569 case ISD::SINT_TO_FP: 8570 case ISD::FABS: 8571 // Fabs is lowered to a bit operation, but it's an and which will clear the 8572 // high bits anyway. 8573 case ISD::FSQRT: 8574 case ISD::FSIN: 8575 case ISD::FCOS: 8576 case ISD::FPOWI: 8577 case ISD::FPOW: 8578 case ISD::FLOG: 8579 case ISD::FLOG2: 8580 case ISD::FLOG10: 8581 case ISD::FEXP: 8582 case ISD::FEXP2: 8583 case ISD::FCEIL: 8584 case ISD::FTRUNC: 8585 case ISD::FRINT: 8586 case ISD::FNEARBYINT: 8587 case ISD::FROUND: 8588 case ISD::FFLOOR: 8589 case ISD::FMINNUM: 8590 case ISD::FMAXNUM: 8591 case AMDGPUISD::FRACT: 8592 case AMDGPUISD::CLAMP: 8593 case AMDGPUISD::COS_HW: 8594 case AMDGPUISD::SIN_HW: 8595 case AMDGPUISD::FMIN3: 8596 case AMDGPUISD::FMAX3: 8597 case AMDGPUISD::FMED3: 8598 case AMDGPUISD::FMAD_FTZ: 8599 case AMDGPUISD::RCP: 8600 case AMDGPUISD::RSQ: 8601 case AMDGPUISD::RCP_IFLAG: 8602 case AMDGPUISD::LDEXP: 8603 return true; 8604 default: 8605 // fcopysign, select and others may be lowered to 32-bit bit operations 8606 // which don't zero the high bits. 8607 return false; 8608 } 8609 } 8610 8611 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8612 DAGCombinerInfo &DCI) const { 8613 if (!Subtarget->has16BitInsts() || 8614 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8615 return SDValue(); 8616 8617 EVT VT = N->getValueType(0); 8618 if (VT != MVT::i32) 8619 return SDValue(); 8620 8621 SDValue Src = N->getOperand(0); 8622 if (Src.getValueType() != MVT::i16) 8623 return SDValue(); 8624 8625 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8626 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8627 if (Src.getOpcode() == ISD::BITCAST) { 8628 SDValue BCSrc = Src.getOperand(0); 8629 if (BCSrc.getValueType() == MVT::f16 && 8630 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8631 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8632 } 8633 8634 return SDValue(); 8635 } 8636 8637 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8638 DAGCombinerInfo &DCI) 8639 const { 8640 SDValue Src = N->getOperand(0); 8641 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8642 8643 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8644 VTSign->getVT() == MVT::i8) || 8645 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8646 VTSign->getVT() == MVT::i16)) && 8647 Src.hasOneUse()) { 8648 auto *M = cast<MemSDNode>(Src); 8649 SDValue Ops[] = { 8650 Src.getOperand(0), // Chain 8651 Src.getOperand(1), // rsrc 8652 Src.getOperand(2), // vindex 8653 Src.getOperand(3), // voffset 8654 Src.getOperand(4), // soffset 8655 Src.getOperand(5), // offset 8656 Src.getOperand(6), 8657 Src.getOperand(7) 8658 }; 8659 // replace with BUFFER_LOAD_BYTE/SHORT 8660 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8661 Src.getOperand(0).getValueType()); 8662 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8663 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8664 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8665 ResList, 8666 Ops, M->getMemoryVT(), 8667 M->getMemOperand()); 8668 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8669 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8670 } 8671 return SDValue(); 8672 } 8673 8674 SDValue SITargetLowering::performClassCombine(SDNode *N, 8675 DAGCombinerInfo &DCI) const { 8676 SelectionDAG &DAG = DCI.DAG; 8677 SDValue Mask = N->getOperand(1); 8678 8679 // fp_class x, 0 -> false 8680 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8681 if (CMask->isNullValue()) 8682 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8683 } 8684 8685 if (N->getOperand(0).isUndef()) 8686 return DAG.getUNDEF(MVT::i1); 8687 8688 return SDValue(); 8689 } 8690 8691 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8692 DAGCombinerInfo &DCI) const { 8693 EVT VT = N->getValueType(0); 8694 SDValue N0 = N->getOperand(0); 8695 8696 if (N0.isUndef()) 8697 return N0; 8698 8699 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8700 N0.getOpcode() == ISD::SINT_TO_FP)) { 8701 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8702 N->getFlags()); 8703 } 8704 8705 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8706 } 8707 8708 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8709 unsigned MaxDepth) const { 8710 unsigned Opcode = Op.getOpcode(); 8711 if (Opcode == ISD::FCANONICALIZE) 8712 return true; 8713 8714 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8715 auto F = CFP->getValueAPF(); 8716 if (F.isNaN() && F.isSignaling()) 8717 return false; 8718 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8719 } 8720 8721 // If source is a result of another standard FP operation it is already in 8722 // canonical form. 8723 if (MaxDepth == 0) 8724 return false; 8725 8726 switch (Opcode) { 8727 // These will flush denorms if required. 8728 case ISD::FADD: 8729 case ISD::FSUB: 8730 case ISD::FMUL: 8731 case ISD::FCEIL: 8732 case ISD::FFLOOR: 8733 case ISD::FMA: 8734 case ISD::FMAD: 8735 case ISD::FSQRT: 8736 case ISD::FDIV: 8737 case ISD::FREM: 8738 case ISD::FP_ROUND: 8739 case ISD::FP_EXTEND: 8740 case AMDGPUISD::FMUL_LEGACY: 8741 case AMDGPUISD::FMAD_FTZ: 8742 case AMDGPUISD::RCP: 8743 case AMDGPUISD::RSQ: 8744 case AMDGPUISD::RSQ_CLAMP: 8745 case AMDGPUISD::RCP_LEGACY: 8746 case AMDGPUISD::RSQ_LEGACY: 8747 case AMDGPUISD::RCP_IFLAG: 8748 case AMDGPUISD::TRIG_PREOP: 8749 case AMDGPUISD::DIV_SCALE: 8750 case AMDGPUISD::DIV_FMAS: 8751 case AMDGPUISD::DIV_FIXUP: 8752 case AMDGPUISD::FRACT: 8753 case AMDGPUISD::LDEXP: 8754 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8755 case AMDGPUISD::CVT_F32_UBYTE0: 8756 case AMDGPUISD::CVT_F32_UBYTE1: 8757 case AMDGPUISD::CVT_F32_UBYTE2: 8758 case AMDGPUISD::CVT_F32_UBYTE3: 8759 return true; 8760 8761 // It can/will be lowered or combined as a bit operation. 8762 // Need to check their input recursively to handle. 8763 case ISD::FNEG: 8764 case ISD::FABS: 8765 case ISD::FCOPYSIGN: 8766 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8767 8768 case ISD::FSIN: 8769 case ISD::FCOS: 8770 case ISD::FSINCOS: 8771 return Op.getValueType().getScalarType() != MVT::f16; 8772 8773 case ISD::FMINNUM: 8774 case ISD::FMAXNUM: 8775 case ISD::FMINNUM_IEEE: 8776 case ISD::FMAXNUM_IEEE: 8777 case AMDGPUISD::CLAMP: 8778 case AMDGPUISD::FMED3: 8779 case AMDGPUISD::FMAX3: 8780 case AMDGPUISD::FMIN3: { 8781 // FIXME: Shouldn't treat the generic operations different based these. 8782 // However, we aren't really required to flush the result from 8783 // minnum/maxnum.. 8784 8785 // snans will be quieted, so we only need to worry about denormals. 8786 if (Subtarget->supportsMinMaxDenormModes() || 8787 denormalsEnabledForType(DAG, Op.getValueType())) 8788 return true; 8789 8790 // Flushing may be required. 8791 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8792 // targets need to check their input recursively. 8793 8794 // FIXME: Does this apply with clamp? It's implemented with max. 8795 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8796 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8797 return false; 8798 } 8799 8800 return true; 8801 } 8802 case ISD::SELECT: { 8803 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8804 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8805 } 8806 case ISD::BUILD_VECTOR: { 8807 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8808 SDValue SrcOp = Op.getOperand(i); 8809 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8810 return false; 8811 } 8812 8813 return true; 8814 } 8815 case ISD::EXTRACT_VECTOR_ELT: 8816 case ISD::EXTRACT_SUBVECTOR: { 8817 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8818 } 8819 case ISD::INSERT_VECTOR_ELT: { 8820 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8821 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8822 } 8823 case ISD::UNDEF: 8824 // Could be anything. 8825 return false; 8826 8827 case ISD::BITCAST: { 8828 // Hack round the mess we make when legalizing extract_vector_elt 8829 SDValue Src = Op.getOperand(0); 8830 if (Src.getValueType() == MVT::i16 && 8831 Src.getOpcode() == ISD::TRUNCATE) { 8832 SDValue TruncSrc = Src.getOperand(0); 8833 if (TruncSrc.getValueType() == MVT::i32 && 8834 TruncSrc.getOpcode() == ISD::BITCAST && 8835 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8836 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8837 } 8838 } 8839 8840 return false; 8841 } 8842 case ISD::INTRINSIC_WO_CHAIN: { 8843 unsigned IntrinsicID 8844 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8845 // TODO: Handle more intrinsics 8846 switch (IntrinsicID) { 8847 case Intrinsic::amdgcn_cvt_pkrtz: 8848 case Intrinsic::amdgcn_cubeid: 8849 case Intrinsic::amdgcn_frexp_mant: 8850 case Intrinsic::amdgcn_fdot2: 8851 return true; 8852 default: 8853 break; 8854 } 8855 8856 LLVM_FALLTHROUGH; 8857 } 8858 default: 8859 return denormalsEnabledForType(DAG, Op.getValueType()) && 8860 DAG.isKnownNeverSNaN(Op); 8861 } 8862 8863 llvm_unreachable("invalid operation"); 8864 } 8865 8866 // Constant fold canonicalize. 8867 SDValue SITargetLowering::getCanonicalConstantFP( 8868 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8869 // Flush denormals to 0 if not enabled. 8870 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8871 return DAG.getConstantFP(0.0, SL, VT); 8872 8873 if (C.isNaN()) { 8874 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8875 if (C.isSignaling()) { 8876 // Quiet a signaling NaN. 8877 // FIXME: Is this supposed to preserve payload bits? 8878 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8879 } 8880 8881 // Make sure it is the canonical NaN bitpattern. 8882 // 8883 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8884 // immediate? 8885 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8886 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8887 } 8888 8889 // Already canonical. 8890 return DAG.getConstantFP(C, SL, VT); 8891 } 8892 8893 static bool vectorEltWillFoldAway(SDValue Op) { 8894 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8895 } 8896 8897 SDValue SITargetLowering::performFCanonicalizeCombine( 8898 SDNode *N, 8899 DAGCombinerInfo &DCI) const { 8900 SelectionDAG &DAG = DCI.DAG; 8901 SDValue N0 = N->getOperand(0); 8902 EVT VT = N->getValueType(0); 8903 8904 // fcanonicalize undef -> qnan 8905 if (N0.isUndef()) { 8906 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8907 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8908 } 8909 8910 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8911 EVT VT = N->getValueType(0); 8912 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8913 } 8914 8915 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8916 // (fcanonicalize k) 8917 // 8918 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8919 8920 // TODO: This could be better with wider vectors that will be split to v2f16, 8921 // and to consider uses since there aren't that many packed operations. 8922 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8923 isTypeLegal(MVT::v2f16)) { 8924 SDLoc SL(N); 8925 SDValue NewElts[2]; 8926 SDValue Lo = N0.getOperand(0); 8927 SDValue Hi = N0.getOperand(1); 8928 EVT EltVT = Lo.getValueType(); 8929 8930 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8931 for (unsigned I = 0; I != 2; ++I) { 8932 SDValue Op = N0.getOperand(I); 8933 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8934 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8935 CFP->getValueAPF()); 8936 } else if (Op.isUndef()) { 8937 // Handled below based on what the other operand is. 8938 NewElts[I] = Op; 8939 } else { 8940 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8941 } 8942 } 8943 8944 // If one half is undef, and one is constant, perfer a splat vector rather 8945 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8946 // cheaper to use and may be free with a packed operation. 8947 if (NewElts[0].isUndef()) { 8948 if (isa<ConstantFPSDNode>(NewElts[1])) 8949 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8950 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8951 } 8952 8953 if (NewElts[1].isUndef()) { 8954 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8955 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8956 } 8957 8958 return DAG.getBuildVector(VT, SL, NewElts); 8959 } 8960 } 8961 8962 unsigned SrcOpc = N0.getOpcode(); 8963 8964 // If it's free to do so, push canonicalizes further up the source, which may 8965 // find a canonical source. 8966 // 8967 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8968 // sNaNs. 8969 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8970 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8971 if (CRHS && N0.hasOneUse()) { 8972 SDLoc SL(N); 8973 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8974 N0.getOperand(0)); 8975 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8976 DCI.AddToWorklist(Canon0.getNode()); 8977 8978 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8979 } 8980 } 8981 8982 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8983 } 8984 8985 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8986 switch (Opc) { 8987 case ISD::FMAXNUM: 8988 case ISD::FMAXNUM_IEEE: 8989 return AMDGPUISD::FMAX3; 8990 case ISD::SMAX: 8991 return AMDGPUISD::SMAX3; 8992 case ISD::UMAX: 8993 return AMDGPUISD::UMAX3; 8994 case ISD::FMINNUM: 8995 case ISD::FMINNUM_IEEE: 8996 return AMDGPUISD::FMIN3; 8997 case ISD::SMIN: 8998 return AMDGPUISD::SMIN3; 8999 case ISD::UMIN: 9000 return AMDGPUISD::UMIN3; 9001 default: 9002 llvm_unreachable("Not a min/max opcode"); 9003 } 9004 } 9005 9006 SDValue SITargetLowering::performIntMed3ImmCombine( 9007 SelectionDAG &DAG, const SDLoc &SL, 9008 SDValue Op0, SDValue Op1, bool Signed) const { 9009 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9010 if (!K1) 9011 return SDValue(); 9012 9013 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9014 if (!K0) 9015 return SDValue(); 9016 9017 if (Signed) { 9018 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9019 return SDValue(); 9020 } else { 9021 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9022 return SDValue(); 9023 } 9024 9025 EVT VT = K0->getValueType(0); 9026 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9027 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9028 return DAG.getNode(Med3Opc, SL, VT, 9029 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9030 } 9031 9032 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9033 MVT NVT = MVT::i32; 9034 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9035 9036 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9037 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9038 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9039 9040 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9041 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9042 } 9043 9044 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9045 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9046 return C; 9047 9048 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9049 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9050 return C; 9051 } 9052 9053 return nullptr; 9054 } 9055 9056 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9057 const SDLoc &SL, 9058 SDValue Op0, 9059 SDValue Op1) const { 9060 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9061 if (!K1) 9062 return SDValue(); 9063 9064 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9065 if (!K0) 9066 return SDValue(); 9067 9068 // Ordered >= (although NaN inputs should have folded away by now). 9069 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 9070 if (Cmp == APFloat::cmpGreaterThan) 9071 return SDValue(); 9072 9073 const MachineFunction &MF = DAG.getMachineFunction(); 9074 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9075 9076 // TODO: Check IEEE bit enabled? 9077 EVT VT = Op0.getValueType(); 9078 if (Info->getMode().DX10Clamp) { 9079 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9080 // hardware fmed3 behavior converting to a min. 9081 // FIXME: Should this be allowing -0.0? 9082 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9083 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9084 } 9085 9086 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9087 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9088 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9089 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9090 // then give the other result, which is different from med3 with a NaN 9091 // input. 9092 SDValue Var = Op0.getOperand(0); 9093 if (!DAG.isKnownNeverSNaN(Var)) 9094 return SDValue(); 9095 9096 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9097 9098 if ((!K0->hasOneUse() || 9099 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9100 (!K1->hasOneUse() || 9101 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9102 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9103 Var, SDValue(K0, 0), SDValue(K1, 0)); 9104 } 9105 } 9106 9107 return SDValue(); 9108 } 9109 9110 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9111 DAGCombinerInfo &DCI) const { 9112 SelectionDAG &DAG = DCI.DAG; 9113 9114 EVT VT = N->getValueType(0); 9115 unsigned Opc = N->getOpcode(); 9116 SDValue Op0 = N->getOperand(0); 9117 SDValue Op1 = N->getOperand(1); 9118 9119 // Only do this if the inner op has one use since this will just increases 9120 // register pressure for no benefit. 9121 9122 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9123 !VT.isVector() && 9124 (VT == MVT::i32 || VT == MVT::f32 || 9125 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9126 // max(max(a, b), c) -> max3(a, b, c) 9127 // min(min(a, b), c) -> min3(a, b, c) 9128 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9129 SDLoc DL(N); 9130 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9131 DL, 9132 N->getValueType(0), 9133 Op0.getOperand(0), 9134 Op0.getOperand(1), 9135 Op1); 9136 } 9137 9138 // Try commuted. 9139 // max(a, max(b, c)) -> max3(a, b, c) 9140 // min(a, min(b, c)) -> min3(a, b, c) 9141 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9142 SDLoc DL(N); 9143 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9144 DL, 9145 N->getValueType(0), 9146 Op0, 9147 Op1.getOperand(0), 9148 Op1.getOperand(1)); 9149 } 9150 } 9151 9152 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9153 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9154 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9155 return Med3; 9156 } 9157 9158 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9159 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9160 return Med3; 9161 } 9162 9163 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9164 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9165 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9166 (Opc == AMDGPUISD::FMIN_LEGACY && 9167 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9168 (VT == MVT::f32 || VT == MVT::f64 || 9169 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9170 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9171 Op0.hasOneUse()) { 9172 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9173 return Res; 9174 } 9175 9176 return SDValue(); 9177 } 9178 9179 static bool isClampZeroToOne(SDValue A, SDValue B) { 9180 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9181 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9182 // FIXME: Should this be allowing -0.0? 9183 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9184 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9185 } 9186 } 9187 9188 return false; 9189 } 9190 9191 // FIXME: Should only worry about snans for version with chain. 9192 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9193 DAGCombinerInfo &DCI) const { 9194 EVT VT = N->getValueType(0); 9195 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9196 // NaNs. With a NaN input, the order of the operands may change the result. 9197 9198 SelectionDAG &DAG = DCI.DAG; 9199 SDLoc SL(N); 9200 9201 SDValue Src0 = N->getOperand(0); 9202 SDValue Src1 = N->getOperand(1); 9203 SDValue Src2 = N->getOperand(2); 9204 9205 if (isClampZeroToOne(Src0, Src1)) { 9206 // const_a, const_b, x -> clamp is safe in all cases including signaling 9207 // nans. 9208 // FIXME: Should this be allowing -0.0? 9209 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9210 } 9211 9212 const MachineFunction &MF = DAG.getMachineFunction(); 9213 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9214 9215 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9216 // handling no dx10-clamp? 9217 if (Info->getMode().DX10Clamp) { 9218 // If NaNs is clamped to 0, we are free to reorder the inputs. 9219 9220 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9221 std::swap(Src0, Src1); 9222 9223 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9224 std::swap(Src1, Src2); 9225 9226 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9227 std::swap(Src0, Src1); 9228 9229 if (isClampZeroToOne(Src1, Src2)) 9230 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9231 } 9232 9233 return SDValue(); 9234 } 9235 9236 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9237 DAGCombinerInfo &DCI) const { 9238 SDValue Src0 = N->getOperand(0); 9239 SDValue Src1 = N->getOperand(1); 9240 if (Src0.isUndef() && Src1.isUndef()) 9241 return DCI.DAG.getUNDEF(N->getValueType(0)); 9242 return SDValue(); 9243 } 9244 9245 SDValue SITargetLowering::performExtractVectorEltCombine( 9246 SDNode *N, DAGCombinerInfo &DCI) const { 9247 SDValue Vec = N->getOperand(0); 9248 SelectionDAG &DAG = DCI.DAG; 9249 9250 EVT VecVT = Vec.getValueType(); 9251 EVT EltVT = VecVT.getVectorElementType(); 9252 9253 if ((Vec.getOpcode() == ISD::FNEG || 9254 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9255 SDLoc SL(N); 9256 EVT EltVT = N->getValueType(0); 9257 SDValue Idx = N->getOperand(1); 9258 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9259 Vec.getOperand(0), Idx); 9260 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9261 } 9262 9263 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9264 // => 9265 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9266 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9267 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9268 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9269 SDLoc SL(N); 9270 EVT EltVT = N->getValueType(0); 9271 SDValue Idx = N->getOperand(1); 9272 unsigned Opc = Vec.getOpcode(); 9273 9274 switch(Opc) { 9275 default: 9276 break; 9277 // TODO: Support other binary operations. 9278 case ISD::FADD: 9279 case ISD::FSUB: 9280 case ISD::FMUL: 9281 case ISD::ADD: 9282 case ISD::UMIN: 9283 case ISD::UMAX: 9284 case ISD::SMIN: 9285 case ISD::SMAX: 9286 case ISD::FMAXNUM: 9287 case ISD::FMINNUM: 9288 case ISD::FMAXNUM_IEEE: 9289 case ISD::FMINNUM_IEEE: { 9290 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9291 Vec.getOperand(0), Idx); 9292 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9293 Vec.getOperand(1), Idx); 9294 9295 DCI.AddToWorklist(Elt0.getNode()); 9296 DCI.AddToWorklist(Elt1.getNode()); 9297 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9298 } 9299 } 9300 } 9301 9302 unsigned VecSize = VecVT.getSizeInBits(); 9303 unsigned EltSize = EltVT.getSizeInBits(); 9304 9305 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9306 // This elminates non-constant index and subsequent movrel or scratch access. 9307 // Sub-dword vectors of size 2 dword or less have better implementation. 9308 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9309 // instructions. 9310 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9311 !isa<ConstantSDNode>(N->getOperand(1))) { 9312 SDLoc SL(N); 9313 SDValue Idx = N->getOperand(1); 9314 EVT IdxVT = Idx.getValueType(); 9315 SDValue V; 9316 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9317 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9318 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9319 if (I == 0) 9320 V = Elt; 9321 else 9322 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9323 } 9324 return V; 9325 } 9326 9327 if (!DCI.isBeforeLegalize()) 9328 return SDValue(); 9329 9330 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9331 // elements. This exposes more load reduction opportunities by replacing 9332 // multiple small extract_vector_elements with a single 32-bit extract. 9333 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9334 if (isa<MemSDNode>(Vec) && 9335 EltSize <= 16 && 9336 EltVT.isByteSized() && 9337 VecSize > 32 && 9338 VecSize % 32 == 0 && 9339 Idx) { 9340 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9341 9342 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9343 unsigned EltIdx = BitIndex / 32; 9344 unsigned LeftoverBitIdx = BitIndex % 32; 9345 SDLoc SL(N); 9346 9347 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9348 DCI.AddToWorklist(Cast.getNode()); 9349 9350 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9351 DAG.getConstant(EltIdx, SL, MVT::i32)); 9352 DCI.AddToWorklist(Elt.getNode()); 9353 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9354 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9355 DCI.AddToWorklist(Srl.getNode()); 9356 9357 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9358 DCI.AddToWorklist(Trunc.getNode()); 9359 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9360 } 9361 9362 return SDValue(); 9363 } 9364 9365 SDValue 9366 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9367 DAGCombinerInfo &DCI) const { 9368 SDValue Vec = N->getOperand(0); 9369 SDValue Idx = N->getOperand(2); 9370 EVT VecVT = Vec.getValueType(); 9371 EVT EltVT = VecVT.getVectorElementType(); 9372 unsigned VecSize = VecVT.getSizeInBits(); 9373 unsigned EltSize = EltVT.getSizeInBits(); 9374 9375 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9376 // => BUILD_VECTOR n x select (e, const-idx) 9377 // This elminates non-constant index and subsequent movrel or scratch access. 9378 // Sub-dword vectors of size 2 dword or less have better implementation. 9379 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9380 // instructions. 9381 if (isa<ConstantSDNode>(Idx) || 9382 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9383 return SDValue(); 9384 9385 SelectionDAG &DAG = DCI.DAG; 9386 SDLoc SL(N); 9387 SDValue Ins = N->getOperand(1); 9388 EVT IdxVT = Idx.getValueType(); 9389 9390 SmallVector<SDValue, 16> Ops; 9391 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9392 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9393 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9394 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9395 Ops.push_back(V); 9396 } 9397 9398 return DAG.getBuildVector(VecVT, SL, Ops); 9399 } 9400 9401 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9402 const SDNode *N0, 9403 const SDNode *N1) const { 9404 EVT VT = N0->getValueType(0); 9405 9406 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9407 // support denormals ever. 9408 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9409 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9410 getSubtarget()->hasMadF16())) && 9411 isOperationLegal(ISD::FMAD, VT)) 9412 return ISD::FMAD; 9413 9414 const TargetOptions &Options = DAG.getTarget().Options; 9415 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9416 (N0->getFlags().hasAllowContract() && 9417 N1->getFlags().hasAllowContract())) && 9418 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9419 return ISD::FMA; 9420 } 9421 9422 return 0; 9423 } 9424 9425 // For a reassociatable opcode perform: 9426 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9427 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9428 SelectionDAG &DAG) const { 9429 EVT VT = N->getValueType(0); 9430 if (VT != MVT::i32 && VT != MVT::i64) 9431 return SDValue(); 9432 9433 unsigned Opc = N->getOpcode(); 9434 SDValue Op0 = N->getOperand(0); 9435 SDValue Op1 = N->getOperand(1); 9436 9437 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9438 return SDValue(); 9439 9440 if (Op0->isDivergent()) 9441 std::swap(Op0, Op1); 9442 9443 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9444 return SDValue(); 9445 9446 SDValue Op2 = Op1.getOperand(1); 9447 Op1 = Op1.getOperand(0); 9448 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9449 return SDValue(); 9450 9451 if (Op1->isDivergent()) 9452 std::swap(Op1, Op2); 9453 9454 // If either operand is constant this will conflict with 9455 // DAGCombiner::ReassociateOps(). 9456 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9457 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9458 return SDValue(); 9459 9460 SDLoc SL(N); 9461 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9462 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9463 } 9464 9465 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9466 EVT VT, 9467 SDValue N0, SDValue N1, SDValue N2, 9468 bool Signed) { 9469 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9470 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9471 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9472 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9473 } 9474 9475 SDValue SITargetLowering::performAddCombine(SDNode *N, 9476 DAGCombinerInfo &DCI) const { 9477 SelectionDAG &DAG = DCI.DAG; 9478 EVT VT = N->getValueType(0); 9479 SDLoc SL(N); 9480 SDValue LHS = N->getOperand(0); 9481 SDValue RHS = N->getOperand(1); 9482 9483 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9484 && Subtarget->hasMad64_32() && 9485 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9486 VT.getScalarSizeInBits() <= 64) { 9487 if (LHS.getOpcode() != ISD::MUL) 9488 std::swap(LHS, RHS); 9489 9490 SDValue MulLHS = LHS.getOperand(0); 9491 SDValue MulRHS = LHS.getOperand(1); 9492 SDValue AddRHS = RHS; 9493 9494 // TODO: Maybe restrict if SGPR inputs. 9495 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9496 numBitsUnsigned(MulRHS, DAG) <= 32) { 9497 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9498 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9499 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9500 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9501 } 9502 9503 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9504 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9505 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9506 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9507 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9508 } 9509 9510 return SDValue(); 9511 } 9512 9513 if (SDValue V = reassociateScalarOps(N, DAG)) { 9514 return V; 9515 } 9516 9517 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9518 return SDValue(); 9519 9520 // add x, zext (setcc) => addcarry x, 0, setcc 9521 // add x, sext (setcc) => subcarry x, 0, setcc 9522 unsigned Opc = LHS.getOpcode(); 9523 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9524 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9525 std::swap(RHS, LHS); 9526 9527 Opc = RHS.getOpcode(); 9528 switch (Opc) { 9529 default: break; 9530 case ISD::ZERO_EXTEND: 9531 case ISD::SIGN_EXTEND: 9532 case ISD::ANY_EXTEND: { 9533 auto Cond = RHS.getOperand(0); 9534 // If this won't be a real VOPC output, we would still need to insert an 9535 // extra instruction anyway. 9536 if (!isBoolSGPR(Cond)) 9537 break; 9538 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9539 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9540 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9541 return DAG.getNode(Opc, SL, VTList, Args); 9542 } 9543 case ISD::ADDCARRY: { 9544 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9545 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9546 if (!C || C->getZExtValue() != 0) break; 9547 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9548 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9549 } 9550 } 9551 return SDValue(); 9552 } 9553 9554 SDValue SITargetLowering::performSubCombine(SDNode *N, 9555 DAGCombinerInfo &DCI) const { 9556 SelectionDAG &DAG = DCI.DAG; 9557 EVT VT = N->getValueType(0); 9558 9559 if (VT != MVT::i32) 9560 return SDValue(); 9561 9562 SDLoc SL(N); 9563 SDValue LHS = N->getOperand(0); 9564 SDValue RHS = N->getOperand(1); 9565 9566 // sub x, zext (setcc) => subcarry x, 0, setcc 9567 // sub x, sext (setcc) => addcarry x, 0, setcc 9568 unsigned Opc = RHS.getOpcode(); 9569 switch (Opc) { 9570 default: break; 9571 case ISD::ZERO_EXTEND: 9572 case ISD::SIGN_EXTEND: 9573 case ISD::ANY_EXTEND: { 9574 auto Cond = RHS.getOperand(0); 9575 // If this won't be a real VOPC output, we would still need to insert an 9576 // extra instruction anyway. 9577 if (!isBoolSGPR(Cond)) 9578 break; 9579 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9580 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9581 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9582 return DAG.getNode(Opc, SL, VTList, Args); 9583 } 9584 } 9585 9586 if (LHS.getOpcode() == ISD::SUBCARRY) { 9587 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9588 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9589 if (!C || !C->isNullValue()) 9590 return SDValue(); 9591 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9592 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9593 } 9594 return SDValue(); 9595 } 9596 9597 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9598 DAGCombinerInfo &DCI) const { 9599 9600 if (N->getValueType(0) != MVT::i32) 9601 return SDValue(); 9602 9603 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9604 if (!C || C->getZExtValue() != 0) 9605 return SDValue(); 9606 9607 SelectionDAG &DAG = DCI.DAG; 9608 SDValue LHS = N->getOperand(0); 9609 9610 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9611 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9612 unsigned LHSOpc = LHS.getOpcode(); 9613 unsigned Opc = N->getOpcode(); 9614 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9615 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9616 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9617 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9618 } 9619 return SDValue(); 9620 } 9621 9622 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9623 DAGCombinerInfo &DCI) const { 9624 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9625 return SDValue(); 9626 9627 SelectionDAG &DAG = DCI.DAG; 9628 EVT VT = N->getValueType(0); 9629 9630 SDLoc SL(N); 9631 SDValue LHS = N->getOperand(0); 9632 SDValue RHS = N->getOperand(1); 9633 9634 // These should really be instruction patterns, but writing patterns with 9635 // source modiifiers is a pain. 9636 9637 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9638 if (LHS.getOpcode() == ISD::FADD) { 9639 SDValue A = LHS.getOperand(0); 9640 if (A == LHS.getOperand(1)) { 9641 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9642 if (FusedOp != 0) { 9643 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9644 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9645 } 9646 } 9647 } 9648 9649 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9650 if (RHS.getOpcode() == ISD::FADD) { 9651 SDValue A = RHS.getOperand(0); 9652 if (A == RHS.getOperand(1)) { 9653 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9654 if (FusedOp != 0) { 9655 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9656 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9657 } 9658 } 9659 } 9660 9661 return SDValue(); 9662 } 9663 9664 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9665 DAGCombinerInfo &DCI) const { 9666 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9667 return SDValue(); 9668 9669 SelectionDAG &DAG = DCI.DAG; 9670 SDLoc SL(N); 9671 EVT VT = N->getValueType(0); 9672 assert(!VT.isVector()); 9673 9674 // Try to get the fneg to fold into the source modifier. This undoes generic 9675 // DAG combines and folds them into the mad. 9676 // 9677 // Only do this if we are not trying to support denormals. v_mad_f32 does 9678 // not support denormals ever. 9679 SDValue LHS = N->getOperand(0); 9680 SDValue RHS = N->getOperand(1); 9681 if (LHS.getOpcode() == ISD::FADD) { 9682 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9683 SDValue A = LHS.getOperand(0); 9684 if (A == LHS.getOperand(1)) { 9685 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9686 if (FusedOp != 0){ 9687 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9688 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9689 9690 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9691 } 9692 } 9693 } 9694 9695 if (RHS.getOpcode() == ISD::FADD) { 9696 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9697 9698 SDValue A = RHS.getOperand(0); 9699 if (A == RHS.getOperand(1)) { 9700 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9701 if (FusedOp != 0){ 9702 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9703 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9704 } 9705 } 9706 } 9707 9708 return SDValue(); 9709 } 9710 9711 SDValue SITargetLowering::performFMACombine(SDNode *N, 9712 DAGCombinerInfo &DCI) const { 9713 SelectionDAG &DAG = DCI.DAG; 9714 EVT VT = N->getValueType(0); 9715 SDLoc SL(N); 9716 9717 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9718 return SDValue(); 9719 9720 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9721 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9722 SDValue Op1 = N->getOperand(0); 9723 SDValue Op2 = N->getOperand(1); 9724 SDValue FMA = N->getOperand(2); 9725 9726 if (FMA.getOpcode() != ISD::FMA || 9727 Op1.getOpcode() != ISD::FP_EXTEND || 9728 Op2.getOpcode() != ISD::FP_EXTEND) 9729 return SDValue(); 9730 9731 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9732 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9733 // is sufficient to allow generaing fdot2. 9734 const TargetOptions &Options = DAG.getTarget().Options; 9735 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9736 (N->getFlags().hasAllowContract() && 9737 FMA->getFlags().hasAllowContract())) { 9738 Op1 = Op1.getOperand(0); 9739 Op2 = Op2.getOperand(0); 9740 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9741 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9742 return SDValue(); 9743 9744 SDValue Vec1 = Op1.getOperand(0); 9745 SDValue Idx1 = Op1.getOperand(1); 9746 SDValue Vec2 = Op2.getOperand(0); 9747 9748 SDValue FMAOp1 = FMA.getOperand(0); 9749 SDValue FMAOp2 = FMA.getOperand(1); 9750 SDValue FMAAcc = FMA.getOperand(2); 9751 9752 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9753 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9754 return SDValue(); 9755 9756 FMAOp1 = FMAOp1.getOperand(0); 9757 FMAOp2 = FMAOp2.getOperand(0); 9758 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9759 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9760 return SDValue(); 9761 9762 SDValue Vec3 = FMAOp1.getOperand(0); 9763 SDValue Vec4 = FMAOp2.getOperand(0); 9764 SDValue Idx2 = FMAOp1.getOperand(1); 9765 9766 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9767 // Idx1 and Idx2 cannot be the same. 9768 Idx1 == Idx2) 9769 return SDValue(); 9770 9771 if (Vec1 == Vec2 || Vec3 == Vec4) 9772 return SDValue(); 9773 9774 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9775 return SDValue(); 9776 9777 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9778 (Vec1 == Vec4 && Vec2 == Vec3)) { 9779 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9780 DAG.getTargetConstant(0, SL, MVT::i1)); 9781 } 9782 } 9783 return SDValue(); 9784 } 9785 9786 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9787 DAGCombinerInfo &DCI) const { 9788 SelectionDAG &DAG = DCI.DAG; 9789 SDLoc SL(N); 9790 9791 SDValue LHS = N->getOperand(0); 9792 SDValue RHS = N->getOperand(1); 9793 EVT VT = LHS.getValueType(); 9794 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9795 9796 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9797 if (!CRHS) { 9798 CRHS = dyn_cast<ConstantSDNode>(LHS); 9799 if (CRHS) { 9800 std::swap(LHS, RHS); 9801 CC = getSetCCSwappedOperands(CC); 9802 } 9803 } 9804 9805 if (CRHS) { 9806 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9807 isBoolSGPR(LHS.getOperand(0))) { 9808 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9809 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9810 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9811 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9812 if ((CRHS->isAllOnesValue() && 9813 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9814 (CRHS->isNullValue() && 9815 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9816 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9817 DAG.getConstant(-1, SL, MVT::i1)); 9818 if ((CRHS->isAllOnesValue() && 9819 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9820 (CRHS->isNullValue() && 9821 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9822 return LHS.getOperand(0); 9823 } 9824 9825 uint64_t CRHSVal = CRHS->getZExtValue(); 9826 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9827 LHS.getOpcode() == ISD::SELECT && 9828 isa<ConstantSDNode>(LHS.getOperand(1)) && 9829 isa<ConstantSDNode>(LHS.getOperand(2)) && 9830 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9831 isBoolSGPR(LHS.getOperand(0))) { 9832 // Given CT != FT: 9833 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9834 // setcc (select cc, CT, CF), CF, ne => cc 9835 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9836 // setcc (select cc, CT, CF), CT, eq => cc 9837 uint64_t CT = LHS.getConstantOperandVal(1); 9838 uint64_t CF = LHS.getConstantOperandVal(2); 9839 9840 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9841 (CT == CRHSVal && CC == ISD::SETNE)) 9842 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9843 DAG.getConstant(-1, SL, MVT::i1)); 9844 if ((CF == CRHSVal && CC == ISD::SETNE) || 9845 (CT == CRHSVal && CC == ISD::SETEQ)) 9846 return LHS.getOperand(0); 9847 } 9848 } 9849 9850 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9851 VT != MVT::f16)) 9852 return SDValue(); 9853 9854 // Match isinf/isfinite pattern 9855 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9856 // (fcmp one (fabs x), inf) -> (fp_class x, 9857 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9858 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9859 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9860 if (!CRHS) 9861 return SDValue(); 9862 9863 const APFloat &APF = CRHS->getValueAPF(); 9864 if (APF.isInfinity() && !APF.isNegative()) { 9865 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9866 SIInstrFlags::N_INFINITY; 9867 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9868 SIInstrFlags::P_ZERO | 9869 SIInstrFlags::N_NORMAL | 9870 SIInstrFlags::P_NORMAL | 9871 SIInstrFlags::N_SUBNORMAL | 9872 SIInstrFlags::P_SUBNORMAL; 9873 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9874 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9875 DAG.getConstant(Mask, SL, MVT::i32)); 9876 } 9877 } 9878 9879 return SDValue(); 9880 } 9881 9882 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9883 DAGCombinerInfo &DCI) const { 9884 SelectionDAG &DAG = DCI.DAG; 9885 SDLoc SL(N); 9886 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9887 9888 SDValue Src = N->getOperand(0); 9889 SDValue Srl = N->getOperand(0); 9890 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9891 Srl = Srl.getOperand(0); 9892 9893 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9894 if (Srl.getOpcode() == ISD::SRL) { 9895 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9896 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9897 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9898 9899 if (const ConstantSDNode *C = 9900 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9901 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9902 EVT(MVT::i32)); 9903 9904 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9905 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9906 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9907 MVT::f32, Srl); 9908 } 9909 } 9910 } 9911 9912 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9913 9914 KnownBits Known; 9915 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9916 !DCI.isBeforeLegalizeOps()); 9917 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9918 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9919 DCI.CommitTargetLoweringOpt(TLO); 9920 } 9921 9922 return SDValue(); 9923 } 9924 9925 SDValue SITargetLowering::performClampCombine(SDNode *N, 9926 DAGCombinerInfo &DCI) const { 9927 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9928 if (!CSrc) 9929 return SDValue(); 9930 9931 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9932 const APFloat &F = CSrc->getValueAPF(); 9933 APFloat Zero = APFloat::getZero(F.getSemantics()); 9934 APFloat::cmpResult Cmp0 = F.compare(Zero); 9935 if (Cmp0 == APFloat::cmpLessThan || 9936 (Cmp0 == APFloat::cmpUnordered && 9937 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9938 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9939 } 9940 9941 APFloat One(F.getSemantics(), "1.0"); 9942 APFloat::cmpResult Cmp1 = F.compare(One); 9943 if (Cmp1 == APFloat::cmpGreaterThan) 9944 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9945 9946 return SDValue(CSrc, 0); 9947 } 9948 9949 9950 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9951 DAGCombinerInfo &DCI) const { 9952 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9953 return SDValue(); 9954 switch (N->getOpcode()) { 9955 default: 9956 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9957 case ISD::ADD: 9958 return performAddCombine(N, DCI); 9959 case ISD::SUB: 9960 return performSubCombine(N, DCI); 9961 case ISD::ADDCARRY: 9962 case ISD::SUBCARRY: 9963 return performAddCarrySubCarryCombine(N, DCI); 9964 case ISD::FADD: 9965 return performFAddCombine(N, DCI); 9966 case ISD::FSUB: 9967 return performFSubCombine(N, DCI); 9968 case ISD::SETCC: 9969 return performSetCCCombine(N, DCI); 9970 case ISD::FMAXNUM: 9971 case ISD::FMINNUM: 9972 case ISD::FMAXNUM_IEEE: 9973 case ISD::FMINNUM_IEEE: 9974 case ISD::SMAX: 9975 case ISD::SMIN: 9976 case ISD::UMAX: 9977 case ISD::UMIN: 9978 case AMDGPUISD::FMIN_LEGACY: 9979 case AMDGPUISD::FMAX_LEGACY: 9980 return performMinMaxCombine(N, DCI); 9981 case ISD::FMA: 9982 return performFMACombine(N, DCI); 9983 case ISD::LOAD: { 9984 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9985 return Widended; 9986 LLVM_FALLTHROUGH; 9987 } 9988 case ISD::STORE: 9989 case ISD::ATOMIC_LOAD: 9990 case ISD::ATOMIC_STORE: 9991 case ISD::ATOMIC_CMP_SWAP: 9992 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9993 case ISD::ATOMIC_SWAP: 9994 case ISD::ATOMIC_LOAD_ADD: 9995 case ISD::ATOMIC_LOAD_SUB: 9996 case ISD::ATOMIC_LOAD_AND: 9997 case ISD::ATOMIC_LOAD_OR: 9998 case ISD::ATOMIC_LOAD_XOR: 9999 case ISD::ATOMIC_LOAD_NAND: 10000 case ISD::ATOMIC_LOAD_MIN: 10001 case ISD::ATOMIC_LOAD_MAX: 10002 case ISD::ATOMIC_LOAD_UMIN: 10003 case ISD::ATOMIC_LOAD_UMAX: 10004 case ISD::ATOMIC_LOAD_FADD: 10005 case AMDGPUISD::ATOMIC_INC: 10006 case AMDGPUISD::ATOMIC_DEC: 10007 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10008 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10009 if (DCI.isBeforeLegalize()) 10010 break; 10011 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10012 case ISD::AND: 10013 return performAndCombine(N, DCI); 10014 case ISD::OR: 10015 return performOrCombine(N, DCI); 10016 case ISD::XOR: 10017 return performXorCombine(N, DCI); 10018 case ISD::ZERO_EXTEND: 10019 return performZeroExtendCombine(N, DCI); 10020 case ISD::SIGN_EXTEND_INREG: 10021 return performSignExtendInRegCombine(N , DCI); 10022 case AMDGPUISD::FP_CLASS: 10023 return performClassCombine(N, DCI); 10024 case ISD::FCANONICALIZE: 10025 return performFCanonicalizeCombine(N, DCI); 10026 case AMDGPUISD::RCP: 10027 return performRcpCombine(N, DCI); 10028 case AMDGPUISD::FRACT: 10029 case AMDGPUISD::RSQ: 10030 case AMDGPUISD::RCP_LEGACY: 10031 case AMDGPUISD::RSQ_LEGACY: 10032 case AMDGPUISD::RCP_IFLAG: 10033 case AMDGPUISD::RSQ_CLAMP: 10034 case AMDGPUISD::LDEXP: { 10035 SDValue Src = N->getOperand(0); 10036 if (Src.isUndef()) 10037 return Src; 10038 break; 10039 } 10040 case ISD::SINT_TO_FP: 10041 case ISD::UINT_TO_FP: 10042 return performUCharToFloatCombine(N, DCI); 10043 case AMDGPUISD::CVT_F32_UBYTE0: 10044 case AMDGPUISD::CVT_F32_UBYTE1: 10045 case AMDGPUISD::CVT_F32_UBYTE2: 10046 case AMDGPUISD::CVT_F32_UBYTE3: 10047 return performCvtF32UByteNCombine(N, DCI); 10048 case AMDGPUISD::FMED3: 10049 return performFMed3Combine(N, DCI); 10050 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10051 return performCvtPkRTZCombine(N, DCI); 10052 case AMDGPUISD::CLAMP: 10053 return performClampCombine(N, DCI); 10054 case ISD::SCALAR_TO_VECTOR: { 10055 SelectionDAG &DAG = DCI.DAG; 10056 EVT VT = N->getValueType(0); 10057 10058 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10059 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10060 SDLoc SL(N); 10061 SDValue Src = N->getOperand(0); 10062 EVT EltVT = Src.getValueType(); 10063 if (EltVT == MVT::f16) 10064 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10065 10066 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10067 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10068 } 10069 10070 break; 10071 } 10072 case ISD::EXTRACT_VECTOR_ELT: 10073 return performExtractVectorEltCombine(N, DCI); 10074 case ISD::INSERT_VECTOR_ELT: 10075 return performInsertVectorEltCombine(N, DCI); 10076 } 10077 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10078 } 10079 10080 /// Helper function for adjustWritemask 10081 static unsigned SubIdx2Lane(unsigned Idx) { 10082 switch (Idx) { 10083 default: return 0; 10084 case AMDGPU::sub0: return 0; 10085 case AMDGPU::sub1: return 1; 10086 case AMDGPU::sub2: return 2; 10087 case AMDGPU::sub3: return 3; 10088 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10089 } 10090 } 10091 10092 /// Adjust the writemask of MIMG instructions 10093 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10094 SelectionDAG &DAG) const { 10095 unsigned Opcode = Node->getMachineOpcode(); 10096 10097 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10098 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10099 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10100 return Node; // not implemented for D16 10101 10102 SDNode *Users[5] = { nullptr }; 10103 unsigned Lane = 0; 10104 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10105 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10106 unsigned NewDmask = 0; 10107 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10108 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10109 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10110 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10111 unsigned TFCLane = 0; 10112 bool HasChain = Node->getNumValues() > 1; 10113 10114 if (OldDmask == 0) { 10115 // These are folded out, but on the chance it happens don't assert. 10116 return Node; 10117 } 10118 10119 unsigned OldBitsSet = countPopulation(OldDmask); 10120 // Work out which is the TFE/LWE lane if that is enabled. 10121 if (UsesTFC) { 10122 TFCLane = OldBitsSet; 10123 } 10124 10125 // Try to figure out the used register components 10126 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10127 I != E; ++I) { 10128 10129 // Don't look at users of the chain. 10130 if (I.getUse().getResNo() != 0) 10131 continue; 10132 10133 // Abort if we can't understand the usage 10134 if (!I->isMachineOpcode() || 10135 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10136 return Node; 10137 10138 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10139 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10140 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10141 // set, etc. 10142 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10143 10144 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10145 if (UsesTFC && Lane == TFCLane) { 10146 Users[Lane] = *I; 10147 } else { 10148 // Set which texture component corresponds to the lane. 10149 unsigned Comp; 10150 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10151 Comp = countTrailingZeros(Dmask); 10152 Dmask &= ~(1 << Comp); 10153 } 10154 10155 // Abort if we have more than one user per component. 10156 if (Users[Lane]) 10157 return Node; 10158 10159 Users[Lane] = *I; 10160 NewDmask |= 1 << Comp; 10161 } 10162 } 10163 10164 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10165 bool NoChannels = !NewDmask; 10166 if (NoChannels) { 10167 if (!UsesTFC) { 10168 // No uses of the result and not using TFC. Then do nothing. 10169 return Node; 10170 } 10171 // If the original dmask has one channel - then nothing to do 10172 if (OldBitsSet == 1) 10173 return Node; 10174 // Use an arbitrary dmask - required for the instruction to work 10175 NewDmask = 1; 10176 } 10177 // Abort if there's no change 10178 if (NewDmask == OldDmask) 10179 return Node; 10180 10181 unsigned BitsSet = countPopulation(NewDmask); 10182 10183 // Check for TFE or LWE - increase the number of channels by one to account 10184 // for the extra return value 10185 // This will need adjustment for D16 if this is also included in 10186 // adjustWriteMask (this function) but at present D16 are excluded. 10187 unsigned NewChannels = BitsSet + UsesTFC; 10188 10189 int NewOpcode = 10190 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10191 assert(NewOpcode != -1 && 10192 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10193 "failed to find equivalent MIMG op"); 10194 10195 // Adjust the writemask in the node 10196 SmallVector<SDValue, 12> Ops; 10197 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10198 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10199 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10200 10201 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10202 10203 MVT ResultVT = NewChannels == 1 ? 10204 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10205 NewChannels == 5 ? 8 : NewChannels); 10206 SDVTList NewVTList = HasChain ? 10207 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10208 10209 10210 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10211 NewVTList, Ops); 10212 10213 if (HasChain) { 10214 // Update chain. 10215 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10216 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10217 } 10218 10219 if (NewChannels == 1) { 10220 assert(Node->hasNUsesOfValue(1, 0)); 10221 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10222 SDLoc(Node), Users[Lane]->getValueType(0), 10223 SDValue(NewNode, 0)); 10224 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10225 return nullptr; 10226 } 10227 10228 // Update the users of the node with the new indices 10229 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10230 SDNode *User = Users[i]; 10231 if (!User) { 10232 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10233 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10234 if (i || !NoChannels) 10235 continue; 10236 } else { 10237 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10238 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10239 } 10240 10241 switch (Idx) { 10242 default: break; 10243 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10244 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10245 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10246 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10247 } 10248 } 10249 10250 DAG.RemoveDeadNode(Node); 10251 return nullptr; 10252 } 10253 10254 static bool isFrameIndexOp(SDValue Op) { 10255 if (Op.getOpcode() == ISD::AssertZext) 10256 Op = Op.getOperand(0); 10257 10258 return isa<FrameIndexSDNode>(Op); 10259 } 10260 10261 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10262 /// with frame index operands. 10263 /// LLVM assumes that inputs are to these instructions are registers. 10264 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10265 SelectionDAG &DAG) const { 10266 if (Node->getOpcode() == ISD::CopyToReg) { 10267 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10268 SDValue SrcVal = Node->getOperand(2); 10269 10270 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10271 // to try understanding copies to physical registers. 10272 if (SrcVal.getValueType() == MVT::i1 && 10273 Register::isPhysicalRegister(DestReg->getReg())) { 10274 SDLoc SL(Node); 10275 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10276 SDValue VReg = DAG.getRegister( 10277 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10278 10279 SDNode *Glued = Node->getGluedNode(); 10280 SDValue ToVReg 10281 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10282 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10283 SDValue ToResultReg 10284 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10285 VReg, ToVReg.getValue(1)); 10286 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10287 DAG.RemoveDeadNode(Node); 10288 return ToResultReg.getNode(); 10289 } 10290 } 10291 10292 SmallVector<SDValue, 8> Ops; 10293 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10294 if (!isFrameIndexOp(Node->getOperand(i))) { 10295 Ops.push_back(Node->getOperand(i)); 10296 continue; 10297 } 10298 10299 SDLoc DL(Node); 10300 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10301 Node->getOperand(i).getValueType(), 10302 Node->getOperand(i)), 0)); 10303 } 10304 10305 return DAG.UpdateNodeOperands(Node, Ops); 10306 } 10307 10308 /// Fold the instructions after selecting them. 10309 /// Returns null if users were already updated. 10310 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10311 SelectionDAG &DAG) const { 10312 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10313 unsigned Opcode = Node->getMachineOpcode(); 10314 10315 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10316 !TII->isGather4(Opcode)) { 10317 return adjustWritemask(Node, DAG); 10318 } 10319 10320 if (Opcode == AMDGPU::INSERT_SUBREG || 10321 Opcode == AMDGPU::REG_SEQUENCE) { 10322 legalizeTargetIndependentNode(Node, DAG); 10323 return Node; 10324 } 10325 10326 switch (Opcode) { 10327 case AMDGPU::V_DIV_SCALE_F32: 10328 case AMDGPU::V_DIV_SCALE_F64: { 10329 // Satisfy the operand register constraint when one of the inputs is 10330 // undefined. Ordinarily each undef value will have its own implicit_def of 10331 // a vreg, so force these to use a single register. 10332 SDValue Src0 = Node->getOperand(0); 10333 SDValue Src1 = Node->getOperand(1); 10334 SDValue Src2 = Node->getOperand(2); 10335 10336 if ((Src0.isMachineOpcode() && 10337 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10338 (Src0 == Src1 || Src0 == Src2)) 10339 break; 10340 10341 MVT VT = Src0.getValueType().getSimpleVT(); 10342 const TargetRegisterClass *RC = 10343 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10344 10345 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10346 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10347 10348 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10349 UndefReg, Src0, SDValue()); 10350 10351 // src0 must be the same register as src1 or src2, even if the value is 10352 // undefined, so make sure we don't violate this constraint. 10353 if (Src0.isMachineOpcode() && 10354 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10355 if (Src1.isMachineOpcode() && 10356 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10357 Src0 = Src1; 10358 else if (Src2.isMachineOpcode() && 10359 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10360 Src0 = Src2; 10361 else { 10362 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10363 Src0 = UndefReg; 10364 Src1 = UndefReg; 10365 } 10366 } else 10367 break; 10368 10369 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10370 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10371 Ops.push_back(Node->getOperand(I)); 10372 10373 Ops.push_back(ImpDef.getValue(1)); 10374 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10375 } 10376 case AMDGPU::V_PERMLANE16_B32: 10377 case AMDGPU::V_PERMLANEX16_B32: { 10378 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10379 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10380 if (!FI->getZExtValue() && !BC->getZExtValue()) 10381 break; 10382 SDValue VDstIn = Node->getOperand(6); 10383 if (VDstIn.isMachineOpcode() 10384 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10385 break; 10386 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10387 SDLoc(Node), MVT::i32); 10388 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10389 SDValue(BC, 0), Node->getOperand(3), 10390 Node->getOperand(4), Node->getOperand(5), 10391 SDValue(ImpDef, 0), Node->getOperand(7) }; 10392 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10393 } 10394 default: 10395 break; 10396 } 10397 10398 return Node; 10399 } 10400 10401 /// Assign the register class depending on the number of 10402 /// bits set in the writemask 10403 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10404 SDNode *Node) const { 10405 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10406 10407 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10408 10409 if (TII->isVOP3(MI.getOpcode())) { 10410 // Make sure constant bus requirements are respected. 10411 TII->legalizeOperandsVOP3(MRI, MI); 10412 10413 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10414 // This saves a chain-copy of registers and better ballance register 10415 // use between vgpr and agpr as agpr tuples tend to be big. 10416 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10417 unsigned Opc = MI.getOpcode(); 10418 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10419 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10420 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10421 if (I == -1) 10422 break; 10423 MachineOperand &Op = MI.getOperand(I); 10424 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10425 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10426 !Register::isVirtualRegister(Op.getReg()) || 10427 !TRI->isAGPR(MRI, Op.getReg())) 10428 continue; 10429 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10430 if (!Src || !Src->isCopy() || 10431 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10432 continue; 10433 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10434 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10435 // All uses of agpr64 and agpr32 can also accept vgpr except for 10436 // v_accvgpr_read, but we do not produce agpr reads during selection, 10437 // so no use checks are needed. 10438 MRI.setRegClass(Op.getReg(), NewRC); 10439 } 10440 } 10441 10442 return; 10443 } 10444 10445 // Replace unused atomics with the no return version. 10446 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10447 if (NoRetAtomicOp != -1) { 10448 if (!Node->hasAnyUseOfValue(0)) { 10449 MI.setDesc(TII->get(NoRetAtomicOp)); 10450 MI.RemoveOperand(0); 10451 return; 10452 } 10453 10454 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10455 // instruction, because the return type of these instructions is a vec2 of 10456 // the memory type, so it can be tied to the input operand. 10457 // This means these instructions always have a use, so we need to add a 10458 // special case to check if the atomic has only one extract_subreg use, 10459 // which itself has no uses. 10460 if ((Node->hasNUsesOfValue(1, 0) && 10461 Node->use_begin()->isMachineOpcode() && 10462 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10463 !Node->use_begin()->hasAnyUseOfValue(0))) { 10464 Register Def = MI.getOperand(0).getReg(); 10465 10466 // Change this into a noret atomic. 10467 MI.setDesc(TII->get(NoRetAtomicOp)); 10468 MI.RemoveOperand(0); 10469 10470 // If we only remove the def operand from the atomic instruction, the 10471 // extract_subreg will be left with a use of a vreg without a def. 10472 // So we need to insert an implicit_def to avoid machine verifier 10473 // errors. 10474 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10475 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10476 } 10477 return; 10478 } 10479 } 10480 10481 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10482 uint64_t Val) { 10483 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10484 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10485 } 10486 10487 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10488 const SDLoc &DL, 10489 SDValue Ptr) const { 10490 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10491 10492 // Build the half of the subregister with the constants before building the 10493 // full 128-bit register. If we are building multiple resource descriptors, 10494 // this will allow CSEing of the 2-component register. 10495 const SDValue Ops0[] = { 10496 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10497 buildSMovImm32(DAG, DL, 0), 10498 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10499 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10500 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10501 }; 10502 10503 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10504 MVT::v2i32, Ops0), 0); 10505 10506 // Combine the constants and the pointer. 10507 const SDValue Ops1[] = { 10508 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10509 Ptr, 10510 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10511 SubRegHi, 10512 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10513 }; 10514 10515 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10516 } 10517 10518 /// Return a resource descriptor with the 'Add TID' bit enabled 10519 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10520 /// of the resource descriptor) to create an offset, which is added to 10521 /// the resource pointer. 10522 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10523 SDValue Ptr, uint32_t RsrcDword1, 10524 uint64_t RsrcDword2And3) const { 10525 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10526 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10527 if (RsrcDword1) { 10528 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10529 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10530 0); 10531 } 10532 10533 SDValue DataLo = buildSMovImm32(DAG, DL, 10534 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10535 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10536 10537 const SDValue Ops[] = { 10538 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10539 PtrLo, 10540 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10541 PtrHi, 10542 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10543 DataLo, 10544 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10545 DataHi, 10546 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10547 }; 10548 10549 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10550 } 10551 10552 //===----------------------------------------------------------------------===// 10553 // SI Inline Assembly Support 10554 //===----------------------------------------------------------------------===// 10555 10556 std::pair<unsigned, const TargetRegisterClass *> 10557 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10558 StringRef Constraint, 10559 MVT VT) const { 10560 const TargetRegisterClass *RC = nullptr; 10561 if (Constraint.size() == 1) { 10562 switch (Constraint[0]) { 10563 default: 10564 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10565 case 's': 10566 case 'r': 10567 switch (VT.getSizeInBits()) { 10568 default: 10569 return std::make_pair(0U, nullptr); 10570 case 32: 10571 case 16: 10572 RC = &AMDGPU::SReg_32RegClass; 10573 break; 10574 case 64: 10575 RC = &AMDGPU::SGPR_64RegClass; 10576 break; 10577 case 96: 10578 RC = &AMDGPU::SReg_96RegClass; 10579 break; 10580 case 128: 10581 RC = &AMDGPU::SGPR_128RegClass; 10582 break; 10583 case 160: 10584 RC = &AMDGPU::SReg_160RegClass; 10585 break; 10586 case 256: 10587 RC = &AMDGPU::SReg_256RegClass; 10588 break; 10589 case 512: 10590 RC = &AMDGPU::SReg_512RegClass; 10591 break; 10592 } 10593 break; 10594 case 'v': 10595 switch (VT.getSizeInBits()) { 10596 default: 10597 return std::make_pair(0U, nullptr); 10598 case 32: 10599 case 16: 10600 RC = &AMDGPU::VGPR_32RegClass; 10601 break; 10602 case 64: 10603 RC = &AMDGPU::VReg_64RegClass; 10604 break; 10605 case 96: 10606 RC = &AMDGPU::VReg_96RegClass; 10607 break; 10608 case 128: 10609 RC = &AMDGPU::VReg_128RegClass; 10610 break; 10611 case 160: 10612 RC = &AMDGPU::VReg_160RegClass; 10613 break; 10614 case 256: 10615 RC = &AMDGPU::VReg_256RegClass; 10616 break; 10617 case 512: 10618 RC = &AMDGPU::VReg_512RegClass; 10619 break; 10620 } 10621 break; 10622 case 'a': 10623 if (!Subtarget->hasMAIInsts()) 10624 break; 10625 switch (VT.getSizeInBits()) { 10626 default: 10627 return std::make_pair(0U, nullptr); 10628 case 32: 10629 case 16: 10630 RC = &AMDGPU::AGPR_32RegClass; 10631 break; 10632 case 64: 10633 RC = &AMDGPU::AReg_64RegClass; 10634 break; 10635 case 128: 10636 RC = &AMDGPU::AReg_128RegClass; 10637 break; 10638 case 512: 10639 RC = &AMDGPU::AReg_512RegClass; 10640 break; 10641 case 1024: 10642 RC = &AMDGPU::AReg_1024RegClass; 10643 // v32 types are not legal but we support them here. 10644 return std::make_pair(0U, RC); 10645 } 10646 break; 10647 } 10648 // We actually support i128, i16 and f16 as inline parameters 10649 // even if they are not reported as legal 10650 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10651 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10652 return std::make_pair(0U, RC); 10653 } 10654 10655 if (Constraint.size() > 1) { 10656 if (Constraint[1] == 'v') { 10657 RC = &AMDGPU::VGPR_32RegClass; 10658 } else if (Constraint[1] == 's') { 10659 RC = &AMDGPU::SGPR_32RegClass; 10660 } else if (Constraint[1] == 'a') { 10661 RC = &AMDGPU::AGPR_32RegClass; 10662 } 10663 10664 if (RC) { 10665 uint32_t Idx; 10666 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10667 if (!Failed && Idx < RC->getNumRegs()) 10668 return std::make_pair(RC->getRegister(Idx), RC); 10669 } 10670 } 10671 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10672 } 10673 10674 SITargetLowering::ConstraintType 10675 SITargetLowering::getConstraintType(StringRef Constraint) const { 10676 if (Constraint.size() == 1) { 10677 switch (Constraint[0]) { 10678 default: break; 10679 case 's': 10680 case 'v': 10681 case 'a': 10682 return C_RegisterClass; 10683 } 10684 } 10685 return TargetLowering::getConstraintType(Constraint); 10686 } 10687 10688 // Figure out which registers should be reserved for stack access. Only after 10689 // the function is legalized do we know all of the non-spill stack objects or if 10690 // calls are present. 10691 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10692 MachineRegisterInfo &MRI = MF.getRegInfo(); 10693 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10694 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10695 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10696 10697 if (Info->isEntryFunction()) { 10698 // Callable functions have fixed registers used for stack access. 10699 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10700 } 10701 10702 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10703 Info->getStackPtrOffsetReg())); 10704 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10705 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10706 10707 // We need to worry about replacing the default register with itself in case 10708 // of MIR testcases missing the MFI. 10709 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10710 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10711 10712 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10713 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10714 10715 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10716 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10717 Info->getScratchWaveOffsetReg()); 10718 } 10719 10720 Info->limitOccupancy(MF); 10721 10722 if (ST.isWave32() && !MF.empty()) { 10723 // Add VCC_HI def because many instructions marked as imp-use VCC where 10724 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10725 // having a use of undef. 10726 10727 const SIInstrInfo *TII = ST.getInstrInfo(); 10728 DebugLoc DL; 10729 10730 MachineBasicBlock &MBB = MF.front(); 10731 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10732 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10733 10734 for (auto &MBB : MF) { 10735 for (auto &MI : MBB) { 10736 TII->fixImplicitOperands(MI); 10737 } 10738 } 10739 } 10740 10741 TargetLoweringBase::finalizeLowering(MF); 10742 } 10743 10744 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10745 KnownBits &Known, 10746 const APInt &DemandedElts, 10747 const SelectionDAG &DAG, 10748 unsigned Depth) const { 10749 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10750 DAG, Depth); 10751 10752 // Set the high bits to zero based on the maximum allowed scratch size per 10753 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10754 // calculation won't overflow, so assume the sign bit is never set. 10755 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10756 } 10757 10758 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10759 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10760 const Align CacheLineAlign = Align(64); 10761 10762 // Pre-GFX10 target did not benefit from loop alignment 10763 if (!ML || DisableLoopAlignment || 10764 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10765 getSubtarget()->hasInstFwdPrefetchBug()) 10766 return PrefAlign; 10767 10768 // On GFX10 I$ is 4 x 64 bytes cache lines. 10769 // By default prefetcher keeps one cache line behind and reads two ahead. 10770 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10771 // behind and one ahead. 10772 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10773 // If loop fits 64 bytes it always spans no more than two cache lines and 10774 // does not need an alignment. 10775 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10776 // Else if loop is less or equal 192 bytes we need two lines behind. 10777 10778 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10779 const MachineBasicBlock *Header = ML->getHeader(); 10780 if (Header->getAlignment() != PrefAlign) 10781 return Header->getAlignment(); // Already processed. 10782 10783 unsigned LoopSize = 0; 10784 for (const MachineBasicBlock *MBB : ML->blocks()) { 10785 // If inner loop block is aligned assume in average half of the alignment 10786 // size to be added as nops. 10787 if (MBB != Header) 10788 LoopSize += MBB->getAlignment().value() / 2; 10789 10790 for (const MachineInstr &MI : *MBB) { 10791 LoopSize += TII->getInstSizeInBytes(MI); 10792 if (LoopSize > 192) 10793 return PrefAlign; 10794 } 10795 } 10796 10797 if (LoopSize <= 64) 10798 return PrefAlign; 10799 10800 if (LoopSize <= 128) 10801 return CacheLineAlign; 10802 10803 // If any of parent loops is surrounded by prefetch instructions do not 10804 // insert new for inner loop, which would reset parent's settings. 10805 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10806 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10807 auto I = Exit->getFirstNonDebugInstr(); 10808 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10809 return CacheLineAlign; 10810 } 10811 } 10812 10813 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10814 MachineBasicBlock *Exit = ML->getExitBlock(); 10815 10816 if (Pre && Exit) { 10817 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10818 TII->get(AMDGPU::S_INST_PREFETCH)) 10819 .addImm(1); // prefetch 2 lines behind PC 10820 10821 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10822 TII->get(AMDGPU::S_INST_PREFETCH)) 10823 .addImm(2); // prefetch 1 line behind PC 10824 } 10825 10826 return CacheLineAlign; 10827 } 10828 10829 LLVM_ATTRIBUTE_UNUSED 10830 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10831 assert(N->getOpcode() == ISD::CopyFromReg); 10832 do { 10833 // Follow the chain until we find an INLINEASM node. 10834 N = N->getOperand(0).getNode(); 10835 if (N->getOpcode() == ISD::INLINEASM || 10836 N->getOpcode() == ISD::INLINEASM_BR) 10837 return true; 10838 } while (N->getOpcode() == ISD::CopyFromReg); 10839 return false; 10840 } 10841 10842 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10843 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10844 { 10845 switch (N->getOpcode()) { 10846 case ISD::CopyFromReg: 10847 { 10848 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10849 const MachineFunction * MF = FLI->MF; 10850 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10851 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10852 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10853 unsigned Reg = R->getReg(); 10854 if (Register::isPhysicalRegister(Reg)) 10855 return !TRI.isSGPRReg(MRI, Reg); 10856 10857 if (MRI.isLiveIn(Reg)) { 10858 // workitem.id.x workitem.id.y workitem.id.z 10859 // Any VGPR formal argument is also considered divergent 10860 if (!TRI.isSGPRReg(MRI, Reg)) 10861 return true; 10862 // Formal arguments of non-entry functions 10863 // are conservatively considered divergent 10864 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10865 return true; 10866 return false; 10867 } 10868 const Value *V = FLI->getValueFromVirtualReg(Reg); 10869 if (V) 10870 return KDA->isDivergent(V); 10871 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10872 return !TRI.isSGPRReg(MRI, Reg); 10873 } 10874 break; 10875 case ISD::LOAD: { 10876 const LoadSDNode *L = cast<LoadSDNode>(N); 10877 unsigned AS = L->getAddressSpace(); 10878 // A flat load may access private memory. 10879 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10880 } break; 10881 case ISD::CALLSEQ_END: 10882 return true; 10883 break; 10884 case ISD::INTRINSIC_WO_CHAIN: 10885 { 10886 10887 } 10888 return AMDGPU::isIntrinsicSourceOfDivergence( 10889 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10890 case ISD::INTRINSIC_W_CHAIN: 10891 return AMDGPU::isIntrinsicSourceOfDivergence( 10892 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10893 } 10894 return false; 10895 } 10896 10897 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10898 EVT VT) const { 10899 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10900 case MVT::f32: 10901 return hasFP32Denormals(DAG.getMachineFunction()); 10902 case MVT::f64: 10903 case MVT::f16: 10904 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10905 default: 10906 return false; 10907 } 10908 } 10909 10910 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10911 const SelectionDAG &DAG, 10912 bool SNaN, 10913 unsigned Depth) const { 10914 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10915 const MachineFunction &MF = DAG.getMachineFunction(); 10916 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10917 10918 if (Info->getMode().DX10Clamp) 10919 return true; // Clamped to 0. 10920 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10921 } 10922 10923 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10924 SNaN, Depth); 10925 } 10926 10927 TargetLowering::AtomicExpansionKind 10928 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10929 switch (RMW->getOperation()) { 10930 case AtomicRMWInst::FAdd: { 10931 Type *Ty = RMW->getType(); 10932 10933 // We don't have a way to support 16-bit atomics now, so just leave them 10934 // as-is. 10935 if (Ty->isHalfTy()) 10936 return AtomicExpansionKind::None; 10937 10938 if (!Ty->isFloatTy()) 10939 return AtomicExpansionKind::CmpXChg; 10940 10941 // TODO: Do have these for flat. Older targets also had them for buffers. 10942 unsigned AS = RMW->getPointerAddressSpace(); 10943 10944 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10945 return RMW->use_empty() ? AtomicExpansionKind::None : 10946 AtomicExpansionKind::CmpXChg; 10947 } 10948 10949 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10950 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10951 } 10952 default: 10953 break; 10954 } 10955 10956 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10957 } 10958 10959 const TargetRegisterClass * 10960 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10961 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10962 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10963 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10964 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10965 : &AMDGPU::SReg_32RegClass; 10966 if (!TRI->isSGPRClass(RC) && !isDivergent) 10967 return TRI->getEquivalentSGPRClass(RC); 10968 else if (TRI->isSGPRClass(RC) && isDivergent) 10969 return TRI->getEquivalentVGPRClass(RC); 10970 10971 return RC; 10972 } 10973 10974 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) { 10975 if (!isa<Instruction>(V)) 10976 return false; 10977 if (!Visited.insert(V).second) 10978 return false; 10979 bool Result = false; 10980 for (auto U : V->users()) { 10981 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10982 if (V == U->getOperand(1)) { 10983 switch (Intrinsic->getIntrinsicID()) { 10984 default: 10985 Result = false; 10986 break; 10987 case Intrinsic::amdgcn_if_break: 10988 case Intrinsic::amdgcn_if: 10989 case Intrinsic::amdgcn_else: 10990 Result = true; 10991 break; 10992 } 10993 } 10994 if (V == U->getOperand(0)) { 10995 switch (Intrinsic->getIntrinsicID()) { 10996 default: 10997 Result = false; 10998 break; 10999 case Intrinsic::amdgcn_end_cf: 11000 case Intrinsic::amdgcn_loop: 11001 Result = true; 11002 break; 11003 } 11004 } 11005 } else { 11006 Result = hasCFUser(U, Visited); 11007 } 11008 if (Result) 11009 break; 11010 } 11011 return Result; 11012 } 11013 11014 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11015 const Value *V) const { 11016 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 11017 switch (Intrinsic->getIntrinsicID()) { 11018 default: 11019 return false; 11020 case Intrinsic::amdgcn_if_break: 11021 return true; 11022 } 11023 } 11024 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 11025 if (const IntrinsicInst *Intrinsic = 11026 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 11027 switch (Intrinsic->getIntrinsicID()) { 11028 default: 11029 return false; 11030 case Intrinsic::amdgcn_if: 11031 case Intrinsic::amdgcn_else: { 11032 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 11033 if (Indices.size() == 1 && Indices[0] == 1) { 11034 return true; 11035 } 11036 } 11037 } 11038 } 11039 } 11040 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11041 if (isa<InlineAsm>(CI->getCalledValue())) { 11042 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11043 ImmutableCallSite CS(CI); 11044 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11045 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 11046 for (auto &TC : TargetConstraints) { 11047 if (TC.Type == InlineAsm::isOutput) { 11048 ComputeConstraintToUse(TC, SDValue()); 11049 unsigned AssignedReg; 11050 const TargetRegisterClass *RC; 11051 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11052 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11053 if (RC) { 11054 MachineRegisterInfo &MRI = MF.getRegInfo(); 11055 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11056 return true; 11057 else if (SIRI->isSGPRClass(RC)) 11058 return true; 11059 } 11060 } 11061 } 11062 } 11063 } 11064 SmallPtrSet<const Value *, 16> Visited; 11065 return hasCFUser(V, Visited); 11066 } 11067