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> EnableVGPRIndexMode( 94 "amdgpu-vgpr-index-mode", 95 cl::desc("Use GPR indexing mode instead of movrel for vector indexing"), 96 cl::init(false)); 97 98 static cl::opt<bool> DisableLoopAlignment( 99 "amdgpu-disable-loop-alignment", 100 cl::desc("Do not align and prefetch loops"), 101 cl::init(false)); 102 103 static bool hasFP32Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().FP32Denormals; 106 } 107 108 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 109 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 110 return Info->getMode().FP64FP16Denormals; 111 } 112 113 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 114 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 115 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 116 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 117 return AMDGPU::SGPR0 + Reg; 118 } 119 } 120 llvm_unreachable("Cannot allocate sgpr"); 121 } 122 123 SITargetLowering::SITargetLowering(const TargetMachine &TM, 124 const GCNSubtarget &STI) 125 : AMDGPUTargetLowering(TM, STI), 126 Subtarget(&STI) { 127 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 128 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 129 130 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 131 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 132 133 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 134 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 135 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 136 137 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 138 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 139 140 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 141 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 142 143 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 144 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 145 146 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 147 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 148 149 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 150 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 151 152 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 153 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 154 155 if (Subtarget->has16BitInsts()) { 156 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 157 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 158 159 // Unless there are also VOP3P operations, not operations are really legal. 160 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 161 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 162 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 163 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 164 } 165 166 if (Subtarget->hasMAIInsts()) { 167 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 168 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 169 } 170 171 computeRegisterProperties(Subtarget->getRegisterInfo()); 172 173 // The boolean content concept here is too inflexible. Compares only ever 174 // really produce a 1-bit result. Any copy/extend from these will turn into a 175 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 176 // it's what most targets use. 177 setBooleanContents(ZeroOrOneBooleanContent); 178 setBooleanVectorContents(ZeroOrOneBooleanContent); 179 180 // We need to custom lower vector stores from local memory 181 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 182 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 183 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 184 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 185 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 186 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 187 setOperationAction(ISD::LOAD, MVT::i1, Custom); 188 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 189 190 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 191 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 192 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 193 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 194 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 195 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 196 setOperationAction(ISD::STORE, MVT::i1, Custom); 197 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 198 199 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 200 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 201 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 202 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 203 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 204 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 205 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 206 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 207 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 208 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 209 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 210 211 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 212 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 213 214 setOperationAction(ISD::SELECT, MVT::i1, Promote); 215 setOperationAction(ISD::SELECT, MVT::i64, Custom); 216 setOperationAction(ISD::SELECT, MVT::f64, Promote); 217 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 218 219 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 220 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 221 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 222 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 223 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 224 225 setOperationAction(ISD::SETCC, MVT::i1, Promote); 226 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 227 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 228 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 229 230 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 231 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 232 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 238 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 239 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 240 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 241 242 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 243 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 244 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 245 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 246 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 247 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 248 249 setOperationAction(ISD::UADDO, MVT::i32, Legal); 250 setOperationAction(ISD::USUBO, MVT::i32, Legal); 251 252 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 253 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 254 255 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 256 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 257 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 258 259 #if 0 260 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 261 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 262 #endif 263 264 // We only support LOAD/STORE and vector manipulation ops for vectors 265 // with > 4 elements. 266 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 267 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 268 MVT::v32i32, MVT::v32f32 }) { 269 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 270 switch (Op) { 271 case ISD::LOAD: 272 case ISD::STORE: 273 case ISD::BUILD_VECTOR: 274 case ISD::BITCAST: 275 case ISD::EXTRACT_VECTOR_ELT: 276 case ISD::INSERT_VECTOR_ELT: 277 case ISD::INSERT_SUBVECTOR: 278 case ISD::EXTRACT_SUBVECTOR: 279 case ISD::SCALAR_TO_VECTOR: 280 break; 281 case ISD::CONCAT_VECTORS: 282 setOperationAction(Op, VT, Custom); 283 break; 284 default: 285 setOperationAction(Op, VT, Expand); 286 break; 287 } 288 } 289 } 290 291 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 292 293 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 294 // is expanded to avoid having two separate loops in case the index is a VGPR. 295 296 // Most operations are naturally 32-bit vector operations. We only support 297 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 298 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 299 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 300 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 301 302 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 303 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 304 305 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 306 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 307 308 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 309 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 310 } 311 312 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 313 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 314 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 315 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 316 317 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 318 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 319 320 // Avoid stack access for these. 321 // TODO: Generalize to more vector types. 322 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 325 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 326 327 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 328 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 329 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 330 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 331 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 332 333 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 336 337 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 338 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 339 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 340 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 341 342 // Deal with vec3 vector operations when widened to vec4. 343 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 347 348 // Deal with vec5 vector operations when widened to vec8. 349 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 350 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 351 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 352 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 353 354 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 355 // and output demarshalling 356 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 358 359 // We can't return success/failure, only the old value, 360 // let LLVM add the comparison 361 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 362 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 363 364 if (Subtarget->hasFlatAddressSpace()) { 365 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 366 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 367 } 368 369 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 370 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 371 372 // On SI this is s_memtime and s_memrealtime on VI. 373 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 374 setOperationAction(ISD::TRAP, MVT::Other, Custom); 375 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 376 377 if (Subtarget->has16BitInsts()) { 378 setOperationAction(ISD::FLOG, MVT::f16, Custom); 379 setOperationAction(ISD::FEXP, MVT::f16, Custom); 380 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 381 } 382 383 // v_mad_f32 does not support denormals. We report it as unconditionally 384 // legal, and the context where it is formed will disallow it when fp32 385 // denormals are enabled. 386 setOperationAction(ISD::FMAD, MVT::f32, Legal); 387 388 if (!Subtarget->hasBFI()) { 389 // fcopysign can be done in a single instruction with BFI. 390 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 391 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 392 } 393 394 if (!Subtarget->hasBCNT(32)) 395 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 396 397 if (!Subtarget->hasBCNT(64)) 398 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 399 400 if (Subtarget->hasFFBH()) 401 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 402 403 if (Subtarget->hasFFBL()) 404 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 405 406 // We only really have 32-bit BFE instructions (and 16-bit on VI). 407 // 408 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 409 // effort to match them now. We want this to be false for i64 cases when the 410 // extraction isn't restricted to the upper or lower half. Ideally we would 411 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 412 // span the midpoint are probably relatively rare, so don't worry about them 413 // for now. 414 if (Subtarget->hasBFE()) 415 setHasExtractBitsInsn(true); 416 417 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 418 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 419 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 420 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 421 422 423 // These are really only legal for ieee_mode functions. We should be avoiding 424 // them for functions that don't have ieee_mode enabled, so just say they are 425 // legal. 426 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 427 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 428 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 429 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 430 431 432 if (Subtarget->haveRoundOpsF64()) { 433 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 434 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 435 setOperationAction(ISD::FRINT, MVT::f64, Legal); 436 } else { 437 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 438 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 439 setOperationAction(ISD::FRINT, MVT::f64, Custom); 440 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 441 } 442 443 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 444 445 setOperationAction(ISD::FSIN, MVT::f32, Custom); 446 setOperationAction(ISD::FCOS, MVT::f32, Custom); 447 setOperationAction(ISD::FDIV, MVT::f32, Custom); 448 setOperationAction(ISD::FDIV, MVT::f64, Custom); 449 450 if (Subtarget->has16BitInsts()) { 451 setOperationAction(ISD::Constant, MVT::i16, Legal); 452 453 setOperationAction(ISD::SMIN, MVT::i16, Legal); 454 setOperationAction(ISD::SMAX, MVT::i16, Legal); 455 456 setOperationAction(ISD::UMIN, MVT::i16, Legal); 457 setOperationAction(ISD::UMAX, MVT::i16, Legal); 458 459 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 460 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 461 462 setOperationAction(ISD::ROTR, MVT::i16, Promote); 463 setOperationAction(ISD::ROTL, MVT::i16, Promote); 464 465 setOperationAction(ISD::SDIV, MVT::i16, Promote); 466 setOperationAction(ISD::UDIV, MVT::i16, Promote); 467 setOperationAction(ISD::SREM, MVT::i16, Promote); 468 setOperationAction(ISD::UREM, MVT::i16, Promote); 469 470 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 471 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 472 473 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 474 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 475 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 476 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 477 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 478 479 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 480 481 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 482 483 setOperationAction(ISD::LOAD, MVT::i16, Custom); 484 485 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 486 487 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 488 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 489 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 490 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 491 492 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 493 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 494 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote); 495 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote); 496 497 // F16 - Constant Actions. 498 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 499 500 // F16 - Load/Store Actions. 501 setOperationAction(ISD::LOAD, MVT::f16, Promote); 502 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 503 setOperationAction(ISD::STORE, MVT::f16, Promote); 504 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 505 506 // F16 - VOP1 Actions. 507 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 508 setOperationAction(ISD::FCOS, MVT::f16, Promote); 509 setOperationAction(ISD::FSIN, MVT::f16, Promote); 510 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 511 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 512 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 513 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 514 setOperationAction(ISD::FROUND, MVT::f16, Custom); 515 516 // F16 - VOP2 Actions. 517 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 518 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 519 520 setOperationAction(ISD::FDIV, MVT::f16, Custom); 521 522 // F16 - VOP3 Actions. 523 setOperationAction(ISD::FMA, MVT::f16, Legal); 524 if (STI.hasMadF16()) 525 setOperationAction(ISD::FMAD, MVT::f16, Legal); 526 527 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 528 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 529 switch (Op) { 530 case ISD::LOAD: 531 case ISD::STORE: 532 case ISD::BUILD_VECTOR: 533 case ISD::BITCAST: 534 case ISD::EXTRACT_VECTOR_ELT: 535 case ISD::INSERT_VECTOR_ELT: 536 case ISD::INSERT_SUBVECTOR: 537 case ISD::EXTRACT_SUBVECTOR: 538 case ISD::SCALAR_TO_VECTOR: 539 break; 540 case ISD::CONCAT_VECTORS: 541 setOperationAction(Op, VT, Custom); 542 break; 543 default: 544 setOperationAction(Op, VT, Expand); 545 break; 546 } 547 } 548 } 549 550 // XXX - Do these do anything? Vector constants turn into build_vector. 551 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 552 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 553 554 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 555 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 556 557 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 558 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 559 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 560 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 561 562 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 563 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 564 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 565 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 566 567 setOperationAction(ISD::AND, MVT::v2i16, Promote); 568 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 569 setOperationAction(ISD::OR, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 571 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 572 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 573 574 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 575 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 576 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 577 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 578 579 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 580 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 581 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 582 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 583 584 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 585 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 586 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 587 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 588 589 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 590 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 591 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 592 593 if (!Subtarget->hasVOP3PInsts()) { 594 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 595 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 596 } 597 598 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 599 // This isn't really legal, but this avoids the legalizer unrolling it (and 600 // allows matching fneg (fabs x) patterns) 601 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 602 603 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 604 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 605 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 606 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 607 608 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 609 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 610 611 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 612 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 613 } 614 615 if (Subtarget->hasVOP3PInsts()) { 616 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 617 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 618 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 619 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 620 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 621 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 622 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 623 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 624 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 625 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 626 627 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 628 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 629 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 630 631 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 632 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 633 634 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 635 636 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 637 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 638 639 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 640 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 641 642 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 643 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 644 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 645 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 646 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 647 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 648 649 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 650 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 651 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 652 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 653 654 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 655 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 656 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 657 658 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 659 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 660 661 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 662 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 663 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 664 665 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 666 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 667 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 668 } 669 670 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 671 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 672 673 if (Subtarget->has16BitInsts()) { 674 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 675 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 676 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 677 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 678 } else { 679 // Legalization hack. 680 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 681 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 682 683 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 684 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 685 } 686 687 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 688 setOperationAction(ISD::SELECT, VT, Custom); 689 } 690 691 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 692 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 693 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 694 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 695 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 696 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 697 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 698 699 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 700 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 701 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 702 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 703 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 704 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 705 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 706 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 707 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 708 709 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 710 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 711 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 712 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 713 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 714 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 715 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 716 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 717 718 setTargetDAGCombine(ISD::ADD); 719 setTargetDAGCombine(ISD::ADDCARRY); 720 setTargetDAGCombine(ISD::SUB); 721 setTargetDAGCombine(ISD::SUBCARRY); 722 setTargetDAGCombine(ISD::FADD); 723 setTargetDAGCombine(ISD::FSUB); 724 setTargetDAGCombine(ISD::FMINNUM); 725 setTargetDAGCombine(ISD::FMAXNUM); 726 setTargetDAGCombine(ISD::FMINNUM_IEEE); 727 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 728 setTargetDAGCombine(ISD::FMA); 729 setTargetDAGCombine(ISD::SMIN); 730 setTargetDAGCombine(ISD::SMAX); 731 setTargetDAGCombine(ISD::UMIN); 732 setTargetDAGCombine(ISD::UMAX); 733 setTargetDAGCombine(ISD::SETCC); 734 setTargetDAGCombine(ISD::AND); 735 setTargetDAGCombine(ISD::OR); 736 setTargetDAGCombine(ISD::XOR); 737 setTargetDAGCombine(ISD::SINT_TO_FP); 738 setTargetDAGCombine(ISD::UINT_TO_FP); 739 setTargetDAGCombine(ISD::FCANONICALIZE); 740 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 741 setTargetDAGCombine(ISD::ZERO_EXTEND); 742 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 743 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 744 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 745 746 // All memory operations. Some folding on the pointer operand is done to help 747 // matching the constant offsets in the addressing modes. 748 setTargetDAGCombine(ISD::LOAD); 749 setTargetDAGCombine(ISD::STORE); 750 setTargetDAGCombine(ISD::ATOMIC_LOAD); 751 setTargetDAGCombine(ISD::ATOMIC_STORE); 752 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 753 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 754 setTargetDAGCombine(ISD::ATOMIC_SWAP); 755 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 756 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 757 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 758 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 759 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 760 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 761 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 762 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 763 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 764 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 765 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 766 767 setSchedulingPreference(Sched::RegPressure); 768 } 769 770 const GCNSubtarget *SITargetLowering::getSubtarget() const { 771 return Subtarget; 772 } 773 774 //===----------------------------------------------------------------------===// 775 // TargetLowering queries 776 //===----------------------------------------------------------------------===// 777 778 // v_mad_mix* support a conversion from f16 to f32. 779 // 780 // There is only one special case when denormals are enabled we don't currently, 781 // where this is OK to use. 782 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 783 EVT DestVT, EVT SrcVT) const { 784 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 785 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 786 DestVT.getScalarType() == MVT::f32 && 787 SrcVT.getScalarType() == MVT::f16 && 788 !hasFP32Denormals(DAG.getMachineFunction()); 789 } 790 791 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 792 // SI has some legal vector types, but no legal vector operations. Say no 793 // shuffles are legal in order to prefer scalarizing some vector operations. 794 return false; 795 } 796 797 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 798 CallingConv::ID CC, 799 EVT VT) const { 800 if (CC == CallingConv::AMDGPU_KERNEL) 801 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 802 803 if (VT.isVector()) { 804 EVT ScalarVT = VT.getScalarType(); 805 unsigned Size = ScalarVT.getSizeInBits(); 806 if (Size == 32) 807 return ScalarVT.getSimpleVT(); 808 809 if (Size > 32) 810 return MVT::i32; 811 812 if (Size == 16 && Subtarget->has16BitInsts()) 813 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 814 } else if (VT.getSizeInBits() > 32) 815 return MVT::i32; 816 817 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 818 } 819 820 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 821 CallingConv::ID CC, 822 EVT VT) const { 823 if (CC == CallingConv::AMDGPU_KERNEL) 824 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 825 826 if (VT.isVector()) { 827 unsigned NumElts = VT.getVectorNumElements(); 828 EVT ScalarVT = VT.getScalarType(); 829 unsigned Size = ScalarVT.getSizeInBits(); 830 831 if (Size == 32) 832 return NumElts; 833 834 if (Size > 32) 835 return NumElts * ((Size + 31) / 32); 836 837 if (Size == 16 && Subtarget->has16BitInsts()) 838 return (NumElts + 1) / 2; 839 } else if (VT.getSizeInBits() > 32) 840 return (VT.getSizeInBits() + 31) / 32; 841 842 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 843 } 844 845 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 846 LLVMContext &Context, CallingConv::ID CC, 847 EVT VT, EVT &IntermediateVT, 848 unsigned &NumIntermediates, MVT &RegisterVT) const { 849 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 850 unsigned NumElts = VT.getVectorNumElements(); 851 EVT ScalarVT = VT.getScalarType(); 852 unsigned Size = ScalarVT.getSizeInBits(); 853 if (Size == 32) { 854 RegisterVT = ScalarVT.getSimpleVT(); 855 IntermediateVT = RegisterVT; 856 NumIntermediates = NumElts; 857 return NumIntermediates; 858 } 859 860 if (Size > 32) { 861 RegisterVT = MVT::i32; 862 IntermediateVT = RegisterVT; 863 NumIntermediates = NumElts * ((Size + 31) / 32); 864 return NumIntermediates; 865 } 866 867 // FIXME: We should fix the ABI to be the same on targets without 16-bit 868 // support, but unless we can properly handle 3-vectors, it will be still be 869 // inconsistent. 870 if (Size == 16 && Subtarget->has16BitInsts()) { 871 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 872 IntermediateVT = RegisterVT; 873 NumIntermediates = (NumElts + 1) / 2; 874 return NumIntermediates; 875 } 876 } 877 878 return TargetLowering::getVectorTypeBreakdownForCallingConv( 879 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 880 } 881 882 static MVT memVTFromAggregate(Type *Ty) { 883 // Only limited forms of aggregate type currently expected. 884 assert(Ty->isStructTy() && "Expected struct type"); 885 886 887 Type *ElementType = nullptr; 888 unsigned NumElts; 889 if (Ty->getContainedType(0)->isVectorTy()) { 890 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 891 ElementType = VecComponent->getElementType(); 892 NumElts = VecComponent->getNumElements(); 893 } else { 894 ElementType = Ty->getContainedType(0); 895 NumElts = 1; 896 } 897 898 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 899 900 // Calculate the size of the memVT type from the aggregate 901 unsigned Pow2Elts = 0; 902 unsigned ElementSize; 903 switch (ElementType->getTypeID()) { 904 default: 905 llvm_unreachable("Unknown type!"); 906 case Type::IntegerTyID: 907 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 908 break; 909 case Type::HalfTyID: 910 ElementSize = 16; 911 break; 912 case Type::FloatTyID: 913 ElementSize = 32; 914 break; 915 } 916 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 917 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 918 919 return MVT::getVectorVT(MVT::getVT(ElementType, false), 920 Pow2Elts); 921 } 922 923 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 924 const CallInst &CI, 925 MachineFunction &MF, 926 unsigned IntrID) const { 927 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 928 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 929 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 930 (Intrinsic::ID)IntrID); 931 if (Attr.hasFnAttribute(Attribute::ReadNone)) 932 return false; 933 934 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 935 936 if (RsrcIntr->IsImage) { 937 Info.ptrVal = MFI->getImagePSV( 938 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 939 CI.getArgOperand(RsrcIntr->RsrcArg)); 940 Info.align.reset(); 941 } else { 942 Info.ptrVal = MFI->getBufferPSV( 943 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 944 CI.getArgOperand(RsrcIntr->RsrcArg)); 945 } 946 947 Info.flags = MachineMemOperand::MODereferenceable; 948 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 949 Info.opc = ISD::INTRINSIC_W_CHAIN; 950 Info.memVT = MVT::getVT(CI.getType(), true); 951 if (Info.memVT == MVT::Other) { 952 // Some intrinsics return an aggregate type - special case to work out 953 // the correct memVT 954 Info.memVT = memVTFromAggregate(CI.getType()); 955 } 956 Info.flags |= MachineMemOperand::MOLoad; 957 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 958 Info.opc = ISD::INTRINSIC_VOID; 959 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 960 Info.flags |= MachineMemOperand::MOStore; 961 } else { 962 // Atomic 963 Info.opc = ISD::INTRINSIC_W_CHAIN; 964 Info.memVT = MVT::getVT(CI.getType()); 965 Info.flags = MachineMemOperand::MOLoad | 966 MachineMemOperand::MOStore | 967 MachineMemOperand::MODereferenceable; 968 969 // XXX - Should this be volatile without known ordering? 970 Info.flags |= MachineMemOperand::MOVolatile; 971 } 972 return true; 973 } 974 975 switch (IntrID) { 976 case Intrinsic::amdgcn_atomic_inc: 977 case Intrinsic::amdgcn_atomic_dec: 978 case Intrinsic::amdgcn_ds_ordered_add: 979 case Intrinsic::amdgcn_ds_ordered_swap: 980 case Intrinsic::amdgcn_ds_fadd: 981 case Intrinsic::amdgcn_ds_fmin: 982 case Intrinsic::amdgcn_ds_fmax: { 983 Info.opc = ISD::INTRINSIC_W_CHAIN; 984 Info.memVT = MVT::getVT(CI.getType()); 985 Info.ptrVal = CI.getOperand(0); 986 Info.align.reset(); 987 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 988 989 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 990 if (!Vol->isZero()) 991 Info.flags |= MachineMemOperand::MOVolatile; 992 993 return true; 994 } 995 case Intrinsic::amdgcn_buffer_atomic_fadd: { 996 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 997 998 Info.opc = ISD::INTRINSIC_VOID; 999 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1000 Info.ptrVal = MFI->getBufferPSV( 1001 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1002 CI.getArgOperand(1)); 1003 Info.align.reset(); 1004 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1005 1006 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1007 if (!Vol || !Vol->isZero()) 1008 Info.flags |= MachineMemOperand::MOVolatile; 1009 1010 return true; 1011 } 1012 case Intrinsic::amdgcn_global_atomic_fadd: { 1013 Info.opc = ISD::INTRINSIC_VOID; 1014 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1015 ->getPointerElementType()); 1016 Info.ptrVal = CI.getOperand(0); 1017 Info.align.reset(); 1018 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1019 1020 return true; 1021 } 1022 case Intrinsic::amdgcn_ds_append: 1023 case Intrinsic::amdgcn_ds_consume: { 1024 Info.opc = ISD::INTRINSIC_W_CHAIN; 1025 Info.memVT = MVT::getVT(CI.getType()); 1026 Info.ptrVal = CI.getOperand(0); 1027 Info.align.reset(); 1028 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1029 1030 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1031 if (!Vol->isZero()) 1032 Info.flags |= MachineMemOperand::MOVolatile; 1033 1034 return true; 1035 } 1036 case Intrinsic::amdgcn_ds_gws_init: 1037 case Intrinsic::amdgcn_ds_gws_barrier: 1038 case Intrinsic::amdgcn_ds_gws_sema_v: 1039 case Intrinsic::amdgcn_ds_gws_sema_br: 1040 case Intrinsic::amdgcn_ds_gws_sema_p: 1041 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1042 Info.opc = ISD::INTRINSIC_VOID; 1043 1044 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1045 Info.ptrVal = 1046 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1047 1048 // This is an abstract access, but we need to specify a type and size. 1049 Info.memVT = MVT::i32; 1050 Info.size = 4; 1051 Info.align = Align(4); 1052 1053 Info.flags = MachineMemOperand::MOStore; 1054 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1055 Info.flags = MachineMemOperand::MOLoad; 1056 return true; 1057 } 1058 default: 1059 return false; 1060 } 1061 } 1062 1063 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1064 SmallVectorImpl<Value*> &Ops, 1065 Type *&AccessTy) const { 1066 switch (II->getIntrinsicID()) { 1067 case Intrinsic::amdgcn_atomic_inc: 1068 case Intrinsic::amdgcn_atomic_dec: 1069 case Intrinsic::amdgcn_ds_ordered_add: 1070 case Intrinsic::amdgcn_ds_ordered_swap: 1071 case Intrinsic::amdgcn_ds_fadd: 1072 case Intrinsic::amdgcn_ds_fmin: 1073 case Intrinsic::amdgcn_ds_fmax: { 1074 Value *Ptr = II->getArgOperand(0); 1075 AccessTy = II->getType(); 1076 Ops.push_back(Ptr); 1077 return true; 1078 } 1079 default: 1080 return false; 1081 } 1082 } 1083 1084 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1085 if (!Subtarget->hasFlatInstOffsets()) { 1086 // Flat instructions do not have offsets, and only have the register 1087 // address. 1088 return AM.BaseOffs == 0 && AM.Scale == 0; 1089 } 1090 1091 return AM.Scale == 0 && 1092 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1093 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1094 /*Signed=*/false)); 1095 } 1096 1097 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1098 if (Subtarget->hasFlatGlobalInsts()) 1099 return AM.Scale == 0 && 1100 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1101 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1102 /*Signed=*/true)); 1103 1104 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1105 // Assume the we will use FLAT for all global memory accesses 1106 // on VI. 1107 // FIXME: This assumption is currently wrong. On VI we still use 1108 // MUBUF instructions for the r + i addressing mode. As currently 1109 // implemented, the MUBUF instructions only work on buffer < 4GB. 1110 // It may be possible to support > 4GB buffers with MUBUF instructions, 1111 // by setting the stride value in the resource descriptor which would 1112 // increase the size limit to (stride * 4GB). However, this is risky, 1113 // because it has never been validated. 1114 return isLegalFlatAddressingMode(AM); 1115 } 1116 1117 return isLegalMUBUFAddressingMode(AM); 1118 } 1119 1120 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1121 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1122 // additionally can do r + r + i with addr64. 32-bit has more addressing 1123 // mode options. Depending on the resource constant, it can also do 1124 // (i64 r0) + (i32 r1) * (i14 i). 1125 // 1126 // Private arrays end up using a scratch buffer most of the time, so also 1127 // assume those use MUBUF instructions. Scratch loads / stores are currently 1128 // implemented as mubuf instructions with offen bit set, so slightly 1129 // different than the normal addr64. 1130 if (!isUInt<12>(AM.BaseOffs)) 1131 return false; 1132 1133 // FIXME: Since we can split immediate into soffset and immediate offset, 1134 // would it make sense to allow any immediate? 1135 1136 switch (AM.Scale) { 1137 case 0: // r + i or just i, depending on HasBaseReg. 1138 return true; 1139 case 1: 1140 return true; // We have r + r or r + i. 1141 case 2: 1142 if (AM.HasBaseReg) { 1143 // Reject 2 * r + r. 1144 return false; 1145 } 1146 1147 // Allow 2 * r as r + r 1148 // Or 2 * r + i is allowed as r + r + i. 1149 return true; 1150 default: // Don't allow n * r 1151 return false; 1152 } 1153 } 1154 1155 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1156 const AddrMode &AM, Type *Ty, 1157 unsigned AS, Instruction *I) const { 1158 // No global is ever allowed as a base. 1159 if (AM.BaseGV) 1160 return false; 1161 1162 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1163 return isLegalGlobalAddressingMode(AM); 1164 1165 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1166 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1167 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1168 // If the offset isn't a multiple of 4, it probably isn't going to be 1169 // correctly aligned. 1170 // FIXME: Can we get the real alignment here? 1171 if (AM.BaseOffs % 4 != 0) 1172 return isLegalMUBUFAddressingMode(AM); 1173 1174 // There are no SMRD extloads, so if we have to do a small type access we 1175 // will use a MUBUF load. 1176 // FIXME?: We also need to do this if unaligned, but we don't know the 1177 // alignment here. 1178 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1179 return isLegalGlobalAddressingMode(AM); 1180 1181 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1182 // SMRD instructions have an 8-bit, dword offset on SI. 1183 if (!isUInt<8>(AM.BaseOffs / 4)) 1184 return false; 1185 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1186 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1187 // in 8-bits, it can use a smaller encoding. 1188 if (!isUInt<32>(AM.BaseOffs / 4)) 1189 return false; 1190 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1191 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1192 if (!isUInt<20>(AM.BaseOffs)) 1193 return false; 1194 } else 1195 llvm_unreachable("unhandled generation"); 1196 1197 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1198 return true; 1199 1200 if (AM.Scale == 1 && AM.HasBaseReg) 1201 return true; 1202 1203 return false; 1204 1205 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1206 return isLegalMUBUFAddressingMode(AM); 1207 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1208 AS == AMDGPUAS::REGION_ADDRESS) { 1209 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1210 // field. 1211 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1212 // an 8-bit dword offset but we don't know the alignment here. 1213 if (!isUInt<16>(AM.BaseOffs)) 1214 return false; 1215 1216 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1217 return true; 1218 1219 if (AM.Scale == 1 && AM.HasBaseReg) 1220 return true; 1221 1222 return false; 1223 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1224 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1225 // For an unknown address space, this usually means that this is for some 1226 // reason being used for pure arithmetic, and not based on some addressing 1227 // computation. We don't have instructions that compute pointers with any 1228 // addressing modes, so treat them as having no offset like flat 1229 // instructions. 1230 return isLegalFlatAddressingMode(AM); 1231 } else { 1232 llvm_unreachable("unhandled address space"); 1233 } 1234 } 1235 1236 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1237 const SelectionDAG &DAG) const { 1238 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1239 return (MemVT.getSizeInBits() <= 4 * 32); 1240 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1241 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1242 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1243 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1244 return (MemVT.getSizeInBits() <= 2 * 32); 1245 } 1246 return true; 1247 } 1248 1249 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1250 unsigned Size, unsigned AddrSpace, unsigned Align, 1251 MachineMemOperand::Flags Flags, bool *IsFast) const { 1252 if (IsFast) 1253 *IsFast = false; 1254 1255 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1256 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1257 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1258 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1259 // with adjacent offsets. 1260 bool AlignedBy4 = (Align % 4 == 0); 1261 if (IsFast) 1262 *IsFast = AlignedBy4; 1263 1264 return AlignedBy4; 1265 } 1266 1267 // FIXME: We have to be conservative here and assume that flat operations 1268 // will access scratch. If we had access to the IR function, then we 1269 // could determine if any private memory was used in the function. 1270 if (!Subtarget->hasUnalignedScratchAccess() && 1271 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1272 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1273 bool AlignedBy4 = Align >= 4; 1274 if (IsFast) 1275 *IsFast = AlignedBy4; 1276 1277 return AlignedBy4; 1278 } 1279 1280 if (Subtarget->hasUnalignedBufferAccess()) { 1281 // If we have an uniform constant load, it still requires using a slow 1282 // buffer instruction if unaligned. 1283 if (IsFast) { 1284 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1285 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1286 (Align % 4 == 0) : true; 1287 } 1288 1289 return true; 1290 } 1291 1292 // Smaller than dword value must be aligned. 1293 if (Size < 32) 1294 return false; 1295 1296 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1297 // byte-address are ignored, thus forcing Dword alignment. 1298 // This applies to private, global, and constant memory. 1299 if (IsFast) 1300 *IsFast = true; 1301 1302 return Size >= 32 && Align >= 4; 1303 } 1304 1305 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1306 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1307 bool *IsFast) const { 1308 if (IsFast) 1309 *IsFast = false; 1310 1311 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1312 // which isn't a simple VT. 1313 // Until MVT is extended to handle this, simply check for the size and 1314 // rely on the condition below: allow accesses if the size is a multiple of 4. 1315 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1316 VT.getStoreSize() > 16)) { 1317 return false; 1318 } 1319 1320 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1321 Align, Flags, IsFast); 1322 } 1323 1324 EVT SITargetLowering::getOptimalMemOpType( 1325 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 1326 bool ZeroMemset, bool MemcpyStrSrc, 1327 const AttributeList &FuncAttributes) const { 1328 // FIXME: Should account for address space here. 1329 1330 // The default fallback uses the private pointer size as a guess for a type to 1331 // use. Make sure we switch these to 64-bit accesses. 1332 1333 if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global 1334 return MVT::v4i32; 1335 1336 if (Size >= 8 && DstAlign >= 4) 1337 return MVT::v2i32; 1338 1339 // Use the default. 1340 return MVT::Other; 1341 } 1342 1343 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1344 unsigned DestAS) const { 1345 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1346 } 1347 1348 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1349 const MemSDNode *MemNode = cast<MemSDNode>(N); 1350 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1351 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1352 return I && I->getMetadata("amdgpu.noclobber"); 1353 } 1354 1355 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1356 unsigned DestAS) const { 1357 // Flat -> private/local is a simple truncate. 1358 // Flat -> global is no-op 1359 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1360 return true; 1361 1362 return isNoopAddrSpaceCast(SrcAS, DestAS); 1363 } 1364 1365 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1366 const MemSDNode *MemNode = cast<MemSDNode>(N); 1367 1368 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1369 } 1370 1371 TargetLoweringBase::LegalizeTypeAction 1372 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1373 int NumElts = VT.getVectorNumElements(); 1374 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1375 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1376 return TargetLoweringBase::getPreferredVectorAction(VT); 1377 } 1378 1379 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1380 Type *Ty) const { 1381 // FIXME: Could be smarter if called for vector constants. 1382 return true; 1383 } 1384 1385 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1386 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1387 switch (Op) { 1388 case ISD::LOAD: 1389 case ISD::STORE: 1390 1391 // These operations are done with 32-bit instructions anyway. 1392 case ISD::AND: 1393 case ISD::OR: 1394 case ISD::XOR: 1395 case ISD::SELECT: 1396 // TODO: Extensions? 1397 return true; 1398 default: 1399 return false; 1400 } 1401 } 1402 1403 // SimplifySetCC uses this function to determine whether or not it should 1404 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1405 if (VT == MVT::i1 && Op == ISD::SETCC) 1406 return false; 1407 1408 return TargetLowering::isTypeDesirableForOp(Op, VT); 1409 } 1410 1411 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1412 const SDLoc &SL, 1413 SDValue Chain, 1414 uint64_t Offset) const { 1415 const DataLayout &DL = DAG.getDataLayout(); 1416 MachineFunction &MF = DAG.getMachineFunction(); 1417 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1418 1419 const ArgDescriptor *InputPtrReg; 1420 const TargetRegisterClass *RC; 1421 1422 std::tie(InputPtrReg, RC) 1423 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1424 1425 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1426 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1427 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1428 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1429 1430 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1431 } 1432 1433 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1434 const SDLoc &SL) const { 1435 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1436 FIRST_IMPLICIT); 1437 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1438 } 1439 1440 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1441 const SDLoc &SL, SDValue Val, 1442 bool Signed, 1443 const ISD::InputArg *Arg) const { 1444 // First, if it is a widened vector, narrow it. 1445 if (VT.isVector() && 1446 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1447 EVT NarrowedVT = 1448 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1449 VT.getVectorNumElements()); 1450 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1451 DAG.getConstant(0, SL, MVT::i32)); 1452 } 1453 1454 // Then convert the vector elements or scalar value. 1455 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1456 VT.bitsLT(MemVT)) { 1457 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1458 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1459 } 1460 1461 if (MemVT.isFloatingPoint()) 1462 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1463 else if (Signed) 1464 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1465 else 1466 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1467 1468 return Val; 1469 } 1470 1471 SDValue SITargetLowering::lowerKernargMemParameter( 1472 SelectionDAG &DAG, EVT VT, EVT MemVT, 1473 const SDLoc &SL, SDValue Chain, 1474 uint64_t Offset, unsigned Align, bool Signed, 1475 const ISD::InputArg *Arg) const { 1476 Type *Ty = MemVT.getTypeForEVT(*DAG.getContext()); 1477 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 1478 MachinePointerInfo PtrInfo(UndefValue::get(PtrTy)); 1479 1480 // Try to avoid using an extload by loading earlier than the argument address, 1481 // and extracting the relevant bits. The load should hopefully be merged with 1482 // the previous argument. 1483 if (MemVT.getStoreSize() < 4 && Align < 4) { 1484 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1485 int64_t AlignDownOffset = alignDown(Offset, 4); 1486 int64_t OffsetDiff = Offset - AlignDownOffset; 1487 1488 EVT IntVT = MemVT.changeTypeToInteger(); 1489 1490 // TODO: If we passed in the base kernel offset we could have a better 1491 // alignment than 4, but we don't really need it. 1492 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1493 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1494 MachineMemOperand::MODereferenceable | 1495 MachineMemOperand::MOInvariant); 1496 1497 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1498 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1499 1500 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1501 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1502 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1503 1504 1505 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1506 } 1507 1508 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1509 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1510 MachineMemOperand::MODereferenceable | 1511 MachineMemOperand::MOInvariant); 1512 1513 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1514 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1515 } 1516 1517 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1518 const SDLoc &SL, SDValue Chain, 1519 const ISD::InputArg &Arg) const { 1520 MachineFunction &MF = DAG.getMachineFunction(); 1521 MachineFrameInfo &MFI = MF.getFrameInfo(); 1522 1523 if (Arg.Flags.isByVal()) { 1524 unsigned Size = Arg.Flags.getByValSize(); 1525 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1526 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1527 } 1528 1529 unsigned ArgOffset = VA.getLocMemOffset(); 1530 unsigned ArgSize = VA.getValVT().getStoreSize(); 1531 1532 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1533 1534 // Create load nodes to retrieve arguments from the stack. 1535 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1536 SDValue ArgValue; 1537 1538 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1539 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1540 MVT MemVT = VA.getValVT(); 1541 1542 switch (VA.getLocInfo()) { 1543 default: 1544 break; 1545 case CCValAssign::BCvt: 1546 MemVT = VA.getLocVT(); 1547 break; 1548 case CCValAssign::SExt: 1549 ExtType = ISD::SEXTLOAD; 1550 break; 1551 case CCValAssign::ZExt: 1552 ExtType = ISD::ZEXTLOAD; 1553 break; 1554 case CCValAssign::AExt: 1555 ExtType = ISD::EXTLOAD; 1556 break; 1557 } 1558 1559 ArgValue = DAG.getExtLoad( 1560 ExtType, SL, VA.getLocVT(), Chain, FIN, 1561 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1562 MemVT); 1563 return ArgValue; 1564 } 1565 1566 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1567 const SIMachineFunctionInfo &MFI, 1568 EVT VT, 1569 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1570 const ArgDescriptor *Reg; 1571 const TargetRegisterClass *RC; 1572 1573 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1574 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1575 } 1576 1577 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1578 CallingConv::ID CallConv, 1579 ArrayRef<ISD::InputArg> Ins, 1580 BitVector &Skipped, 1581 FunctionType *FType, 1582 SIMachineFunctionInfo *Info) { 1583 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1584 const ISD::InputArg *Arg = &Ins[I]; 1585 1586 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1587 "vector type argument should have been split"); 1588 1589 // First check if it's a PS input addr. 1590 if (CallConv == CallingConv::AMDGPU_PS && 1591 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1592 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1593 1594 // Inconveniently only the first part of the split is marked as isSplit, 1595 // so skip to the end. We only want to increment PSInputNum once for the 1596 // entire split argument. 1597 if (Arg->Flags.isSplit()) { 1598 while (!Arg->Flags.isSplitEnd()) { 1599 assert((!Arg->VT.isVector() || 1600 Arg->VT.getScalarSizeInBits() == 16) && 1601 "unexpected vector split in ps argument type"); 1602 if (!SkipArg) 1603 Splits.push_back(*Arg); 1604 Arg = &Ins[++I]; 1605 } 1606 } 1607 1608 if (SkipArg) { 1609 // We can safely skip PS inputs. 1610 Skipped.set(Arg->getOrigArgIndex()); 1611 ++PSInputNum; 1612 continue; 1613 } 1614 1615 Info->markPSInputAllocated(PSInputNum); 1616 if (Arg->Used) 1617 Info->markPSInputEnabled(PSInputNum); 1618 1619 ++PSInputNum; 1620 } 1621 1622 Splits.push_back(*Arg); 1623 } 1624 } 1625 1626 // Allocate special inputs passed in VGPRs. 1627 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1628 MachineFunction &MF, 1629 const SIRegisterInfo &TRI, 1630 SIMachineFunctionInfo &Info) const { 1631 const LLT S32 = LLT::scalar(32); 1632 MachineRegisterInfo &MRI = MF.getRegInfo(); 1633 1634 if (Info.hasWorkItemIDX()) { 1635 Register Reg = AMDGPU::VGPR0; 1636 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1637 1638 CCInfo.AllocateReg(Reg); 1639 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1640 } 1641 1642 if (Info.hasWorkItemIDY()) { 1643 Register Reg = AMDGPU::VGPR1; 1644 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1645 1646 CCInfo.AllocateReg(Reg); 1647 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1648 } 1649 1650 if (Info.hasWorkItemIDZ()) { 1651 Register Reg = AMDGPU::VGPR2; 1652 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1653 1654 CCInfo.AllocateReg(Reg); 1655 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1656 } 1657 } 1658 1659 // Try to allocate a VGPR at the end of the argument list, or if no argument 1660 // VGPRs are left allocating a stack slot. 1661 // If \p Mask is is given it indicates bitfield position in the register. 1662 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1663 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1664 ArgDescriptor Arg = ArgDescriptor()) { 1665 if (Arg.isSet()) 1666 return ArgDescriptor::createArg(Arg, Mask); 1667 1668 ArrayRef<MCPhysReg> ArgVGPRs 1669 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1670 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1671 if (RegIdx == ArgVGPRs.size()) { 1672 // Spill to stack required. 1673 int64_t Offset = CCInfo.AllocateStack(4, 4); 1674 1675 return ArgDescriptor::createStack(Offset, Mask); 1676 } 1677 1678 unsigned Reg = ArgVGPRs[RegIdx]; 1679 Reg = CCInfo.AllocateReg(Reg); 1680 assert(Reg != AMDGPU::NoRegister); 1681 1682 MachineFunction &MF = CCInfo.getMachineFunction(); 1683 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1684 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1685 return ArgDescriptor::createRegister(Reg, Mask); 1686 } 1687 1688 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1689 const TargetRegisterClass *RC, 1690 unsigned NumArgRegs) { 1691 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1692 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1693 if (RegIdx == ArgSGPRs.size()) 1694 report_fatal_error("ran out of SGPRs for arguments"); 1695 1696 unsigned Reg = ArgSGPRs[RegIdx]; 1697 Reg = CCInfo.AllocateReg(Reg); 1698 assert(Reg != AMDGPU::NoRegister); 1699 1700 MachineFunction &MF = CCInfo.getMachineFunction(); 1701 MF.addLiveIn(Reg, RC); 1702 return ArgDescriptor::createRegister(Reg); 1703 } 1704 1705 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1706 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1707 } 1708 1709 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1710 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1711 } 1712 1713 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo, 1714 MachineFunction &MF, 1715 const SIRegisterInfo &TRI, 1716 SIMachineFunctionInfo &Info) const { 1717 const unsigned Mask = 0x3ff; 1718 ArgDescriptor Arg; 1719 1720 if (Info.hasWorkItemIDX()) { 1721 Arg = allocateVGPR32Input(CCInfo, Mask); 1722 Info.setWorkItemIDX(Arg); 1723 } 1724 1725 if (Info.hasWorkItemIDY()) { 1726 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1727 Info.setWorkItemIDY(Arg); 1728 } 1729 1730 if (Info.hasWorkItemIDZ()) 1731 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1732 } 1733 1734 void SITargetLowering::allocateSpecialInputSGPRs( 1735 CCState &CCInfo, 1736 MachineFunction &MF, 1737 const SIRegisterInfo &TRI, 1738 SIMachineFunctionInfo &Info) const { 1739 auto &ArgInfo = Info.getArgInfo(); 1740 1741 // TODO: Unify handling with private memory pointers. 1742 1743 if (Info.hasDispatchPtr()) 1744 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1745 1746 if (Info.hasQueuePtr()) 1747 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1748 1749 if (Info.hasKernargSegmentPtr()) 1750 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1751 1752 if (Info.hasDispatchID()) 1753 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1754 1755 // flat_scratch_init is not applicable for non-kernel functions. 1756 1757 if (Info.hasWorkGroupIDX()) 1758 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1759 1760 if (Info.hasWorkGroupIDY()) 1761 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1762 1763 if (Info.hasWorkGroupIDZ()) 1764 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1765 1766 if (Info.hasImplicitArgPtr()) 1767 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1768 } 1769 1770 // Allocate special inputs passed in user SGPRs. 1771 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1772 MachineFunction &MF, 1773 const SIRegisterInfo &TRI, 1774 SIMachineFunctionInfo &Info) const { 1775 if (Info.hasImplicitBufferPtr()) { 1776 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1777 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1778 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1779 } 1780 1781 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1782 if (Info.hasPrivateSegmentBuffer()) { 1783 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1784 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1785 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1786 } 1787 1788 if (Info.hasDispatchPtr()) { 1789 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1790 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1791 CCInfo.AllocateReg(DispatchPtrReg); 1792 } 1793 1794 if (Info.hasQueuePtr()) { 1795 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1796 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1797 CCInfo.AllocateReg(QueuePtrReg); 1798 } 1799 1800 if (Info.hasKernargSegmentPtr()) { 1801 MachineRegisterInfo &MRI = MF.getRegInfo(); 1802 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1803 CCInfo.AllocateReg(InputPtrReg); 1804 1805 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1806 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1807 } 1808 1809 if (Info.hasDispatchID()) { 1810 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1811 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1812 CCInfo.AllocateReg(DispatchIDReg); 1813 } 1814 1815 if (Info.hasFlatScratchInit()) { 1816 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1817 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1818 CCInfo.AllocateReg(FlatScratchInitReg); 1819 } 1820 1821 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1822 // these from the dispatch pointer. 1823 } 1824 1825 // Allocate special input registers that are initialized per-wave. 1826 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1827 MachineFunction &MF, 1828 SIMachineFunctionInfo &Info, 1829 CallingConv::ID CallConv, 1830 bool IsShader) const { 1831 if (Info.hasWorkGroupIDX()) { 1832 unsigned Reg = Info.addWorkGroupIDX(); 1833 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1834 CCInfo.AllocateReg(Reg); 1835 } 1836 1837 if (Info.hasWorkGroupIDY()) { 1838 unsigned Reg = Info.addWorkGroupIDY(); 1839 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1840 CCInfo.AllocateReg(Reg); 1841 } 1842 1843 if (Info.hasWorkGroupIDZ()) { 1844 unsigned Reg = Info.addWorkGroupIDZ(); 1845 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1846 CCInfo.AllocateReg(Reg); 1847 } 1848 1849 if (Info.hasWorkGroupInfo()) { 1850 unsigned Reg = Info.addWorkGroupInfo(); 1851 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1852 CCInfo.AllocateReg(Reg); 1853 } 1854 1855 if (Info.hasPrivateSegmentWaveByteOffset()) { 1856 // Scratch wave offset passed in system SGPR. 1857 unsigned PrivateSegmentWaveByteOffsetReg; 1858 1859 if (IsShader) { 1860 PrivateSegmentWaveByteOffsetReg = 1861 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1862 1863 // This is true if the scratch wave byte offset doesn't have a fixed 1864 // location. 1865 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1866 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1867 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1868 } 1869 } else 1870 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1871 1872 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1873 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1874 } 1875 } 1876 1877 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1878 MachineFunction &MF, 1879 const SIRegisterInfo &TRI, 1880 SIMachineFunctionInfo &Info) { 1881 // Now that we've figured out where the scratch register inputs are, see if 1882 // should reserve the arguments and use them directly. 1883 MachineFrameInfo &MFI = MF.getFrameInfo(); 1884 bool HasStackObjects = MFI.hasStackObjects(); 1885 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1886 1887 // Record that we know we have non-spill stack objects so we don't need to 1888 // check all stack objects later. 1889 if (HasStackObjects) 1890 Info.setHasNonSpillStackObjects(true); 1891 1892 // Everything live out of a block is spilled with fast regalloc, so it's 1893 // almost certain that spilling will be required. 1894 if (TM.getOptLevel() == CodeGenOpt::None) 1895 HasStackObjects = true; 1896 1897 // For now assume stack access is needed in any callee functions, so we need 1898 // the scratch registers to pass in. 1899 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1900 1901 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1902 // If we have stack objects, we unquestionably need the private buffer 1903 // resource. For the Code Object V2 ABI, this will be the first 4 user 1904 // SGPR inputs. We can reserve those and use them directly. 1905 1906 Register PrivateSegmentBufferReg = 1907 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1908 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1909 } else { 1910 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1911 // We tentatively reserve the last registers (skipping the last registers 1912 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1913 // we'll replace these with the ones immediately after those which were 1914 // really allocated. In the prologue copies will be inserted from the 1915 // argument to these reserved registers. 1916 1917 // Without HSA, relocations are used for the scratch pointer and the 1918 // buffer resource setup is always inserted in the prologue. Scratch wave 1919 // offset is still in an input SGPR. 1920 Info.setScratchRSrcReg(ReservedBufferReg); 1921 } 1922 1923 // hasFP should be accurate for kernels even before the frame is finalized. 1924 if (ST.getFrameLowering()->hasFP(MF)) { 1925 MachineRegisterInfo &MRI = MF.getRegInfo(); 1926 1927 // Try to use s32 as the SP, but move it if it would interfere with input 1928 // arguments. This won't work with calls though. 1929 // 1930 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1931 // registers. 1932 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1933 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1934 } else { 1935 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1936 1937 if (MFI.hasCalls()) 1938 report_fatal_error("call in graphics shader with too many input SGPRs"); 1939 1940 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1941 if (!MRI.isLiveIn(Reg)) { 1942 Info.setStackPtrOffsetReg(Reg); 1943 break; 1944 } 1945 } 1946 1947 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1948 report_fatal_error("failed to find register for SP"); 1949 } 1950 1951 if (MFI.hasCalls()) { 1952 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1953 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1954 } else { 1955 unsigned ReservedOffsetReg = 1956 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1957 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1958 Info.setFrameOffsetReg(ReservedOffsetReg); 1959 } 1960 } else if (RequiresStackAccess) { 1961 assert(!MFI.hasCalls()); 1962 // We know there are accesses and they will be done relative to SP, so just 1963 // pin it to the input. 1964 // 1965 // FIXME: Should not do this if inline asm is reading/writing these 1966 // registers. 1967 Register PreloadedSP = Info.getPreloadedReg( 1968 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1969 1970 Info.setStackPtrOffsetReg(PreloadedSP); 1971 Info.setScratchWaveOffsetReg(PreloadedSP); 1972 Info.setFrameOffsetReg(PreloadedSP); 1973 } else { 1974 assert(!MFI.hasCalls()); 1975 1976 // There may not be stack access at all. There may still be spills, or 1977 // access of a constant pointer (in which cases an extra copy will be 1978 // emitted in the prolog). 1979 unsigned ReservedOffsetReg 1980 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1981 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1982 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1983 Info.setFrameOffsetReg(ReservedOffsetReg); 1984 } 1985 } 1986 1987 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1988 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1989 return !Info->isEntryFunction(); 1990 } 1991 1992 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1993 1994 } 1995 1996 void SITargetLowering::insertCopiesSplitCSR( 1997 MachineBasicBlock *Entry, 1998 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1999 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2000 2001 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2002 if (!IStart) 2003 return; 2004 2005 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2006 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2007 MachineBasicBlock::iterator MBBI = Entry->begin(); 2008 for (const MCPhysReg *I = IStart; *I; ++I) { 2009 const TargetRegisterClass *RC = nullptr; 2010 if (AMDGPU::SReg_64RegClass.contains(*I)) 2011 RC = &AMDGPU::SGPR_64RegClass; 2012 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2013 RC = &AMDGPU::SGPR_32RegClass; 2014 else 2015 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2016 2017 Register NewVR = MRI->createVirtualRegister(RC); 2018 // Create copy from CSR to a virtual register. 2019 Entry->addLiveIn(*I); 2020 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2021 .addReg(*I); 2022 2023 // Insert the copy-back instructions right before the terminator. 2024 for (auto *Exit : Exits) 2025 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2026 TII->get(TargetOpcode::COPY), *I) 2027 .addReg(NewVR); 2028 } 2029 } 2030 2031 SDValue SITargetLowering::LowerFormalArguments( 2032 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2033 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2034 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2035 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2036 2037 MachineFunction &MF = DAG.getMachineFunction(); 2038 const Function &Fn = MF.getFunction(); 2039 FunctionType *FType = MF.getFunction().getFunctionType(); 2040 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2041 2042 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2043 DiagnosticInfoUnsupported NoGraphicsHSA( 2044 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2045 DAG.getContext()->diagnose(NoGraphicsHSA); 2046 return DAG.getEntryNode(); 2047 } 2048 2049 SmallVector<ISD::InputArg, 16> Splits; 2050 SmallVector<CCValAssign, 16> ArgLocs; 2051 BitVector Skipped(Ins.size()); 2052 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2053 *DAG.getContext()); 2054 2055 bool IsShader = AMDGPU::isShader(CallConv); 2056 bool IsKernel = AMDGPU::isKernel(CallConv); 2057 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2058 2059 if (IsShader) { 2060 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2061 2062 // At least one interpolation mode must be enabled or else the GPU will 2063 // hang. 2064 // 2065 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2066 // set PSInputAddr, the user wants to enable some bits after the compilation 2067 // based on run-time states. Since we can't know what the final PSInputEna 2068 // will look like, so we shouldn't do anything here and the user should take 2069 // responsibility for the correct programming. 2070 // 2071 // Otherwise, the following restrictions apply: 2072 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2073 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2074 // enabled too. 2075 if (CallConv == CallingConv::AMDGPU_PS) { 2076 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2077 ((Info->getPSInputAddr() & 0xF) == 0 && 2078 Info->isPSInputAllocated(11))) { 2079 CCInfo.AllocateReg(AMDGPU::VGPR0); 2080 CCInfo.AllocateReg(AMDGPU::VGPR1); 2081 Info->markPSInputAllocated(0); 2082 Info->markPSInputEnabled(0); 2083 } 2084 if (Subtarget->isAmdPalOS()) { 2085 // For isAmdPalOS, the user does not enable some bits after compilation 2086 // based on run-time states; the register values being generated here are 2087 // the final ones set in hardware. Therefore we need to apply the 2088 // workaround to PSInputAddr and PSInputEnable together. (The case where 2089 // a bit is set in PSInputAddr but not PSInputEnable is where the 2090 // frontend set up an input arg for a particular interpolation mode, but 2091 // nothing uses that input arg. Really we should have an earlier pass 2092 // that removes such an arg.) 2093 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2094 if ((PsInputBits & 0x7F) == 0 || 2095 ((PsInputBits & 0xF) == 0 && 2096 (PsInputBits >> 11 & 1))) 2097 Info->markPSInputEnabled( 2098 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2099 } 2100 } 2101 2102 assert(!Info->hasDispatchPtr() && 2103 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2104 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2105 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2106 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2107 !Info->hasWorkItemIDZ()); 2108 } else if (IsKernel) { 2109 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2110 } else { 2111 Splits.append(Ins.begin(), Ins.end()); 2112 } 2113 2114 if (IsEntryFunc) { 2115 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2116 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2117 } 2118 2119 if (IsKernel) { 2120 analyzeFormalArgumentsCompute(CCInfo, Ins); 2121 } else { 2122 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2123 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2124 } 2125 2126 SmallVector<SDValue, 16> Chains; 2127 2128 // FIXME: This is the minimum kernel argument alignment. We should improve 2129 // this to the maximum alignment of the arguments. 2130 // 2131 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2132 // kern arg offset. 2133 const unsigned KernelArgBaseAlign = 16; 2134 2135 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2136 const ISD::InputArg &Arg = Ins[i]; 2137 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2138 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2139 continue; 2140 } 2141 2142 CCValAssign &VA = ArgLocs[ArgIdx++]; 2143 MVT VT = VA.getLocVT(); 2144 2145 if (IsEntryFunc && VA.isMemLoc()) { 2146 VT = Ins[i].VT; 2147 EVT MemVT = VA.getLocVT(); 2148 2149 const uint64_t Offset = VA.getLocMemOffset(); 2150 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2151 2152 SDValue Arg = lowerKernargMemParameter( 2153 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2154 Chains.push_back(Arg.getValue(1)); 2155 2156 auto *ParamTy = 2157 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2158 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2159 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2160 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2161 // On SI local pointers are just offsets into LDS, so they are always 2162 // less than 16-bits. On CI and newer they could potentially be 2163 // real pointers, so we can't guarantee their size. 2164 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2165 DAG.getValueType(MVT::i16)); 2166 } 2167 2168 InVals.push_back(Arg); 2169 continue; 2170 } else if (!IsEntryFunc && VA.isMemLoc()) { 2171 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2172 InVals.push_back(Val); 2173 if (!Arg.Flags.isByVal()) 2174 Chains.push_back(Val.getValue(1)); 2175 continue; 2176 } 2177 2178 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2179 2180 Register Reg = VA.getLocReg(); 2181 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2182 EVT ValVT = VA.getValVT(); 2183 2184 Reg = MF.addLiveIn(Reg, RC); 2185 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2186 2187 if (Arg.Flags.isSRet()) { 2188 // The return object should be reasonably addressable. 2189 2190 // FIXME: This helps when the return is a real sret. If it is a 2191 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2192 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2193 unsigned NumBits 2194 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2195 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2196 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2197 } 2198 2199 // If this is an 8 or 16-bit value, it is really passed promoted 2200 // to 32 bits. Insert an assert[sz]ext to capture this, then 2201 // truncate to the right size. 2202 switch (VA.getLocInfo()) { 2203 case CCValAssign::Full: 2204 break; 2205 case CCValAssign::BCvt: 2206 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2207 break; 2208 case CCValAssign::SExt: 2209 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2210 DAG.getValueType(ValVT)); 2211 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2212 break; 2213 case CCValAssign::ZExt: 2214 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2215 DAG.getValueType(ValVT)); 2216 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2217 break; 2218 case CCValAssign::AExt: 2219 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2220 break; 2221 default: 2222 llvm_unreachable("Unknown loc info!"); 2223 } 2224 2225 InVals.push_back(Val); 2226 } 2227 2228 if (!IsEntryFunc) { 2229 // Special inputs come after user arguments. 2230 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2231 } 2232 2233 // Start adding system SGPRs. 2234 if (IsEntryFunc) { 2235 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2236 } else { 2237 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2238 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2239 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2240 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2241 } 2242 2243 auto &ArgUsageInfo = 2244 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2245 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2246 2247 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2248 Info->setBytesInStackArgArea(StackArgSize); 2249 2250 return Chains.empty() ? Chain : 2251 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2252 } 2253 2254 // TODO: If return values can't fit in registers, we should return as many as 2255 // possible in registers before passing on stack. 2256 bool SITargetLowering::CanLowerReturn( 2257 CallingConv::ID CallConv, 2258 MachineFunction &MF, bool IsVarArg, 2259 const SmallVectorImpl<ISD::OutputArg> &Outs, 2260 LLVMContext &Context) const { 2261 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2262 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2263 // for shaders. Vector types should be explicitly handled by CC. 2264 if (AMDGPU::isEntryFunctionCC(CallConv)) 2265 return true; 2266 2267 SmallVector<CCValAssign, 16> RVLocs; 2268 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2269 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2270 } 2271 2272 SDValue 2273 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2274 bool isVarArg, 2275 const SmallVectorImpl<ISD::OutputArg> &Outs, 2276 const SmallVectorImpl<SDValue> &OutVals, 2277 const SDLoc &DL, SelectionDAG &DAG) const { 2278 MachineFunction &MF = DAG.getMachineFunction(); 2279 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2280 2281 if (AMDGPU::isKernel(CallConv)) { 2282 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2283 OutVals, DL, DAG); 2284 } 2285 2286 bool IsShader = AMDGPU::isShader(CallConv); 2287 2288 Info->setIfReturnsVoid(Outs.empty()); 2289 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2290 2291 // CCValAssign - represent the assignment of the return value to a location. 2292 SmallVector<CCValAssign, 48> RVLocs; 2293 SmallVector<ISD::OutputArg, 48> Splits; 2294 2295 // CCState - Info about the registers and stack slots. 2296 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2297 *DAG.getContext()); 2298 2299 // Analyze outgoing return values. 2300 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2301 2302 SDValue Flag; 2303 SmallVector<SDValue, 48> RetOps; 2304 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2305 2306 // Add return address for callable functions. 2307 if (!Info->isEntryFunction()) { 2308 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2309 SDValue ReturnAddrReg = CreateLiveInRegister( 2310 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2311 2312 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2313 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2314 MVT::i64); 2315 Chain = 2316 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2317 Flag = Chain.getValue(1); 2318 RetOps.push_back(ReturnAddrVirtualReg); 2319 } 2320 2321 // Copy the result values into the output registers. 2322 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2323 ++I, ++RealRVLocIdx) { 2324 CCValAssign &VA = RVLocs[I]; 2325 assert(VA.isRegLoc() && "Can only return in registers!"); 2326 // TODO: Partially return in registers if return values don't fit. 2327 SDValue Arg = OutVals[RealRVLocIdx]; 2328 2329 // Copied from other backends. 2330 switch (VA.getLocInfo()) { 2331 case CCValAssign::Full: 2332 break; 2333 case CCValAssign::BCvt: 2334 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2335 break; 2336 case CCValAssign::SExt: 2337 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2338 break; 2339 case CCValAssign::ZExt: 2340 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2341 break; 2342 case CCValAssign::AExt: 2343 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2344 break; 2345 default: 2346 llvm_unreachable("Unknown loc info!"); 2347 } 2348 2349 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2350 Flag = Chain.getValue(1); 2351 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2352 } 2353 2354 // FIXME: Does sret work properly? 2355 if (!Info->isEntryFunction()) { 2356 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2357 const MCPhysReg *I = 2358 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2359 if (I) { 2360 for (; *I; ++I) { 2361 if (AMDGPU::SReg_64RegClass.contains(*I)) 2362 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2363 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2364 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2365 else 2366 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2367 } 2368 } 2369 } 2370 2371 // Update chain and glue. 2372 RetOps[0] = Chain; 2373 if (Flag.getNode()) 2374 RetOps.push_back(Flag); 2375 2376 unsigned Opc = AMDGPUISD::ENDPGM; 2377 if (!IsWaveEnd) 2378 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2379 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2380 } 2381 2382 SDValue SITargetLowering::LowerCallResult( 2383 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2384 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2385 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2386 SDValue ThisVal) const { 2387 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2388 2389 // Assign locations to each value returned by this call. 2390 SmallVector<CCValAssign, 16> RVLocs; 2391 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2392 *DAG.getContext()); 2393 CCInfo.AnalyzeCallResult(Ins, RetCC); 2394 2395 // Copy all of the result registers out of their specified physreg. 2396 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2397 CCValAssign VA = RVLocs[i]; 2398 SDValue Val; 2399 2400 if (VA.isRegLoc()) { 2401 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2402 Chain = Val.getValue(1); 2403 InFlag = Val.getValue(2); 2404 } else if (VA.isMemLoc()) { 2405 report_fatal_error("TODO: return values in memory"); 2406 } else 2407 llvm_unreachable("unknown argument location type"); 2408 2409 switch (VA.getLocInfo()) { 2410 case CCValAssign::Full: 2411 break; 2412 case CCValAssign::BCvt: 2413 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2414 break; 2415 case CCValAssign::ZExt: 2416 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2417 DAG.getValueType(VA.getValVT())); 2418 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2419 break; 2420 case CCValAssign::SExt: 2421 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2422 DAG.getValueType(VA.getValVT())); 2423 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2424 break; 2425 case CCValAssign::AExt: 2426 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2427 break; 2428 default: 2429 llvm_unreachable("Unknown loc info!"); 2430 } 2431 2432 InVals.push_back(Val); 2433 } 2434 2435 return Chain; 2436 } 2437 2438 // Add code to pass special inputs required depending on used features separate 2439 // from the explicit user arguments present in the IR. 2440 void SITargetLowering::passSpecialInputs( 2441 CallLoweringInfo &CLI, 2442 CCState &CCInfo, 2443 const SIMachineFunctionInfo &Info, 2444 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2445 SmallVectorImpl<SDValue> &MemOpChains, 2446 SDValue Chain) const { 2447 // If we don't have a call site, this was a call inserted by 2448 // legalization. These can never use special inputs. 2449 if (!CLI.CS) 2450 return; 2451 2452 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2453 assert(CalleeFunc); 2454 2455 SelectionDAG &DAG = CLI.DAG; 2456 const SDLoc &DL = CLI.DL; 2457 2458 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2459 2460 auto &ArgUsageInfo = 2461 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2462 const AMDGPUFunctionArgInfo &CalleeArgInfo 2463 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2464 2465 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2466 2467 // TODO: Unify with private memory register handling. This is complicated by 2468 // the fact that at least in kernels, the input argument is not necessarily 2469 // in the same location as the input. 2470 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2471 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2472 AMDGPUFunctionArgInfo::QUEUE_PTR, 2473 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2474 AMDGPUFunctionArgInfo::DISPATCH_ID, 2475 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2476 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2477 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2478 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2479 }; 2480 2481 for (auto InputID : InputRegs) { 2482 const ArgDescriptor *OutgoingArg; 2483 const TargetRegisterClass *ArgRC; 2484 2485 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2486 if (!OutgoingArg) 2487 continue; 2488 2489 const ArgDescriptor *IncomingArg; 2490 const TargetRegisterClass *IncomingArgRC; 2491 std::tie(IncomingArg, IncomingArgRC) 2492 = CallerArgInfo.getPreloadedValue(InputID); 2493 assert(IncomingArgRC == ArgRC); 2494 2495 // All special arguments are ints for now. 2496 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2497 SDValue InputReg; 2498 2499 if (IncomingArg) { 2500 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2501 } else { 2502 // The implicit arg ptr is special because it doesn't have a corresponding 2503 // input for kernels, and is computed from the kernarg segment pointer. 2504 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2505 InputReg = getImplicitArgPtr(DAG, DL); 2506 } 2507 2508 if (OutgoingArg->isRegister()) { 2509 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2510 } else { 2511 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2512 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2513 SpecialArgOffset); 2514 MemOpChains.push_back(ArgStore); 2515 } 2516 } 2517 2518 // Pack workitem IDs into a single register or pass it as is if already 2519 // packed. 2520 const ArgDescriptor *OutgoingArg; 2521 const TargetRegisterClass *ArgRC; 2522 2523 std::tie(OutgoingArg, ArgRC) = 2524 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2525 if (!OutgoingArg) 2526 std::tie(OutgoingArg, ArgRC) = 2527 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2528 if (!OutgoingArg) 2529 std::tie(OutgoingArg, ArgRC) = 2530 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2531 if (!OutgoingArg) 2532 return; 2533 2534 const ArgDescriptor *IncomingArgX 2535 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2536 const ArgDescriptor *IncomingArgY 2537 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2538 const ArgDescriptor *IncomingArgZ 2539 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2540 2541 SDValue InputReg; 2542 SDLoc SL; 2543 2544 // If incoming ids are not packed we need to pack them. 2545 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2546 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2547 2548 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2549 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2550 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2551 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2552 InputReg = InputReg.getNode() ? 2553 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2554 } 2555 2556 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2557 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2558 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2559 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2560 InputReg = InputReg.getNode() ? 2561 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2562 } 2563 2564 if (!InputReg.getNode()) { 2565 // Workitem ids are already packed, any of present incoming arguments 2566 // will carry all required fields. 2567 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2568 IncomingArgX ? *IncomingArgX : 2569 IncomingArgY ? *IncomingArgY : 2570 *IncomingArgZ, ~0u); 2571 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2572 } 2573 2574 if (OutgoingArg->isRegister()) { 2575 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2576 } else { 2577 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2578 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2579 SpecialArgOffset); 2580 MemOpChains.push_back(ArgStore); 2581 } 2582 } 2583 2584 static bool canGuaranteeTCO(CallingConv::ID CC) { 2585 return CC == CallingConv::Fast; 2586 } 2587 2588 /// Return true if we might ever do TCO for calls with this calling convention. 2589 static bool mayTailCallThisCC(CallingConv::ID CC) { 2590 switch (CC) { 2591 case CallingConv::C: 2592 return true; 2593 default: 2594 return canGuaranteeTCO(CC); 2595 } 2596 } 2597 2598 bool SITargetLowering::isEligibleForTailCallOptimization( 2599 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2600 const SmallVectorImpl<ISD::OutputArg> &Outs, 2601 const SmallVectorImpl<SDValue> &OutVals, 2602 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2603 if (!mayTailCallThisCC(CalleeCC)) 2604 return false; 2605 2606 MachineFunction &MF = DAG.getMachineFunction(); 2607 const Function &CallerF = MF.getFunction(); 2608 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2609 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2610 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2611 2612 // Kernels aren't callable, and don't have a live in return address so it 2613 // doesn't make sense to do a tail call with entry functions. 2614 if (!CallerPreserved) 2615 return false; 2616 2617 bool CCMatch = CallerCC == CalleeCC; 2618 2619 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2620 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2621 return true; 2622 return false; 2623 } 2624 2625 // TODO: Can we handle var args? 2626 if (IsVarArg) 2627 return false; 2628 2629 for (const Argument &Arg : CallerF.args()) { 2630 if (Arg.hasByValAttr()) 2631 return false; 2632 } 2633 2634 LLVMContext &Ctx = *DAG.getContext(); 2635 2636 // Check that the call results are passed in the same way. 2637 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2638 CCAssignFnForCall(CalleeCC, IsVarArg), 2639 CCAssignFnForCall(CallerCC, IsVarArg))) 2640 return false; 2641 2642 // The callee has to preserve all registers the caller needs to preserve. 2643 if (!CCMatch) { 2644 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2645 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2646 return false; 2647 } 2648 2649 // Nothing more to check if the callee is taking no arguments. 2650 if (Outs.empty()) 2651 return true; 2652 2653 SmallVector<CCValAssign, 16> ArgLocs; 2654 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2655 2656 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2657 2658 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2659 // If the stack arguments for this call do not fit into our own save area then 2660 // the call cannot be made tail. 2661 // TODO: Is this really necessary? 2662 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2663 return false; 2664 2665 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2666 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2667 } 2668 2669 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2670 if (!CI->isTailCall()) 2671 return false; 2672 2673 const Function *ParentFn = CI->getParent()->getParent(); 2674 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2675 return false; 2676 2677 auto Attr = ParentFn->getFnAttribute("disable-tail-calls"); 2678 return (Attr.getValueAsString() != "true"); 2679 } 2680 2681 // The wave scratch offset register is used as the global base pointer. 2682 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2683 SmallVectorImpl<SDValue> &InVals) const { 2684 SelectionDAG &DAG = CLI.DAG; 2685 const SDLoc &DL = CLI.DL; 2686 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2687 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2688 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2689 SDValue Chain = CLI.Chain; 2690 SDValue Callee = CLI.Callee; 2691 bool &IsTailCall = CLI.IsTailCall; 2692 CallingConv::ID CallConv = CLI.CallConv; 2693 bool IsVarArg = CLI.IsVarArg; 2694 bool IsSibCall = false; 2695 bool IsThisReturn = false; 2696 MachineFunction &MF = DAG.getMachineFunction(); 2697 2698 if (Callee.isUndef() || isNullConstant(Callee)) { 2699 if (!CLI.IsTailCall) { 2700 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2701 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2702 } 2703 2704 return Chain; 2705 } 2706 2707 if (IsVarArg) { 2708 return lowerUnhandledCall(CLI, InVals, 2709 "unsupported call to variadic function "); 2710 } 2711 2712 if (!CLI.CS.getInstruction()) 2713 report_fatal_error("unsupported libcall legalization"); 2714 2715 if (!CLI.CS.getCalledFunction()) { 2716 return lowerUnhandledCall(CLI, InVals, 2717 "unsupported indirect call to function "); 2718 } 2719 2720 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2721 return lowerUnhandledCall(CLI, InVals, 2722 "unsupported required tail call to function "); 2723 } 2724 2725 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2726 // Note the issue is with the CC of the calling function, not of the call 2727 // itself. 2728 return lowerUnhandledCall(CLI, InVals, 2729 "unsupported call from graphics shader of function "); 2730 } 2731 2732 if (IsTailCall) { 2733 IsTailCall = isEligibleForTailCallOptimization( 2734 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2735 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2736 report_fatal_error("failed to perform tail call elimination on a call " 2737 "site marked musttail"); 2738 } 2739 2740 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2741 2742 // A sibling call is one where we're under the usual C ABI and not planning 2743 // to change that but can still do a tail call: 2744 if (!TailCallOpt && IsTailCall) 2745 IsSibCall = true; 2746 2747 if (IsTailCall) 2748 ++NumTailCalls; 2749 } 2750 2751 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2752 2753 // Analyze operands of the call, assigning locations to each operand. 2754 SmallVector<CCValAssign, 16> ArgLocs; 2755 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2756 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2757 2758 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2759 2760 // Get a count of how many bytes are to be pushed on the stack. 2761 unsigned NumBytes = CCInfo.getNextStackOffset(); 2762 2763 if (IsSibCall) { 2764 // Since we're not changing the ABI to make this a tail call, the memory 2765 // operands are already available in the caller's incoming argument space. 2766 NumBytes = 0; 2767 } 2768 2769 // FPDiff is the byte offset of the call's argument area from the callee's. 2770 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2771 // by this amount for a tail call. In a sibling call it must be 0 because the 2772 // caller will deallocate the entire stack and the callee still expects its 2773 // arguments to begin at SP+0. Completely unused for non-tail calls. 2774 int32_t FPDiff = 0; 2775 MachineFrameInfo &MFI = MF.getFrameInfo(); 2776 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2777 2778 // Adjust the stack pointer for the new arguments... 2779 // These operations are automatically eliminated by the prolog/epilog pass 2780 if (!IsSibCall) { 2781 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2782 2783 SmallVector<SDValue, 4> CopyFromChains; 2784 2785 // In the HSA case, this should be an identity copy. 2786 SDValue ScratchRSrcReg 2787 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2788 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2789 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2790 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2791 } 2792 2793 SmallVector<SDValue, 8> MemOpChains; 2794 MVT PtrVT = MVT::i32; 2795 2796 // Walk the register/memloc assignments, inserting copies/loads. 2797 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 2798 ++i, ++realArgIdx) { 2799 CCValAssign &VA = ArgLocs[i]; 2800 SDValue Arg = OutVals[realArgIdx]; 2801 2802 // Promote the value if needed. 2803 switch (VA.getLocInfo()) { 2804 case CCValAssign::Full: 2805 break; 2806 case CCValAssign::BCvt: 2807 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2808 break; 2809 case CCValAssign::ZExt: 2810 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2811 break; 2812 case CCValAssign::SExt: 2813 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2814 break; 2815 case CCValAssign::AExt: 2816 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2817 break; 2818 case CCValAssign::FPExt: 2819 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2820 break; 2821 default: 2822 llvm_unreachable("Unknown loc info!"); 2823 } 2824 2825 if (VA.isRegLoc()) { 2826 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2827 } else { 2828 assert(VA.isMemLoc()); 2829 2830 SDValue DstAddr; 2831 MachinePointerInfo DstInfo; 2832 2833 unsigned LocMemOffset = VA.getLocMemOffset(); 2834 int32_t Offset = LocMemOffset; 2835 2836 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2837 MaybeAlign Alignment; 2838 2839 if (IsTailCall) { 2840 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 2841 unsigned OpSize = Flags.isByVal() ? 2842 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2843 2844 // FIXME: We can have better than the minimum byval required alignment. 2845 Alignment = 2846 Flags.isByVal() 2847 ? MaybeAlign(Flags.getByValAlign()) 2848 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2849 2850 Offset = Offset + FPDiff; 2851 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2852 2853 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2854 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2855 2856 // Make sure any stack arguments overlapping with where we're storing 2857 // are loaded before this eventual operation. Otherwise they'll be 2858 // clobbered. 2859 2860 // FIXME: Why is this really necessary? This seems to just result in a 2861 // lot of code to copy the stack and write them back to the same 2862 // locations, which are supposed to be immutable? 2863 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2864 } else { 2865 DstAddr = PtrOff; 2866 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2867 Alignment = 2868 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2869 } 2870 2871 if (Outs[i].Flags.isByVal()) { 2872 SDValue SizeNode = 2873 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2874 SDValue Cpy = DAG.getMemcpy( 2875 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 2876 /*isVol = */ false, /*AlwaysInline = */ true, 2877 /*isTailCall = */ false, DstInfo, 2878 MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy( 2879 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS)))); 2880 2881 MemOpChains.push_back(Cpy); 2882 } else { 2883 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2884 Alignment ? Alignment->value() : 0); 2885 MemOpChains.push_back(Store); 2886 } 2887 } 2888 } 2889 2890 // Copy special input registers after user input arguments. 2891 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2892 2893 if (!MemOpChains.empty()) 2894 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2895 2896 // Build a sequence of copy-to-reg nodes chained together with token chain 2897 // and flag operands which copy the outgoing args into the appropriate regs. 2898 SDValue InFlag; 2899 for (auto &RegToPass : RegsToPass) { 2900 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2901 RegToPass.second, InFlag); 2902 InFlag = Chain.getValue(1); 2903 } 2904 2905 2906 SDValue PhysReturnAddrReg; 2907 if (IsTailCall) { 2908 // Since the return is being combined with the call, we need to pass on the 2909 // return address. 2910 2911 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2912 SDValue ReturnAddrReg = CreateLiveInRegister( 2913 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2914 2915 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2916 MVT::i64); 2917 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2918 InFlag = Chain.getValue(1); 2919 } 2920 2921 // We don't usually want to end the call-sequence here because we would tidy 2922 // the frame up *after* the call, however in the ABI-changing tail-call case 2923 // we've carefully laid out the parameters so that when sp is reset they'll be 2924 // in the correct location. 2925 if (IsTailCall && !IsSibCall) { 2926 Chain = DAG.getCALLSEQ_END(Chain, 2927 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2928 DAG.getTargetConstant(0, DL, MVT::i32), 2929 InFlag, DL); 2930 InFlag = Chain.getValue(1); 2931 } 2932 2933 std::vector<SDValue> Ops; 2934 Ops.push_back(Chain); 2935 Ops.push_back(Callee); 2936 // Add a redundant copy of the callee global which will not be legalized, as 2937 // we need direct access to the callee later. 2938 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2939 const GlobalValue *GV = GSD->getGlobal(); 2940 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2941 2942 if (IsTailCall) { 2943 // Each tail call may have to adjust the stack by a different amount, so 2944 // this information must travel along with the operation for eventual 2945 // consumption by emitEpilogue. 2946 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2947 2948 Ops.push_back(PhysReturnAddrReg); 2949 } 2950 2951 // Add argument registers to the end of the list so that they are known live 2952 // into the call. 2953 for (auto &RegToPass : RegsToPass) { 2954 Ops.push_back(DAG.getRegister(RegToPass.first, 2955 RegToPass.second.getValueType())); 2956 } 2957 2958 // Add a register mask operand representing the call-preserved registers. 2959 2960 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2961 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2962 assert(Mask && "Missing call preserved mask for calling convention"); 2963 Ops.push_back(DAG.getRegisterMask(Mask)); 2964 2965 if (InFlag.getNode()) 2966 Ops.push_back(InFlag); 2967 2968 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2969 2970 // If we're doing a tall call, use a TC_RETURN here rather than an 2971 // actual call instruction. 2972 if (IsTailCall) { 2973 MFI.setHasTailCall(); 2974 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2975 } 2976 2977 // Returns a chain and a flag for retval copy to use. 2978 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2979 Chain = Call.getValue(0); 2980 InFlag = Call.getValue(1); 2981 2982 uint64_t CalleePopBytes = NumBytes; 2983 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2984 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2985 InFlag, DL); 2986 if (!Ins.empty()) 2987 InFlag = Chain.getValue(1); 2988 2989 // Handle result values, copying them out of physregs into vregs that we 2990 // return. 2991 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2992 InVals, IsThisReturn, 2993 IsThisReturn ? OutVals[0] : SDValue()); 2994 } 2995 2996 Register SITargetLowering::getRegisterByName(const char* RegName, EVT VT, 2997 const MachineFunction &MF) const { 2998 Register Reg = StringSwitch<Register>(RegName) 2999 .Case("m0", AMDGPU::M0) 3000 .Case("exec", AMDGPU::EXEC) 3001 .Case("exec_lo", AMDGPU::EXEC_LO) 3002 .Case("exec_hi", AMDGPU::EXEC_HI) 3003 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3004 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3005 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3006 .Default(Register()); 3007 3008 if (Reg == AMDGPU::NoRegister) { 3009 report_fatal_error(Twine("invalid register name \"" 3010 + StringRef(RegName) + "\".")); 3011 3012 } 3013 3014 if (!Subtarget->hasFlatScrRegister() && 3015 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3016 report_fatal_error(Twine("invalid register \"" 3017 + StringRef(RegName) + "\" for subtarget.")); 3018 } 3019 3020 switch (Reg) { 3021 case AMDGPU::M0: 3022 case AMDGPU::EXEC_LO: 3023 case AMDGPU::EXEC_HI: 3024 case AMDGPU::FLAT_SCR_LO: 3025 case AMDGPU::FLAT_SCR_HI: 3026 if (VT.getSizeInBits() == 32) 3027 return Reg; 3028 break; 3029 case AMDGPU::EXEC: 3030 case AMDGPU::FLAT_SCR: 3031 if (VT.getSizeInBits() == 64) 3032 return Reg; 3033 break; 3034 default: 3035 llvm_unreachable("missing register type checking"); 3036 } 3037 3038 report_fatal_error(Twine("invalid type for register \"" 3039 + StringRef(RegName) + "\".")); 3040 } 3041 3042 // If kill is not the last instruction, split the block so kill is always a 3043 // proper terminator. 3044 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3045 MachineBasicBlock *BB) const { 3046 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3047 3048 MachineBasicBlock::iterator SplitPoint(&MI); 3049 ++SplitPoint; 3050 3051 if (SplitPoint == BB->end()) { 3052 // Don't bother with a new block. 3053 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3054 return BB; 3055 } 3056 3057 MachineFunction *MF = BB->getParent(); 3058 MachineBasicBlock *SplitBB 3059 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3060 3061 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3062 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3063 3064 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3065 BB->addSuccessor(SplitBB); 3066 3067 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3068 return SplitBB; 3069 } 3070 3071 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3072 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3073 // be the first instruction in the remainder block. 3074 // 3075 /// \returns { LoopBody, Remainder } 3076 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3077 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3078 MachineFunction *MF = MBB.getParent(); 3079 MachineBasicBlock::iterator I(&MI); 3080 3081 // To insert the loop we need to split the block. Move everything after this 3082 // point to a new block, and insert a new empty block between the two. 3083 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3084 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3085 MachineFunction::iterator MBBI(MBB); 3086 ++MBBI; 3087 3088 MF->insert(MBBI, LoopBB); 3089 MF->insert(MBBI, RemainderBB); 3090 3091 LoopBB->addSuccessor(LoopBB); 3092 LoopBB->addSuccessor(RemainderBB); 3093 3094 // Move the rest of the block into a new block. 3095 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3096 3097 if (InstInLoop) { 3098 auto Next = std::next(I); 3099 3100 // Move instruction to loop body. 3101 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3102 3103 // Move the rest of the block. 3104 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3105 } else { 3106 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3107 } 3108 3109 MBB.addSuccessor(LoopBB); 3110 3111 return std::make_pair(LoopBB, RemainderBB); 3112 } 3113 3114 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3115 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3116 MachineBasicBlock *MBB = MI.getParent(); 3117 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3118 auto I = MI.getIterator(); 3119 auto E = std::next(I); 3120 3121 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3122 .addImm(0); 3123 3124 MIBundleBuilder Bundler(*MBB, I, E); 3125 finalizeBundle(*MBB, Bundler.begin()); 3126 } 3127 3128 MachineBasicBlock * 3129 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3130 MachineBasicBlock *BB) const { 3131 const DebugLoc &DL = MI.getDebugLoc(); 3132 3133 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3134 3135 MachineBasicBlock *LoopBB; 3136 MachineBasicBlock *RemainderBB; 3137 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3138 3139 // Apparently kill flags are only valid if the def is in the same block? 3140 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3141 Src->setIsKill(false); 3142 3143 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3144 3145 MachineBasicBlock::iterator I = LoopBB->end(); 3146 3147 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3148 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3149 3150 // Clear TRAP_STS.MEM_VIOL 3151 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3152 .addImm(0) 3153 .addImm(EncodedReg); 3154 3155 bundleInstWithWaitcnt(MI); 3156 3157 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3158 3159 // Load and check TRAP_STS.MEM_VIOL 3160 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3161 .addImm(EncodedReg); 3162 3163 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3164 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3165 .addReg(Reg, RegState::Kill) 3166 .addImm(0); 3167 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3168 .addMBB(LoopBB); 3169 3170 return RemainderBB; 3171 } 3172 3173 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3174 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3175 // will only do one iteration. In the worst case, this will loop 64 times. 3176 // 3177 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3178 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3179 const SIInstrInfo *TII, 3180 MachineRegisterInfo &MRI, 3181 MachineBasicBlock &OrigBB, 3182 MachineBasicBlock &LoopBB, 3183 const DebugLoc &DL, 3184 const MachineOperand &IdxReg, 3185 unsigned InitReg, 3186 unsigned ResultReg, 3187 unsigned PhiReg, 3188 unsigned InitSaveExecReg, 3189 int Offset, 3190 bool UseGPRIdxMode, 3191 bool IsIndirectSrc) { 3192 MachineFunction *MF = OrigBB.getParent(); 3193 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3194 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3195 MachineBasicBlock::iterator I = LoopBB.begin(); 3196 3197 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3198 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3199 Register NewExec = MRI.createVirtualRegister(BoolRC); 3200 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3201 Register CondReg = MRI.createVirtualRegister(BoolRC); 3202 3203 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3204 .addReg(InitReg) 3205 .addMBB(&OrigBB) 3206 .addReg(ResultReg) 3207 .addMBB(&LoopBB); 3208 3209 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3210 .addReg(InitSaveExecReg) 3211 .addMBB(&OrigBB) 3212 .addReg(NewExec) 3213 .addMBB(&LoopBB); 3214 3215 // Read the next variant <- also loop target. 3216 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3217 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3218 3219 // Compare the just read M0 value to all possible Idx values. 3220 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3221 .addReg(CurrentIdxReg) 3222 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3223 3224 // Update EXEC, save the original EXEC value to VCC. 3225 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3226 : AMDGPU::S_AND_SAVEEXEC_B64), 3227 NewExec) 3228 .addReg(CondReg, RegState::Kill); 3229 3230 MRI.setSimpleHint(NewExec, CondReg); 3231 3232 if (UseGPRIdxMode) { 3233 unsigned IdxReg; 3234 if (Offset == 0) { 3235 IdxReg = CurrentIdxReg; 3236 } else { 3237 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3238 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3239 .addReg(CurrentIdxReg, RegState::Kill) 3240 .addImm(Offset); 3241 } 3242 unsigned IdxMode = IsIndirectSrc ? 3243 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3244 MachineInstr *SetOn = 3245 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3246 .addReg(IdxReg, RegState::Kill) 3247 .addImm(IdxMode); 3248 SetOn->getOperand(3).setIsUndef(); 3249 } else { 3250 // Move index from VCC into M0 3251 if (Offset == 0) { 3252 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3253 .addReg(CurrentIdxReg, RegState::Kill); 3254 } else { 3255 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3256 .addReg(CurrentIdxReg, RegState::Kill) 3257 .addImm(Offset); 3258 } 3259 } 3260 3261 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3262 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3263 MachineInstr *InsertPt = 3264 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3265 : AMDGPU::S_XOR_B64_term), Exec) 3266 .addReg(Exec) 3267 .addReg(NewExec); 3268 3269 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3270 // s_cbranch_scc0? 3271 3272 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3273 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3274 .addMBB(&LoopBB); 3275 3276 return InsertPt->getIterator(); 3277 } 3278 3279 // This has slightly sub-optimal regalloc when the source vector is killed by 3280 // the read. The register allocator does not understand that the kill is 3281 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3282 // subregister from it, using 1 more VGPR than necessary. This was saved when 3283 // this was expanded after register allocation. 3284 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3285 MachineBasicBlock &MBB, 3286 MachineInstr &MI, 3287 unsigned InitResultReg, 3288 unsigned PhiReg, 3289 int Offset, 3290 bool UseGPRIdxMode, 3291 bool IsIndirectSrc) { 3292 MachineFunction *MF = MBB.getParent(); 3293 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3294 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3295 MachineRegisterInfo &MRI = MF->getRegInfo(); 3296 const DebugLoc &DL = MI.getDebugLoc(); 3297 MachineBasicBlock::iterator I(&MI); 3298 3299 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3300 Register DstReg = MI.getOperand(0).getReg(); 3301 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3302 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3303 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3304 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3305 3306 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3307 3308 // Save the EXEC mask 3309 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3310 .addReg(Exec); 3311 3312 MachineBasicBlock *LoopBB; 3313 MachineBasicBlock *RemainderBB; 3314 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3315 3316 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3317 3318 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3319 InitResultReg, DstReg, PhiReg, TmpExec, 3320 Offset, UseGPRIdxMode, IsIndirectSrc); 3321 3322 MachineBasicBlock::iterator First = RemainderBB->begin(); 3323 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3324 .addReg(SaveExec); 3325 3326 return InsPt; 3327 } 3328 3329 // Returns subreg index, offset 3330 static std::pair<unsigned, int> 3331 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3332 const TargetRegisterClass *SuperRC, 3333 unsigned VecReg, 3334 int Offset) { 3335 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3336 3337 // Skip out of bounds offsets, or else we would end up using an undefined 3338 // register. 3339 if (Offset >= NumElts || Offset < 0) 3340 return std::make_pair(AMDGPU::sub0, Offset); 3341 3342 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3343 } 3344 3345 // Return true if the index is an SGPR and was set. 3346 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3347 MachineRegisterInfo &MRI, 3348 MachineInstr &MI, 3349 int Offset, 3350 bool UseGPRIdxMode, 3351 bool IsIndirectSrc) { 3352 MachineBasicBlock *MBB = MI.getParent(); 3353 const DebugLoc &DL = MI.getDebugLoc(); 3354 MachineBasicBlock::iterator I(&MI); 3355 3356 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3357 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3358 3359 assert(Idx->getReg() != AMDGPU::NoRegister); 3360 3361 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3362 return false; 3363 3364 if (UseGPRIdxMode) { 3365 unsigned IdxMode = IsIndirectSrc ? 3366 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3367 if (Offset == 0) { 3368 MachineInstr *SetOn = 3369 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3370 .add(*Idx) 3371 .addImm(IdxMode); 3372 3373 SetOn->getOperand(3).setIsUndef(); 3374 } else { 3375 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3376 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3377 .add(*Idx) 3378 .addImm(Offset); 3379 MachineInstr *SetOn = 3380 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3381 .addReg(Tmp, RegState::Kill) 3382 .addImm(IdxMode); 3383 3384 SetOn->getOperand(3).setIsUndef(); 3385 } 3386 3387 return true; 3388 } 3389 3390 if (Offset == 0) { 3391 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3392 .add(*Idx); 3393 } else { 3394 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3395 .add(*Idx) 3396 .addImm(Offset); 3397 } 3398 3399 return true; 3400 } 3401 3402 // Control flow needs to be inserted if indexing with a VGPR. 3403 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3404 MachineBasicBlock &MBB, 3405 const GCNSubtarget &ST) { 3406 const SIInstrInfo *TII = ST.getInstrInfo(); 3407 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3408 MachineFunction *MF = MBB.getParent(); 3409 MachineRegisterInfo &MRI = MF->getRegInfo(); 3410 3411 Register Dst = MI.getOperand(0).getReg(); 3412 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3413 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3414 3415 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3416 3417 unsigned SubReg; 3418 std::tie(SubReg, Offset) 3419 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3420 3421 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3422 3423 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3424 MachineBasicBlock::iterator I(&MI); 3425 const DebugLoc &DL = MI.getDebugLoc(); 3426 3427 if (UseGPRIdxMode) { 3428 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3429 // to avoid interfering with other uses, so probably requires a new 3430 // optimization pass. 3431 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3432 .addReg(SrcReg, RegState::Undef, SubReg) 3433 .addReg(SrcReg, RegState::Implicit) 3434 .addReg(AMDGPU::M0, RegState::Implicit); 3435 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3436 } else { 3437 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3438 .addReg(SrcReg, RegState::Undef, SubReg) 3439 .addReg(SrcReg, RegState::Implicit); 3440 } 3441 3442 MI.eraseFromParent(); 3443 3444 return &MBB; 3445 } 3446 3447 const DebugLoc &DL = MI.getDebugLoc(); 3448 MachineBasicBlock::iterator I(&MI); 3449 3450 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3451 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3452 3453 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3454 3455 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3456 Offset, UseGPRIdxMode, true); 3457 MachineBasicBlock *LoopBB = InsPt->getParent(); 3458 3459 if (UseGPRIdxMode) { 3460 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3461 .addReg(SrcReg, RegState::Undef, SubReg) 3462 .addReg(SrcReg, RegState::Implicit) 3463 .addReg(AMDGPU::M0, RegState::Implicit); 3464 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3465 } else { 3466 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3467 .addReg(SrcReg, RegState::Undef, SubReg) 3468 .addReg(SrcReg, RegState::Implicit); 3469 } 3470 3471 MI.eraseFromParent(); 3472 3473 return LoopBB; 3474 } 3475 3476 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI, 3477 const TargetRegisterClass *VecRC) { 3478 switch (TRI.getRegSizeInBits(*VecRC)) { 3479 case 32: // 4 bytes 3480 return AMDGPU::V_MOVRELD_B32_V1; 3481 case 64: // 8 bytes 3482 return AMDGPU::V_MOVRELD_B32_V2; 3483 case 128: // 16 bytes 3484 return AMDGPU::V_MOVRELD_B32_V4; 3485 case 256: // 32 bytes 3486 return AMDGPU::V_MOVRELD_B32_V8; 3487 case 512: // 64 bytes 3488 return AMDGPU::V_MOVRELD_B32_V16; 3489 default: 3490 llvm_unreachable("unsupported size for MOVRELD pseudos"); 3491 } 3492 } 3493 3494 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3495 MachineBasicBlock &MBB, 3496 const GCNSubtarget &ST) { 3497 const SIInstrInfo *TII = ST.getInstrInfo(); 3498 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3499 MachineFunction *MF = MBB.getParent(); 3500 MachineRegisterInfo &MRI = MF->getRegInfo(); 3501 3502 Register Dst = MI.getOperand(0).getReg(); 3503 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3504 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3505 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3506 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3507 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3508 3509 // This can be an immediate, but will be folded later. 3510 assert(Val->getReg()); 3511 3512 unsigned SubReg; 3513 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3514 SrcVec->getReg(), 3515 Offset); 3516 bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode); 3517 3518 if (Idx->getReg() == AMDGPU::NoRegister) { 3519 MachineBasicBlock::iterator I(&MI); 3520 const DebugLoc &DL = MI.getDebugLoc(); 3521 3522 assert(Offset == 0); 3523 3524 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3525 .add(*SrcVec) 3526 .add(*Val) 3527 .addImm(SubReg); 3528 3529 MI.eraseFromParent(); 3530 return &MBB; 3531 } 3532 3533 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3534 MachineBasicBlock::iterator I(&MI); 3535 const DebugLoc &DL = MI.getDebugLoc(); 3536 3537 if (UseGPRIdxMode) { 3538 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3539 .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst 3540 .add(*Val) 3541 .addReg(Dst, RegState::ImplicitDefine) 3542 .addReg(SrcVec->getReg(), RegState::Implicit) 3543 .addReg(AMDGPU::M0, RegState::Implicit); 3544 3545 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3546 } else { 3547 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3548 3549 BuildMI(MBB, I, DL, MovRelDesc) 3550 .addReg(Dst, RegState::Define) 3551 .addReg(SrcVec->getReg()) 3552 .add(*Val) 3553 .addImm(SubReg - AMDGPU::sub0); 3554 } 3555 3556 MI.eraseFromParent(); 3557 return &MBB; 3558 } 3559 3560 if (Val->isReg()) 3561 MRI.clearKillFlags(Val->getReg()); 3562 3563 const DebugLoc &DL = MI.getDebugLoc(); 3564 3565 Register PhiReg = MRI.createVirtualRegister(VecRC); 3566 3567 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3568 Offset, UseGPRIdxMode, false); 3569 MachineBasicBlock *LoopBB = InsPt->getParent(); 3570 3571 if (UseGPRIdxMode) { 3572 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect)) 3573 .addReg(PhiReg, RegState::Undef, SubReg) // vdst 3574 .add(*Val) // src0 3575 .addReg(Dst, RegState::ImplicitDefine) 3576 .addReg(PhiReg, RegState::Implicit) 3577 .addReg(AMDGPU::M0, RegState::Implicit); 3578 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3579 } else { 3580 const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC)); 3581 3582 BuildMI(*LoopBB, InsPt, DL, MovRelDesc) 3583 .addReg(Dst, RegState::Define) 3584 .addReg(PhiReg) 3585 .add(*Val) 3586 .addImm(SubReg - AMDGPU::sub0); 3587 } 3588 3589 MI.eraseFromParent(); 3590 3591 return LoopBB; 3592 } 3593 3594 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3595 MachineInstr &MI, MachineBasicBlock *BB) const { 3596 3597 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3598 MachineFunction *MF = BB->getParent(); 3599 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3600 3601 if (TII->isMIMG(MI)) { 3602 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3603 report_fatal_error("missing mem operand from MIMG instruction"); 3604 } 3605 // Add a memoperand for mimg instructions so that they aren't assumed to 3606 // be ordered memory instuctions. 3607 3608 return BB; 3609 } 3610 3611 switch (MI.getOpcode()) { 3612 case AMDGPU::S_ADD_U64_PSEUDO: 3613 case AMDGPU::S_SUB_U64_PSEUDO: { 3614 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3615 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3616 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3617 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3618 const DebugLoc &DL = MI.getDebugLoc(); 3619 3620 MachineOperand &Dest = MI.getOperand(0); 3621 MachineOperand &Src0 = MI.getOperand(1); 3622 MachineOperand &Src1 = MI.getOperand(2); 3623 3624 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3625 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3626 3627 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3628 Src0, BoolRC, AMDGPU::sub0, 3629 &AMDGPU::SReg_32RegClass); 3630 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3631 Src0, BoolRC, AMDGPU::sub1, 3632 &AMDGPU::SReg_32RegClass); 3633 3634 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3635 Src1, BoolRC, AMDGPU::sub0, 3636 &AMDGPU::SReg_32RegClass); 3637 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3638 Src1, BoolRC, AMDGPU::sub1, 3639 &AMDGPU::SReg_32RegClass); 3640 3641 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3642 3643 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3644 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3645 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3646 .add(Src0Sub0) 3647 .add(Src1Sub0); 3648 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3649 .add(Src0Sub1) 3650 .add(Src1Sub1); 3651 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3652 .addReg(DestSub0) 3653 .addImm(AMDGPU::sub0) 3654 .addReg(DestSub1) 3655 .addImm(AMDGPU::sub1); 3656 MI.eraseFromParent(); 3657 return BB; 3658 } 3659 case AMDGPU::SI_INIT_M0: { 3660 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3661 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3662 .add(MI.getOperand(0)); 3663 MI.eraseFromParent(); 3664 return BB; 3665 } 3666 case AMDGPU::SI_INIT_EXEC: 3667 // This should be before all vector instructions. 3668 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3669 AMDGPU::EXEC) 3670 .addImm(MI.getOperand(0).getImm()); 3671 MI.eraseFromParent(); 3672 return BB; 3673 3674 case AMDGPU::SI_INIT_EXEC_LO: 3675 // This should be before all vector instructions. 3676 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3677 AMDGPU::EXEC_LO) 3678 .addImm(MI.getOperand(0).getImm()); 3679 MI.eraseFromParent(); 3680 return BB; 3681 3682 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3683 // Extract the thread count from an SGPR input and set EXEC accordingly. 3684 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3685 // 3686 // S_BFE_U32 count, input, {shift, 7} 3687 // S_BFM_B64 exec, count, 0 3688 // S_CMP_EQ_U32 count, 64 3689 // S_CMOV_B64 exec, -1 3690 MachineInstr *FirstMI = &*BB->begin(); 3691 MachineRegisterInfo &MRI = MF->getRegInfo(); 3692 Register InputReg = MI.getOperand(0).getReg(); 3693 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3694 bool Found = false; 3695 3696 // Move the COPY of the input reg to the beginning, so that we can use it. 3697 for (auto I = BB->begin(); I != &MI; I++) { 3698 if (I->getOpcode() != TargetOpcode::COPY || 3699 I->getOperand(0).getReg() != InputReg) 3700 continue; 3701 3702 if (I == FirstMI) { 3703 FirstMI = &*++BB->begin(); 3704 } else { 3705 I->removeFromParent(); 3706 BB->insert(FirstMI, &*I); 3707 } 3708 Found = true; 3709 break; 3710 } 3711 assert(Found); 3712 (void)Found; 3713 3714 // This should be before all vector instructions. 3715 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3716 bool isWave32 = getSubtarget()->isWave32(); 3717 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3718 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3719 .addReg(InputReg) 3720 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3721 BuildMI(*BB, FirstMI, DebugLoc(), 3722 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3723 Exec) 3724 .addReg(CountReg) 3725 .addImm(0); 3726 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3727 .addReg(CountReg, RegState::Kill) 3728 .addImm(getSubtarget()->getWavefrontSize()); 3729 BuildMI(*BB, FirstMI, DebugLoc(), 3730 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3731 Exec) 3732 .addImm(-1); 3733 MI.eraseFromParent(); 3734 return BB; 3735 } 3736 3737 case AMDGPU::GET_GROUPSTATICSIZE: { 3738 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3739 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3740 DebugLoc DL = MI.getDebugLoc(); 3741 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3742 .add(MI.getOperand(0)) 3743 .addImm(MFI->getLDSSize()); 3744 MI.eraseFromParent(); 3745 return BB; 3746 } 3747 case AMDGPU::SI_INDIRECT_SRC_V1: 3748 case AMDGPU::SI_INDIRECT_SRC_V2: 3749 case AMDGPU::SI_INDIRECT_SRC_V4: 3750 case AMDGPU::SI_INDIRECT_SRC_V8: 3751 case AMDGPU::SI_INDIRECT_SRC_V16: 3752 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3753 case AMDGPU::SI_INDIRECT_DST_V1: 3754 case AMDGPU::SI_INDIRECT_DST_V2: 3755 case AMDGPU::SI_INDIRECT_DST_V4: 3756 case AMDGPU::SI_INDIRECT_DST_V8: 3757 case AMDGPU::SI_INDIRECT_DST_V16: 3758 return emitIndirectDst(MI, *BB, *getSubtarget()); 3759 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3760 case AMDGPU::SI_KILL_I1_PSEUDO: 3761 return splitKillBlock(MI, BB); 3762 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3763 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3764 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3765 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3766 3767 Register Dst = MI.getOperand(0).getReg(); 3768 Register Src0 = MI.getOperand(1).getReg(); 3769 Register Src1 = MI.getOperand(2).getReg(); 3770 const DebugLoc &DL = MI.getDebugLoc(); 3771 Register SrcCond = MI.getOperand(3).getReg(); 3772 3773 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3774 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3775 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3776 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3777 3778 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3779 .addReg(SrcCond); 3780 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3781 .addImm(0) 3782 .addReg(Src0, 0, AMDGPU::sub0) 3783 .addImm(0) 3784 .addReg(Src1, 0, AMDGPU::sub0) 3785 .addReg(SrcCondCopy); 3786 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3787 .addImm(0) 3788 .addReg(Src0, 0, AMDGPU::sub1) 3789 .addImm(0) 3790 .addReg(Src1, 0, AMDGPU::sub1) 3791 .addReg(SrcCondCopy); 3792 3793 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3794 .addReg(DstLo) 3795 .addImm(AMDGPU::sub0) 3796 .addReg(DstHi) 3797 .addImm(AMDGPU::sub1); 3798 MI.eraseFromParent(); 3799 return BB; 3800 } 3801 case AMDGPU::SI_BR_UNDEF: { 3802 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3803 const DebugLoc &DL = MI.getDebugLoc(); 3804 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3805 .add(MI.getOperand(0)); 3806 Br->getOperand(1).setIsUndef(true); // read undef SCC 3807 MI.eraseFromParent(); 3808 return BB; 3809 } 3810 case AMDGPU::ADJCALLSTACKUP: 3811 case AMDGPU::ADJCALLSTACKDOWN: { 3812 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3813 MachineInstrBuilder MIB(*MF, &MI); 3814 3815 // Add an implicit use of the frame offset reg to prevent the restore copy 3816 // inserted after the call from being reorderd after stack operations in the 3817 // the caller's frame. 3818 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3819 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3820 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3821 return BB; 3822 } 3823 case AMDGPU::SI_CALL_ISEL: { 3824 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3825 const DebugLoc &DL = MI.getDebugLoc(); 3826 3827 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3828 3829 MachineInstrBuilder MIB; 3830 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3831 3832 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3833 MIB.add(MI.getOperand(I)); 3834 3835 MIB.cloneMemRefs(MI); 3836 MI.eraseFromParent(); 3837 return BB; 3838 } 3839 case AMDGPU::V_ADD_I32_e32: 3840 case AMDGPU::V_SUB_I32_e32: 3841 case AMDGPU::V_SUBREV_I32_e32: { 3842 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3843 const DebugLoc &DL = MI.getDebugLoc(); 3844 unsigned Opc = MI.getOpcode(); 3845 3846 bool NeedClampOperand = false; 3847 if (TII->pseudoToMCOpcode(Opc) == -1) { 3848 Opc = AMDGPU::getVOPe64(Opc); 3849 NeedClampOperand = true; 3850 } 3851 3852 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3853 if (TII->isVOP3(*I)) { 3854 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3855 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3856 I.addReg(TRI->getVCC(), RegState::Define); 3857 } 3858 I.add(MI.getOperand(1)) 3859 .add(MI.getOperand(2)); 3860 if (NeedClampOperand) 3861 I.addImm(0); // clamp bit for e64 encoding 3862 3863 TII->legalizeOperands(*I); 3864 3865 MI.eraseFromParent(); 3866 return BB; 3867 } 3868 case AMDGPU::DS_GWS_INIT: 3869 case AMDGPU::DS_GWS_SEMA_V: 3870 case AMDGPU::DS_GWS_SEMA_BR: 3871 case AMDGPU::DS_GWS_SEMA_P: 3872 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3873 case AMDGPU::DS_GWS_BARRIER: 3874 // A s_waitcnt 0 is required to be the instruction immediately following. 3875 if (getSubtarget()->hasGWSAutoReplay()) { 3876 bundleInstWithWaitcnt(MI); 3877 return BB; 3878 } 3879 3880 return emitGWSMemViolTestLoop(MI, BB); 3881 default: 3882 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3883 } 3884 } 3885 3886 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3887 return isTypeLegal(VT.getScalarType()); 3888 } 3889 3890 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3891 // This currently forces unfolding various combinations of fsub into fma with 3892 // free fneg'd operands. As long as we have fast FMA (controlled by 3893 // isFMAFasterThanFMulAndFAdd), we should perform these. 3894 3895 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3896 // most of these combines appear to be cycle neutral but save on instruction 3897 // count / code size. 3898 return true; 3899 } 3900 3901 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3902 EVT VT) const { 3903 if (!VT.isVector()) { 3904 return MVT::i1; 3905 } 3906 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3907 } 3908 3909 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3910 // TODO: Should i16 be used always if legal? For now it would force VALU 3911 // shifts. 3912 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3913 } 3914 3915 // Answering this is somewhat tricky and depends on the specific device which 3916 // have different rates for fma or all f64 operations. 3917 // 3918 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3919 // regardless of which device (although the number of cycles differs between 3920 // devices), so it is always profitable for f64. 3921 // 3922 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3923 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3924 // which we can always do even without fused FP ops since it returns the same 3925 // result as the separate operations and since it is always full 3926 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3927 // however does not support denormals, so we do report fma as faster if we have 3928 // a fast fma device and require denormals. 3929 // 3930 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3931 EVT VT) const { 3932 VT = VT.getScalarType(); 3933 3934 switch (VT.getSimpleVT().SimpleTy) { 3935 case MVT::f32: { 3936 // This is as fast on some subtargets. However, we always have full rate f32 3937 // mad available which returns the same result as the separate operations 3938 // which we should prefer over fma. We can't use this if we want to support 3939 // denormals, so only report this in these cases. 3940 if (hasFP32Denormals(MF)) 3941 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3942 3943 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3944 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3945 } 3946 case MVT::f64: 3947 return true; 3948 case MVT::f16: 3949 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3950 default: 3951 break; 3952 } 3953 3954 return false; 3955 } 3956 3957 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3958 const SDNode *N) const { 3959 // TODO: Check future ftz flag 3960 // v_mad_f32/v_mac_f32 do not support denormals. 3961 EVT VT = N->getValueType(0); 3962 if (VT == MVT::f32) 3963 return !hasFP32Denormals(DAG.getMachineFunction()); 3964 if (VT == MVT::f16) { 3965 return Subtarget->hasMadF16() && 3966 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3967 } 3968 3969 return false; 3970 } 3971 3972 //===----------------------------------------------------------------------===// 3973 // Custom DAG Lowering Operations 3974 //===----------------------------------------------------------------------===// 3975 3976 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3977 // wider vector type is legal. 3978 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3979 SelectionDAG &DAG) const { 3980 unsigned Opc = Op.getOpcode(); 3981 EVT VT = Op.getValueType(); 3982 assert(VT == MVT::v4f16); 3983 3984 SDValue Lo, Hi; 3985 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3986 3987 SDLoc SL(Op); 3988 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3989 Op->getFlags()); 3990 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3991 Op->getFlags()); 3992 3993 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3994 } 3995 3996 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3997 // wider vector type is legal. 3998 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3999 SelectionDAG &DAG) const { 4000 unsigned Opc = Op.getOpcode(); 4001 EVT VT = Op.getValueType(); 4002 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4003 4004 SDValue Lo0, Hi0; 4005 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4006 SDValue Lo1, Hi1; 4007 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4008 4009 SDLoc SL(Op); 4010 4011 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4012 Op->getFlags()); 4013 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4014 Op->getFlags()); 4015 4016 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4017 } 4018 4019 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4020 SelectionDAG &DAG) const { 4021 unsigned Opc = Op.getOpcode(); 4022 EVT VT = Op.getValueType(); 4023 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 4024 4025 SDValue Lo0, Hi0; 4026 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4027 SDValue Lo1, Hi1; 4028 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4029 SDValue Lo2, Hi2; 4030 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4031 4032 SDLoc SL(Op); 4033 4034 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4035 Op->getFlags()); 4036 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4037 Op->getFlags()); 4038 4039 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4040 } 4041 4042 4043 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4044 switch (Op.getOpcode()) { 4045 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4046 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4047 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4048 case ISD::LOAD: { 4049 SDValue Result = LowerLOAD(Op, DAG); 4050 assert((!Result.getNode() || 4051 Result.getNode()->getNumValues() == 2) && 4052 "Load should return a value and a chain"); 4053 return Result; 4054 } 4055 4056 case ISD::FSIN: 4057 case ISD::FCOS: 4058 return LowerTrig(Op, DAG); 4059 case ISD::SELECT: return LowerSELECT(Op, DAG); 4060 case ISD::FDIV: return LowerFDIV(Op, DAG); 4061 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4062 case ISD::STORE: return LowerSTORE(Op, DAG); 4063 case ISD::GlobalAddress: { 4064 MachineFunction &MF = DAG.getMachineFunction(); 4065 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4066 return LowerGlobalAddress(MFI, Op, DAG); 4067 } 4068 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4069 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4070 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4071 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4072 case ISD::INSERT_SUBVECTOR: 4073 return lowerINSERT_SUBVECTOR(Op, DAG); 4074 case ISD::INSERT_VECTOR_ELT: 4075 return lowerINSERT_VECTOR_ELT(Op, DAG); 4076 case ISD::EXTRACT_VECTOR_ELT: 4077 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4078 case ISD::VECTOR_SHUFFLE: 4079 return lowerVECTOR_SHUFFLE(Op, DAG); 4080 case ISD::BUILD_VECTOR: 4081 return lowerBUILD_VECTOR(Op, DAG); 4082 case ISD::FP_ROUND: 4083 return lowerFP_ROUND(Op, DAG); 4084 case ISD::TRAP: 4085 return lowerTRAP(Op, DAG); 4086 case ISD::DEBUGTRAP: 4087 return lowerDEBUGTRAP(Op, DAG); 4088 case ISD::FABS: 4089 case ISD::FNEG: 4090 case ISD::FCANONICALIZE: 4091 return splitUnaryVectorOp(Op, DAG); 4092 case ISD::FMINNUM: 4093 case ISD::FMAXNUM: 4094 return lowerFMINNUM_FMAXNUM(Op, DAG); 4095 case ISD::FMA: 4096 return splitTernaryVectorOp(Op, DAG); 4097 case ISD::SHL: 4098 case ISD::SRA: 4099 case ISD::SRL: 4100 case ISD::ADD: 4101 case ISD::SUB: 4102 case ISD::MUL: 4103 case ISD::SMIN: 4104 case ISD::SMAX: 4105 case ISD::UMIN: 4106 case ISD::UMAX: 4107 case ISD::FADD: 4108 case ISD::FMUL: 4109 case ISD::FMINNUM_IEEE: 4110 case ISD::FMAXNUM_IEEE: 4111 return splitBinaryVectorOp(Op, DAG); 4112 } 4113 return SDValue(); 4114 } 4115 4116 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4117 const SDLoc &DL, 4118 SelectionDAG &DAG, bool Unpacked) { 4119 if (!LoadVT.isVector()) 4120 return Result; 4121 4122 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4123 // Truncate to v2i16/v4i16. 4124 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4125 4126 // Workaround legalizer not scalarizing truncate after vector op 4127 // legalization byt not creating intermediate vector trunc. 4128 SmallVector<SDValue, 4> Elts; 4129 DAG.ExtractVectorElements(Result, Elts); 4130 for (SDValue &Elt : Elts) 4131 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4132 4133 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4134 4135 // Bitcast to original type (v2f16/v4f16). 4136 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4137 } 4138 4139 // Cast back to the original packed type. 4140 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4141 } 4142 4143 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4144 MemSDNode *M, 4145 SelectionDAG &DAG, 4146 ArrayRef<SDValue> Ops, 4147 bool IsIntrinsic) const { 4148 SDLoc DL(M); 4149 4150 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4151 EVT LoadVT = M->getValueType(0); 4152 4153 EVT EquivLoadVT = LoadVT; 4154 if (Unpacked && LoadVT.isVector()) { 4155 EquivLoadVT = LoadVT.isVector() ? 4156 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4157 LoadVT.getVectorNumElements()) : LoadVT; 4158 } 4159 4160 // Change from v4f16/v2f16 to EquivLoadVT. 4161 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4162 4163 SDValue Load 4164 = DAG.getMemIntrinsicNode( 4165 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4166 VTList, Ops, M->getMemoryVT(), 4167 M->getMemOperand()); 4168 if (!Unpacked) // Just adjusted the opcode. 4169 return Load; 4170 4171 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4172 4173 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4174 } 4175 4176 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4177 SelectionDAG &DAG, 4178 ArrayRef<SDValue> Ops) const { 4179 SDLoc DL(M); 4180 EVT LoadVT = M->getValueType(0); 4181 EVT EltType = LoadVT.getScalarType(); 4182 EVT IntVT = LoadVT.changeTypeToInteger(); 4183 4184 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4185 4186 unsigned Opc = 4187 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4188 4189 if (IsD16) { 4190 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4191 } 4192 4193 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4194 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4195 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4196 4197 if (isTypeLegal(LoadVT)) { 4198 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4199 M->getMemOperand(), DAG); 4200 } 4201 4202 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4203 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4204 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4205 M->getMemOperand(), DAG); 4206 return DAG.getMergeValues( 4207 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4208 DL); 4209 } 4210 4211 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4212 SDNode *N, SelectionDAG &DAG) { 4213 EVT VT = N->getValueType(0); 4214 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4215 int CondCode = CD->getSExtValue(); 4216 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4217 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4218 return DAG.getUNDEF(VT); 4219 4220 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4221 4222 SDValue LHS = N->getOperand(1); 4223 SDValue RHS = N->getOperand(2); 4224 4225 SDLoc DL(N); 4226 4227 EVT CmpVT = LHS.getValueType(); 4228 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4229 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4230 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4231 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4232 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4233 } 4234 4235 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4236 4237 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4238 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4239 4240 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4241 DAG.getCondCode(CCOpcode)); 4242 if (VT.bitsEq(CCVT)) 4243 return SetCC; 4244 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4245 } 4246 4247 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4248 SDNode *N, SelectionDAG &DAG) { 4249 EVT VT = N->getValueType(0); 4250 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4251 4252 int CondCode = CD->getSExtValue(); 4253 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4254 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4255 return DAG.getUNDEF(VT); 4256 } 4257 4258 SDValue Src0 = N->getOperand(1); 4259 SDValue Src1 = N->getOperand(2); 4260 EVT CmpVT = Src0.getValueType(); 4261 SDLoc SL(N); 4262 4263 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4264 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4265 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4266 } 4267 4268 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4269 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4270 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4271 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4272 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4273 Src1, DAG.getCondCode(CCOpcode)); 4274 if (VT.bitsEq(CCVT)) 4275 return SetCC; 4276 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4277 } 4278 4279 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4280 SmallVectorImpl<SDValue> &Results, 4281 SelectionDAG &DAG) const { 4282 switch (N->getOpcode()) { 4283 case ISD::INSERT_VECTOR_ELT: { 4284 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4285 Results.push_back(Res); 4286 return; 4287 } 4288 case ISD::EXTRACT_VECTOR_ELT: { 4289 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4290 Results.push_back(Res); 4291 return; 4292 } 4293 case ISD::INTRINSIC_WO_CHAIN: { 4294 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4295 switch (IID) { 4296 case Intrinsic::amdgcn_cvt_pkrtz: { 4297 SDValue Src0 = N->getOperand(1); 4298 SDValue Src1 = N->getOperand(2); 4299 SDLoc SL(N); 4300 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4301 Src0, Src1); 4302 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4303 return; 4304 } 4305 case Intrinsic::amdgcn_cvt_pknorm_i16: 4306 case Intrinsic::amdgcn_cvt_pknorm_u16: 4307 case Intrinsic::amdgcn_cvt_pk_i16: 4308 case Intrinsic::amdgcn_cvt_pk_u16: { 4309 SDValue Src0 = N->getOperand(1); 4310 SDValue Src1 = N->getOperand(2); 4311 SDLoc SL(N); 4312 unsigned Opcode; 4313 4314 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4315 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4316 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4317 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4318 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4319 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4320 else 4321 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4322 4323 EVT VT = N->getValueType(0); 4324 if (isTypeLegal(VT)) 4325 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4326 else { 4327 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4328 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4329 } 4330 return; 4331 } 4332 } 4333 break; 4334 } 4335 case ISD::INTRINSIC_W_CHAIN: { 4336 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4337 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4338 // FIXME: Hacky 4339 Results.push_back(Res.getOperand(0)); 4340 Results.push_back(Res.getOperand(1)); 4341 } else { 4342 Results.push_back(Res); 4343 Results.push_back(Res.getValue(1)); 4344 } 4345 return; 4346 } 4347 4348 break; 4349 } 4350 case ISD::SELECT: { 4351 SDLoc SL(N); 4352 EVT VT = N->getValueType(0); 4353 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4354 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4355 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4356 4357 EVT SelectVT = NewVT; 4358 if (NewVT.bitsLT(MVT::i32)) { 4359 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4360 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4361 SelectVT = MVT::i32; 4362 } 4363 4364 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4365 N->getOperand(0), LHS, RHS); 4366 4367 if (NewVT != SelectVT) 4368 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4369 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4370 return; 4371 } 4372 case ISD::FNEG: { 4373 if (N->getValueType(0) != MVT::v2f16) 4374 break; 4375 4376 SDLoc SL(N); 4377 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4378 4379 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4380 BC, 4381 DAG.getConstant(0x80008000, SL, MVT::i32)); 4382 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4383 return; 4384 } 4385 case ISD::FABS: { 4386 if (N->getValueType(0) != MVT::v2f16) 4387 break; 4388 4389 SDLoc SL(N); 4390 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4391 4392 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4393 BC, 4394 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4395 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4396 return; 4397 } 4398 default: 4399 break; 4400 } 4401 } 4402 4403 /// Helper function for LowerBRCOND 4404 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4405 4406 SDNode *Parent = Value.getNode(); 4407 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4408 I != E; ++I) { 4409 4410 if (I.getUse().get() != Value) 4411 continue; 4412 4413 if (I->getOpcode() == Opcode) 4414 return *I; 4415 } 4416 return nullptr; 4417 } 4418 4419 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4420 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4421 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4422 case Intrinsic::amdgcn_if: 4423 return AMDGPUISD::IF; 4424 case Intrinsic::amdgcn_else: 4425 return AMDGPUISD::ELSE; 4426 case Intrinsic::amdgcn_loop: 4427 return AMDGPUISD::LOOP; 4428 case Intrinsic::amdgcn_end_cf: 4429 llvm_unreachable("should not occur"); 4430 default: 4431 return 0; 4432 } 4433 } 4434 4435 // break, if_break, else_break are all only used as inputs to loop, not 4436 // directly as branch conditions. 4437 return 0; 4438 } 4439 4440 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4441 const Triple &TT = getTargetMachine().getTargetTriple(); 4442 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4443 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4444 AMDGPU::shouldEmitConstantsToTextSection(TT); 4445 } 4446 4447 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4448 // FIXME: Either avoid relying on address space here or change the default 4449 // address space for functions to avoid the explicit check. 4450 return (GV->getValueType()->isFunctionTy() || 4451 GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4452 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4453 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4454 !shouldEmitFixup(GV) && 4455 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4456 } 4457 4458 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4459 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4460 } 4461 4462 /// This transforms the control flow intrinsics to get the branch destination as 4463 /// last parameter, also switches branch target with BR if the need arise 4464 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4465 SelectionDAG &DAG) const { 4466 SDLoc DL(BRCOND); 4467 4468 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4469 SDValue Target = BRCOND.getOperand(2); 4470 SDNode *BR = nullptr; 4471 SDNode *SetCC = nullptr; 4472 4473 if (Intr->getOpcode() == ISD::SETCC) { 4474 // As long as we negate the condition everything is fine 4475 SetCC = Intr; 4476 Intr = SetCC->getOperand(0).getNode(); 4477 4478 } else { 4479 // Get the target from BR if we don't negate the condition 4480 BR = findUser(BRCOND, ISD::BR); 4481 Target = BR->getOperand(1); 4482 } 4483 4484 // FIXME: This changes the types of the intrinsics instead of introducing new 4485 // nodes with the correct types. 4486 // e.g. llvm.amdgcn.loop 4487 4488 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4489 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4490 4491 unsigned CFNode = isCFIntrinsic(Intr); 4492 if (CFNode == 0) { 4493 // This is a uniform branch so we don't need to legalize. 4494 return BRCOND; 4495 } 4496 4497 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4498 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4499 4500 assert(!SetCC || 4501 (SetCC->getConstantOperandVal(1) == 1 && 4502 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4503 ISD::SETNE)); 4504 4505 // operands of the new intrinsic call 4506 SmallVector<SDValue, 4> Ops; 4507 if (HaveChain) 4508 Ops.push_back(BRCOND.getOperand(0)); 4509 4510 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4511 Ops.push_back(Target); 4512 4513 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4514 4515 // build the new intrinsic call 4516 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4517 4518 if (!HaveChain) { 4519 SDValue Ops[] = { 4520 SDValue(Result, 0), 4521 BRCOND.getOperand(0) 4522 }; 4523 4524 Result = DAG.getMergeValues(Ops, DL).getNode(); 4525 } 4526 4527 if (BR) { 4528 // Give the branch instruction our target 4529 SDValue Ops[] = { 4530 BR->getOperand(0), 4531 BRCOND.getOperand(2) 4532 }; 4533 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4534 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4535 BR = NewBR.getNode(); 4536 } 4537 4538 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4539 4540 // Copy the intrinsic results to registers 4541 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4542 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4543 if (!CopyToReg) 4544 continue; 4545 4546 Chain = DAG.getCopyToReg( 4547 Chain, DL, 4548 CopyToReg->getOperand(1), 4549 SDValue(Result, i - 1), 4550 SDValue()); 4551 4552 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4553 } 4554 4555 // Remove the old intrinsic from the chain 4556 DAG.ReplaceAllUsesOfValueWith( 4557 SDValue(Intr, Intr->getNumValues() - 1), 4558 Intr->getOperand(0)); 4559 4560 return Chain; 4561 } 4562 4563 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4564 SelectionDAG &DAG) const { 4565 MVT VT = Op.getSimpleValueType(); 4566 SDLoc DL(Op); 4567 // Checking the depth 4568 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4569 return DAG.getConstant(0, DL, VT); 4570 4571 MachineFunction &MF = DAG.getMachineFunction(); 4572 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4573 // Check for kernel and shader functions 4574 if (Info->isEntryFunction()) 4575 return DAG.getConstant(0, DL, VT); 4576 4577 MachineFrameInfo &MFI = MF.getFrameInfo(); 4578 // There is a call to @llvm.returnaddress in this function 4579 MFI.setReturnAddressIsTaken(true); 4580 4581 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4582 // Get the return address reg and mark it as an implicit live-in 4583 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4584 4585 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4586 } 4587 4588 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4589 SDValue Op, 4590 const SDLoc &DL, 4591 EVT VT) const { 4592 return Op.getValueType().bitsLE(VT) ? 4593 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4594 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4595 } 4596 4597 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4598 assert(Op.getValueType() == MVT::f16 && 4599 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4600 4601 SDValue Src = Op.getOperand(0); 4602 EVT SrcVT = Src.getValueType(); 4603 if (SrcVT != MVT::f64) 4604 return Op; 4605 4606 SDLoc DL(Op); 4607 4608 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4609 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4610 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4611 } 4612 4613 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4614 SelectionDAG &DAG) const { 4615 EVT VT = Op.getValueType(); 4616 const MachineFunction &MF = DAG.getMachineFunction(); 4617 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4618 bool IsIEEEMode = Info->getMode().IEEE; 4619 4620 // FIXME: Assert during eslection that this is only selected for 4621 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4622 // mode functions, but this happens to be OK since it's only done in cases 4623 // where there is known no sNaN. 4624 if (IsIEEEMode) 4625 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4626 4627 if (VT == MVT::v4f16) 4628 return splitBinaryVectorOp(Op, DAG); 4629 return Op; 4630 } 4631 4632 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4633 SDLoc SL(Op); 4634 SDValue Chain = Op.getOperand(0); 4635 4636 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4637 !Subtarget->isTrapHandlerEnabled()) 4638 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4639 4640 MachineFunction &MF = DAG.getMachineFunction(); 4641 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4642 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4643 assert(UserSGPR != AMDGPU::NoRegister); 4644 SDValue QueuePtr = CreateLiveInRegister( 4645 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4646 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4647 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4648 QueuePtr, SDValue()); 4649 SDValue Ops[] = { 4650 ToReg, 4651 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4652 SGPR01, 4653 ToReg.getValue(1) 4654 }; 4655 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4656 } 4657 4658 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4659 SDLoc SL(Op); 4660 SDValue Chain = Op.getOperand(0); 4661 MachineFunction &MF = DAG.getMachineFunction(); 4662 4663 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4664 !Subtarget->isTrapHandlerEnabled()) { 4665 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4666 "debugtrap handler not supported", 4667 Op.getDebugLoc(), 4668 DS_Warning); 4669 LLVMContext &Ctx = MF.getFunction().getContext(); 4670 Ctx.diagnose(NoTrap); 4671 return Chain; 4672 } 4673 4674 SDValue Ops[] = { 4675 Chain, 4676 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4677 }; 4678 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4679 } 4680 4681 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4682 SelectionDAG &DAG) const { 4683 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4684 if (Subtarget->hasApertureRegs()) { 4685 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4686 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4687 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4688 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4689 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4690 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4691 unsigned Encoding = 4692 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4693 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4694 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4695 4696 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4697 SDValue ApertureReg = SDValue( 4698 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4699 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4700 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4701 } 4702 4703 MachineFunction &MF = DAG.getMachineFunction(); 4704 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4705 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4706 assert(UserSGPR != AMDGPU::NoRegister); 4707 4708 SDValue QueuePtr = CreateLiveInRegister( 4709 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4710 4711 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4712 // private_segment_aperture_base_hi. 4713 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4714 4715 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4716 4717 // TODO: Use custom target PseudoSourceValue. 4718 // TODO: We should use the value from the IR intrinsic call, but it might not 4719 // be available and how do we get it? 4720 Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()), 4721 AMDGPUAS::CONSTANT_ADDRESS)); 4722 4723 MachinePointerInfo PtrInfo(V, StructOffset); 4724 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4725 MinAlign(64, StructOffset), 4726 MachineMemOperand::MODereferenceable | 4727 MachineMemOperand::MOInvariant); 4728 } 4729 4730 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4731 SelectionDAG &DAG) const { 4732 SDLoc SL(Op); 4733 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4734 4735 SDValue Src = ASC->getOperand(0); 4736 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4737 4738 const AMDGPUTargetMachine &TM = 4739 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4740 4741 // flat -> local/private 4742 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4743 unsigned DestAS = ASC->getDestAddressSpace(); 4744 4745 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4746 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4747 unsigned NullVal = TM.getNullPointerValue(DestAS); 4748 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4749 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4750 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4751 4752 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4753 NonNull, Ptr, SegmentNullPtr); 4754 } 4755 } 4756 4757 // local/private -> flat 4758 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4759 unsigned SrcAS = ASC->getSrcAddressSpace(); 4760 4761 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4762 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4763 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4764 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4765 4766 SDValue NonNull 4767 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4768 4769 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4770 SDValue CvtPtr 4771 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4772 4773 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4774 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4775 FlatNullPtr); 4776 } 4777 } 4778 4779 // global <-> flat are no-ops and never emitted. 4780 4781 const MachineFunction &MF = DAG.getMachineFunction(); 4782 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4783 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4784 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4785 4786 return DAG.getUNDEF(ASC->getValueType(0)); 4787 } 4788 4789 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4790 // the small vector and inserting them into the big vector. That is better than 4791 // the default expansion of doing it via a stack slot. Even though the use of 4792 // the stack slot would be optimized away afterwards, the stack slot itself 4793 // remains. 4794 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4795 SelectionDAG &DAG) const { 4796 SDValue Vec = Op.getOperand(0); 4797 SDValue Ins = Op.getOperand(1); 4798 SDValue Idx = Op.getOperand(2); 4799 EVT VecVT = Vec.getValueType(); 4800 EVT InsVT = Ins.getValueType(); 4801 EVT EltVT = VecVT.getVectorElementType(); 4802 unsigned InsNumElts = InsVT.getVectorNumElements(); 4803 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4804 SDLoc SL(Op); 4805 4806 for (unsigned I = 0; I != InsNumElts; ++I) { 4807 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4808 DAG.getConstant(I, SL, MVT::i32)); 4809 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4810 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4811 } 4812 return Vec; 4813 } 4814 4815 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4816 SelectionDAG &DAG) const { 4817 SDValue Vec = Op.getOperand(0); 4818 SDValue InsVal = Op.getOperand(1); 4819 SDValue Idx = Op.getOperand(2); 4820 EVT VecVT = Vec.getValueType(); 4821 EVT EltVT = VecVT.getVectorElementType(); 4822 unsigned VecSize = VecVT.getSizeInBits(); 4823 unsigned EltSize = EltVT.getSizeInBits(); 4824 4825 4826 assert(VecSize <= 64); 4827 4828 unsigned NumElts = VecVT.getVectorNumElements(); 4829 SDLoc SL(Op); 4830 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4831 4832 if (NumElts == 4 && EltSize == 16 && KIdx) { 4833 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4834 4835 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4836 DAG.getConstant(0, SL, MVT::i32)); 4837 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4838 DAG.getConstant(1, SL, MVT::i32)); 4839 4840 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4841 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4842 4843 unsigned Idx = KIdx->getZExtValue(); 4844 bool InsertLo = Idx < 2; 4845 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4846 InsertLo ? LoVec : HiVec, 4847 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4848 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4849 4850 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4851 4852 SDValue Concat = InsertLo ? 4853 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4854 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4855 4856 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4857 } 4858 4859 if (isa<ConstantSDNode>(Idx)) 4860 return SDValue(); 4861 4862 MVT IntVT = MVT::getIntegerVT(VecSize); 4863 4864 // Avoid stack access for dynamic indexing. 4865 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4866 4867 // Create a congruent vector with the target value in each element so that 4868 // the required element can be masked and ORed into the target vector. 4869 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4870 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4871 4872 assert(isPowerOf2_32(EltSize)); 4873 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4874 4875 // Convert vector index to bit-index. 4876 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4877 4878 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4879 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4880 DAG.getConstant(0xffff, SL, IntVT), 4881 ScaledIdx); 4882 4883 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4884 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4885 DAG.getNOT(SL, BFM, IntVT), BCVec); 4886 4887 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4888 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4889 } 4890 4891 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4892 SelectionDAG &DAG) const { 4893 SDLoc SL(Op); 4894 4895 EVT ResultVT = Op.getValueType(); 4896 SDValue Vec = Op.getOperand(0); 4897 SDValue Idx = Op.getOperand(1); 4898 EVT VecVT = Vec.getValueType(); 4899 unsigned VecSize = VecVT.getSizeInBits(); 4900 EVT EltVT = VecVT.getVectorElementType(); 4901 assert(VecSize <= 64); 4902 4903 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4904 4905 // Make sure we do any optimizations that will make it easier to fold 4906 // source modifiers before obscuring it with bit operations. 4907 4908 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4909 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4910 return Combined; 4911 4912 unsigned EltSize = EltVT.getSizeInBits(); 4913 assert(isPowerOf2_32(EltSize)); 4914 4915 MVT IntVT = MVT::getIntegerVT(VecSize); 4916 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4917 4918 // Convert vector index to bit-index (* EltSize) 4919 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4920 4921 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4922 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4923 4924 if (ResultVT == MVT::f16) { 4925 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4926 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4927 } 4928 4929 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4930 } 4931 4932 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4933 assert(Elt % 2 == 0); 4934 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4935 } 4936 4937 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4938 SelectionDAG &DAG) const { 4939 SDLoc SL(Op); 4940 EVT ResultVT = Op.getValueType(); 4941 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4942 4943 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4944 EVT EltVT = PackVT.getVectorElementType(); 4945 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4946 4947 // vector_shuffle <0,1,6,7> lhs, rhs 4948 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4949 // 4950 // vector_shuffle <6,7,2,3> lhs, rhs 4951 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4952 // 4953 // vector_shuffle <6,7,0,1> lhs, rhs 4954 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4955 4956 // Avoid scalarizing when both halves are reading from consecutive elements. 4957 SmallVector<SDValue, 4> Pieces; 4958 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4959 if (elementPairIsContiguous(SVN->getMask(), I)) { 4960 const int Idx = SVN->getMaskElt(I); 4961 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4962 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4963 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4964 PackVT, SVN->getOperand(VecIdx), 4965 DAG.getConstant(EltIdx, SL, MVT::i32)); 4966 Pieces.push_back(SubVec); 4967 } else { 4968 const int Idx0 = SVN->getMaskElt(I); 4969 const int Idx1 = SVN->getMaskElt(I + 1); 4970 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4971 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4972 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4973 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4974 4975 SDValue Vec0 = SVN->getOperand(VecIdx0); 4976 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4977 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4978 4979 SDValue Vec1 = SVN->getOperand(VecIdx1); 4980 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4981 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4982 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4983 } 4984 } 4985 4986 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4987 } 4988 4989 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4990 SelectionDAG &DAG) const { 4991 SDLoc SL(Op); 4992 EVT VT = Op.getValueType(); 4993 4994 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4995 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4996 4997 // Turn into pair of packed build_vectors. 4998 // TODO: Special case for constants that can be materialized with s_mov_b64. 4999 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5000 { Op.getOperand(0), Op.getOperand(1) }); 5001 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5002 { Op.getOperand(2), Op.getOperand(3) }); 5003 5004 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5005 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5006 5007 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5008 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5009 } 5010 5011 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5012 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5013 5014 SDValue Lo = Op.getOperand(0); 5015 SDValue Hi = Op.getOperand(1); 5016 5017 // Avoid adding defined bits with the zero_extend. 5018 if (Hi.isUndef()) { 5019 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5020 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5021 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5022 } 5023 5024 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5025 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5026 5027 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5028 DAG.getConstant(16, SL, MVT::i32)); 5029 if (Lo.isUndef()) 5030 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5031 5032 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5033 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5034 5035 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5036 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5037 } 5038 5039 bool 5040 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5041 // We can fold offsets for anything that doesn't require a GOT relocation. 5042 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5043 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5044 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5045 !shouldEmitGOTReloc(GA->getGlobal()); 5046 } 5047 5048 static SDValue 5049 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5050 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5051 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5052 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5053 // lowered to the following code sequence: 5054 // 5055 // For constant address space: 5056 // s_getpc_b64 s[0:1] 5057 // s_add_u32 s0, s0, $symbol 5058 // s_addc_u32 s1, s1, 0 5059 // 5060 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5061 // a fixup or relocation is emitted to replace $symbol with a literal 5062 // constant, which is a pc-relative offset from the encoding of the $symbol 5063 // operand to the global variable. 5064 // 5065 // For global address space: 5066 // s_getpc_b64 s[0:1] 5067 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5068 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5069 // 5070 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5071 // fixups or relocations are emitted to replace $symbol@*@lo and 5072 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5073 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5074 // operand to the global variable. 5075 // 5076 // What we want here is an offset from the value returned by s_getpc 5077 // (which is the address of the s_add_u32 instruction) to the global 5078 // variable, but since the encoding of $symbol starts 4 bytes after the start 5079 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5080 // small. This requires us to add 4 to the global variable offset in order to 5081 // compute the correct address. 5082 SDValue PtrLo = 5083 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5084 SDValue PtrHi; 5085 if (GAFlags == SIInstrInfo::MO_NONE) { 5086 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5087 } else { 5088 PtrHi = 5089 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5090 } 5091 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5092 } 5093 5094 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5095 SDValue Op, 5096 SelectionDAG &DAG) const { 5097 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5098 const GlobalValue *GV = GSD->getGlobal(); 5099 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5100 (!GV->hasExternalLinkage() || 5101 getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 5102 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) || 5103 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5104 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5105 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5106 5107 SDLoc DL(GSD); 5108 EVT PtrVT = Op.getValueType(); 5109 5110 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5111 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5112 SIInstrInfo::MO_ABS32_LO); 5113 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5114 } 5115 5116 if (shouldEmitFixup(GV)) 5117 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5118 else if (shouldEmitPCReloc(GV)) 5119 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5120 SIInstrInfo::MO_REL32); 5121 5122 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5123 SIInstrInfo::MO_GOTPCREL32); 5124 5125 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5126 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5127 const DataLayout &DataLayout = DAG.getDataLayout(); 5128 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5129 MachinePointerInfo PtrInfo 5130 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5131 5132 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5133 MachineMemOperand::MODereferenceable | 5134 MachineMemOperand::MOInvariant); 5135 } 5136 5137 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5138 const SDLoc &DL, SDValue V) const { 5139 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5140 // the destination register. 5141 // 5142 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5143 // so we will end up with redundant moves to m0. 5144 // 5145 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5146 5147 // A Null SDValue creates a glue result. 5148 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5149 V, Chain); 5150 return SDValue(M0, 0); 5151 } 5152 5153 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5154 SDValue Op, 5155 MVT VT, 5156 unsigned Offset) const { 5157 SDLoc SL(Op); 5158 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5159 DAG.getEntryNode(), Offset, 4, false); 5160 // The local size values will have the hi 16-bits as zero. 5161 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5162 DAG.getValueType(VT)); 5163 } 5164 5165 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5166 EVT VT) { 5167 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5168 "non-hsa intrinsic with hsa target", 5169 DL.getDebugLoc()); 5170 DAG.getContext()->diagnose(BadIntrin); 5171 return DAG.getUNDEF(VT); 5172 } 5173 5174 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5175 EVT VT) { 5176 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5177 "intrinsic not supported on subtarget", 5178 DL.getDebugLoc()); 5179 DAG.getContext()->diagnose(BadIntrin); 5180 return DAG.getUNDEF(VT); 5181 } 5182 5183 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5184 ArrayRef<SDValue> Elts) { 5185 assert(!Elts.empty()); 5186 MVT Type; 5187 unsigned NumElts; 5188 5189 if (Elts.size() == 1) { 5190 Type = MVT::f32; 5191 NumElts = 1; 5192 } else if (Elts.size() == 2) { 5193 Type = MVT::v2f32; 5194 NumElts = 2; 5195 } else if (Elts.size() <= 4) { 5196 Type = MVT::v4f32; 5197 NumElts = 4; 5198 } else if (Elts.size() <= 8) { 5199 Type = MVT::v8f32; 5200 NumElts = 8; 5201 } else { 5202 assert(Elts.size() <= 16); 5203 Type = MVT::v16f32; 5204 NumElts = 16; 5205 } 5206 5207 SmallVector<SDValue, 16> VecElts(NumElts); 5208 for (unsigned i = 0; i < Elts.size(); ++i) { 5209 SDValue Elt = Elts[i]; 5210 if (Elt.getValueType() != MVT::f32) 5211 Elt = DAG.getBitcast(MVT::f32, Elt); 5212 VecElts[i] = Elt; 5213 } 5214 for (unsigned i = Elts.size(); i < NumElts; ++i) 5215 VecElts[i] = DAG.getUNDEF(MVT::f32); 5216 5217 if (NumElts == 1) 5218 return VecElts[0]; 5219 return DAG.getBuildVector(Type, DL, VecElts); 5220 } 5221 5222 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5223 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5224 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5225 5226 uint64_t Value = CachePolicyConst->getZExtValue(); 5227 SDLoc DL(CachePolicy); 5228 if (GLC) { 5229 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5230 Value &= ~(uint64_t)0x1; 5231 } 5232 if (SLC) { 5233 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5234 Value &= ~(uint64_t)0x2; 5235 } 5236 if (DLC) { 5237 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5238 Value &= ~(uint64_t)0x4; 5239 } 5240 5241 return Value == 0; 5242 } 5243 5244 // Re-construct the required return value for a image load intrinsic. 5245 // This is more complicated due to the optional use TexFailCtrl which means the required 5246 // return type is an aggregate 5247 static SDValue constructRetValue(SelectionDAG &DAG, 5248 MachineSDNode *Result, 5249 ArrayRef<EVT> ResultTypes, 5250 bool IsTexFail, bool Unpacked, bool IsD16, 5251 int DMaskPop, int NumVDataDwords, 5252 const SDLoc &DL, LLVMContext &Context) { 5253 // Determine the required return type. This is the same regardless of IsTexFail flag 5254 EVT ReqRetVT = ResultTypes[0]; 5255 EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT; 5256 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5257 EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT; 5258 EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts) 5259 : AdjEltVT 5260 : ReqRetVT; 5261 5262 // Extract data part of the result 5263 // Bitcast the result to the same type as the required return type 5264 int NumElts; 5265 if (IsD16 && !Unpacked) 5266 NumElts = NumVDataDwords << 1; 5267 else 5268 NumElts = NumVDataDwords; 5269 5270 EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts) 5271 : AdjEltVT; 5272 5273 // Special case for v6f16. Rather than add support for this, use v3i32 to 5274 // extract the data elements 5275 bool V6F16Special = false; 5276 if (NumElts == 6) { 5277 CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2); 5278 DMaskPop >>= 1; 5279 ReqRetNumElts >>= 1; 5280 V6F16Special = true; 5281 AdjVT = MVT::v2i32; 5282 } 5283 5284 SDValue N = SDValue(Result, 0); 5285 SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N); 5286 5287 // Iterate over the result 5288 SmallVector<SDValue, 4> BVElts; 5289 5290 if (CastVT.isVector()) { 5291 DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop); 5292 } else { 5293 BVElts.push_back(CastRes); 5294 } 5295 int ExtraElts = ReqRetNumElts - DMaskPop; 5296 while(ExtraElts--) 5297 BVElts.push_back(DAG.getUNDEF(AdjEltVT)); 5298 5299 SDValue PreTFCRes; 5300 if (ReqRetNumElts > 1) { 5301 SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts); 5302 if (IsD16 && Unpacked) 5303 PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked); 5304 else 5305 PreTFCRes = NewVec; 5306 } else { 5307 PreTFCRes = BVElts[0]; 5308 } 5309 5310 if (V6F16Special) 5311 PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes); 5312 5313 if (!IsTexFail) { 5314 if (Result->getNumValues() > 1) 5315 return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL); 5316 else 5317 return PreTFCRes; 5318 } 5319 5320 // Extract the TexFail result and insert into aggregate return 5321 SmallVector<SDValue, 1> TFCElt; 5322 DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1); 5323 SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]); 5324 return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL); 5325 } 5326 5327 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5328 SDValue *LWE, bool &IsTexFail) { 5329 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5330 5331 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5332 if (Value) { 5333 IsTexFail = true; 5334 } 5335 5336 SDLoc DL(TexFailCtrlConst); 5337 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5338 Value &= ~(uint64_t)0x1; 5339 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5340 Value &= ~(uint64_t)0x2; 5341 5342 return Value == 0; 5343 } 5344 5345 SDValue SITargetLowering::lowerImage(SDValue Op, 5346 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5347 SelectionDAG &DAG) const { 5348 SDLoc DL(Op); 5349 MachineFunction &MF = DAG.getMachineFunction(); 5350 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5351 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5352 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5353 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5354 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5355 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5356 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5357 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5358 unsigned IntrOpcode = Intr->BaseOpcode; 5359 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5360 5361 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5362 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5363 bool IsD16 = false; 5364 bool IsA16 = false; 5365 SDValue VData; 5366 int NumVDataDwords; 5367 bool AdjustRetType = false; 5368 5369 unsigned AddrIdx; // Index of first address argument 5370 unsigned DMask; 5371 unsigned DMaskLanes = 0; 5372 5373 if (BaseOpcode->Atomic) { 5374 VData = Op.getOperand(2); 5375 5376 bool Is64Bit = VData.getValueType() == MVT::i64; 5377 if (BaseOpcode->AtomicX2) { 5378 SDValue VData2 = Op.getOperand(3); 5379 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5380 {VData, VData2}); 5381 if (Is64Bit) 5382 VData = DAG.getBitcast(MVT::v4i32, VData); 5383 5384 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5385 DMask = Is64Bit ? 0xf : 0x3; 5386 NumVDataDwords = Is64Bit ? 4 : 2; 5387 AddrIdx = 4; 5388 } else { 5389 DMask = Is64Bit ? 0x3 : 0x1; 5390 NumVDataDwords = Is64Bit ? 2 : 1; 5391 AddrIdx = 3; 5392 } 5393 } else { 5394 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5395 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5396 DMask = DMaskConst->getZExtValue(); 5397 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5398 5399 if (BaseOpcode->Store) { 5400 VData = Op.getOperand(2); 5401 5402 MVT StoreVT = VData.getSimpleValueType(); 5403 if (StoreVT.getScalarType() == MVT::f16) { 5404 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5405 return Op; // D16 is unsupported for this instruction 5406 5407 IsD16 = true; 5408 VData = handleD16VData(VData, DAG); 5409 } 5410 5411 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5412 } else { 5413 // Work out the num dwords based on the dmask popcount and underlying type 5414 // and whether packing is supported. 5415 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5416 if (LoadVT.getScalarType() == MVT::f16) { 5417 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5418 return Op; // D16 is unsupported for this instruction 5419 5420 IsD16 = true; 5421 } 5422 5423 // Confirm that the return type is large enough for the dmask specified 5424 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5425 (!LoadVT.isVector() && DMaskLanes > 1)) 5426 return Op; 5427 5428 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5429 NumVDataDwords = (DMaskLanes + 1) / 2; 5430 else 5431 NumVDataDwords = DMaskLanes; 5432 5433 AdjustRetType = true; 5434 } 5435 5436 AddrIdx = DMaskIdx + 1; 5437 } 5438 5439 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5440 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5441 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5442 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5443 NumCoords + NumLCM; 5444 unsigned NumMIVAddrs = NumVAddrs; 5445 5446 SmallVector<SDValue, 4> VAddrs; 5447 5448 // Optimize _L to _LZ when _L is zero 5449 if (LZMappingInfo) { 5450 if (auto ConstantLod = 5451 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5452 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5453 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5454 NumMIVAddrs--; // remove 'lod' 5455 } 5456 } 5457 } 5458 5459 // Optimize _mip away, when 'lod' is zero 5460 if (MIPMappingInfo) { 5461 if (auto ConstantLod = 5462 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5463 if (ConstantLod->isNullValue()) { 5464 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5465 NumMIVAddrs--; // remove 'lod' 5466 } 5467 } 5468 } 5469 5470 // Check for 16 bit addresses and pack if true. 5471 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5472 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5473 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5474 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) && 5475 ST->hasFeature(AMDGPU::FeatureR128A16)) { 5476 IsA16 = true; 5477 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5478 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5479 SDValue AddrLo, AddrHi; 5480 // Push back extra arguments. 5481 if (i < DimIdx) { 5482 AddrLo = Op.getOperand(i); 5483 } else { 5484 AddrLo = Op.getOperand(i); 5485 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5486 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5487 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5488 ((NumGradients / 2) % 2 == 1 && 5489 (i == DimIdx + (NumGradients / 2) - 1 || 5490 i == DimIdx + NumGradients - 1))) { 5491 AddrHi = DAG.getUNDEF(MVT::f16); 5492 } else { 5493 AddrHi = Op.getOperand(i + 1); 5494 i++; 5495 } 5496 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5497 {AddrLo, AddrHi}); 5498 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5499 } 5500 VAddrs.push_back(AddrLo); 5501 } 5502 } else { 5503 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5504 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5505 } 5506 5507 // If the register allocator cannot place the address registers contiguously 5508 // without introducing moves, then using the non-sequential address encoding 5509 // is always preferable, since it saves VALU instructions and is usually a 5510 // wash in terms of code size or even better. 5511 // 5512 // However, we currently have no way of hinting to the register allocator that 5513 // MIMG addresses should be placed contiguously when it is possible to do so, 5514 // so force non-NSA for the common 2-address case as a heuristic. 5515 // 5516 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5517 // allocation when possible. 5518 bool UseNSA = 5519 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5520 SDValue VAddr; 5521 if (!UseNSA) 5522 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5523 5524 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5525 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5526 unsigned CtrlIdx; // Index of texfailctrl argument 5527 SDValue Unorm; 5528 if (!BaseOpcode->Sampler) { 5529 Unorm = True; 5530 CtrlIdx = AddrIdx + NumVAddrs + 1; 5531 } else { 5532 auto UnormConst = 5533 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5534 5535 Unorm = UnormConst->getZExtValue() ? True : False; 5536 CtrlIdx = AddrIdx + NumVAddrs + 3; 5537 } 5538 5539 SDValue TFE; 5540 SDValue LWE; 5541 SDValue TexFail = Op.getOperand(CtrlIdx); 5542 bool IsTexFail = false; 5543 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5544 return Op; 5545 5546 if (IsTexFail) { 5547 if (!DMaskLanes) { 5548 // Expecting to get an error flag since TFC is on - and dmask is 0 5549 // Force dmask to be at least 1 otherwise the instruction will fail 5550 DMask = 0x1; 5551 DMaskLanes = 1; 5552 NumVDataDwords = 1; 5553 } 5554 NumVDataDwords += 1; 5555 AdjustRetType = true; 5556 } 5557 5558 // Has something earlier tagged that the return type needs adjusting 5559 // This happens if the instruction is a load or has set TexFailCtrl flags 5560 if (AdjustRetType) { 5561 // NumVDataDwords reflects the true number of dwords required in the return type 5562 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5563 // This is a no-op load. This can be eliminated 5564 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5565 if (isa<MemSDNode>(Op)) 5566 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5567 return Undef; 5568 } 5569 5570 EVT NewVT = NumVDataDwords > 1 ? 5571 EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords) 5572 : MVT::f32; 5573 5574 ResultTypes[0] = NewVT; 5575 if (ResultTypes.size() == 3) { 5576 // Original result was aggregate type used for TexFailCtrl results 5577 // The actual instruction returns as a vector type which has now been 5578 // created. Remove the aggregate result. 5579 ResultTypes.erase(&ResultTypes[1]); 5580 } 5581 } 5582 5583 SDValue GLC; 5584 SDValue SLC; 5585 SDValue DLC; 5586 if (BaseOpcode->Atomic) { 5587 GLC = True; // TODO no-return optimization 5588 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5589 IsGFX10 ? &DLC : nullptr)) 5590 return Op; 5591 } else { 5592 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5593 IsGFX10 ? &DLC : nullptr)) 5594 return Op; 5595 } 5596 5597 SmallVector<SDValue, 26> Ops; 5598 if (BaseOpcode->Store || BaseOpcode->Atomic) 5599 Ops.push_back(VData); // vdata 5600 if (UseNSA) { 5601 for (const SDValue &Addr : VAddrs) 5602 Ops.push_back(Addr); 5603 } else { 5604 Ops.push_back(VAddr); 5605 } 5606 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5607 if (BaseOpcode->Sampler) 5608 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5609 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5610 if (IsGFX10) 5611 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5612 Ops.push_back(Unorm); 5613 if (IsGFX10) 5614 Ops.push_back(DLC); 5615 Ops.push_back(GLC); 5616 Ops.push_back(SLC); 5617 Ops.push_back(IsA16 && // a16 or r128 5618 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5619 Ops.push_back(TFE); // tfe 5620 Ops.push_back(LWE); // lwe 5621 if (!IsGFX10) 5622 Ops.push_back(DimInfo->DA ? True : False); 5623 if (BaseOpcode->HasD16) 5624 Ops.push_back(IsD16 ? True : False); 5625 if (isa<MemSDNode>(Op)) 5626 Ops.push_back(Op.getOperand(0)); // chain 5627 5628 int NumVAddrDwords = 5629 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5630 int Opcode = -1; 5631 5632 if (IsGFX10) { 5633 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5634 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5635 : AMDGPU::MIMGEncGfx10Default, 5636 NumVDataDwords, NumVAddrDwords); 5637 } else { 5638 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5639 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5640 NumVDataDwords, NumVAddrDwords); 5641 if (Opcode == -1) 5642 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5643 NumVDataDwords, NumVAddrDwords); 5644 } 5645 assert(Opcode != -1); 5646 5647 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5648 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5649 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5650 DAG.setNodeMemRefs(NewNode, {MemRef}); 5651 } 5652 5653 if (BaseOpcode->AtomicX2) { 5654 SmallVector<SDValue, 1> Elt; 5655 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5656 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5657 } else if (!BaseOpcode->Store) { 5658 return constructRetValue(DAG, NewNode, 5659 OrigResultTypes, IsTexFail, 5660 Subtarget->hasUnpackedD16VMem(), IsD16, 5661 DMaskLanes, NumVDataDwords, DL, 5662 *DAG.getContext()); 5663 } 5664 5665 return SDValue(NewNode, 0); 5666 } 5667 5668 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5669 SDValue Offset, SDValue GLC, SDValue DLC, 5670 SelectionDAG &DAG) const { 5671 MachineFunction &MF = DAG.getMachineFunction(); 5672 5673 const DataLayout &DataLayout = DAG.getDataLayout(); 5674 unsigned Align = 5675 DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5676 5677 MachineMemOperand *MMO = MF.getMachineMemOperand( 5678 MachinePointerInfo(), 5679 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5680 MachineMemOperand::MOInvariant, 5681 VT.getStoreSize(), Align); 5682 5683 if (!Offset->isDivergent()) { 5684 SDValue Ops[] = { 5685 Rsrc, 5686 Offset, // Offset 5687 GLC, 5688 DLC, 5689 }; 5690 5691 // Widen vec3 load to vec4. 5692 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5693 EVT WidenedVT = 5694 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5695 auto WidenedOp = DAG.getMemIntrinsicNode( 5696 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5697 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5698 auto Subvector = DAG.getNode( 5699 ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5700 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 5701 return Subvector; 5702 } 5703 5704 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5705 DAG.getVTList(VT), Ops, VT, MMO); 5706 } 5707 5708 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5709 // assume that the buffer is unswizzled. 5710 SmallVector<SDValue, 4> Loads; 5711 unsigned NumLoads = 1; 5712 MVT LoadVT = VT.getSimpleVT(); 5713 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5714 assert((LoadVT.getScalarType() == MVT::i32 || 5715 LoadVT.getScalarType() == MVT::f32)); 5716 5717 if (NumElts == 8 || NumElts == 16) { 5718 NumLoads = NumElts / 4; 5719 LoadVT = MVT::v4i32; 5720 } 5721 5722 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5723 unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue(); 5724 SDValue Ops[] = { 5725 DAG.getEntryNode(), // Chain 5726 Rsrc, // rsrc 5727 DAG.getConstant(0, DL, MVT::i32), // vindex 5728 {}, // voffset 5729 {}, // soffset 5730 {}, // offset 5731 DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy 5732 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5733 }; 5734 5735 // Use the alignment to ensure that the required offsets will fit into the 5736 // immediate offsets. 5737 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5738 5739 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5740 for (unsigned i = 0; i < NumLoads; ++i) { 5741 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5742 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5743 LoadVT, MMO, DAG)); 5744 } 5745 5746 if (VT == MVT::v8i32 || VT == MVT::v16i32) 5747 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5748 5749 return Loads[0]; 5750 } 5751 5752 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5753 SelectionDAG &DAG) const { 5754 MachineFunction &MF = DAG.getMachineFunction(); 5755 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5756 5757 EVT VT = Op.getValueType(); 5758 SDLoc DL(Op); 5759 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5760 5761 // TODO: Should this propagate fast-math-flags? 5762 5763 switch (IntrinsicID) { 5764 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5765 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5766 return emitNonHSAIntrinsicError(DAG, DL, VT); 5767 return getPreloadedValue(DAG, *MFI, VT, 5768 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5769 } 5770 case Intrinsic::amdgcn_dispatch_ptr: 5771 case Intrinsic::amdgcn_queue_ptr: { 5772 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5773 DiagnosticInfoUnsupported BadIntrin( 5774 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5775 DL.getDebugLoc()); 5776 DAG.getContext()->diagnose(BadIntrin); 5777 return DAG.getUNDEF(VT); 5778 } 5779 5780 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5781 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5782 return getPreloadedValue(DAG, *MFI, VT, RegID); 5783 } 5784 case Intrinsic::amdgcn_implicitarg_ptr: { 5785 if (MFI->isEntryFunction()) 5786 return getImplicitArgPtr(DAG, DL); 5787 return getPreloadedValue(DAG, *MFI, VT, 5788 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5789 } 5790 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5791 return getPreloadedValue(DAG, *MFI, VT, 5792 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5793 } 5794 case Intrinsic::amdgcn_dispatch_id: { 5795 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5796 } 5797 case Intrinsic::amdgcn_rcp: 5798 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5799 case Intrinsic::amdgcn_rsq: 5800 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5801 case Intrinsic::amdgcn_rsq_legacy: 5802 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5803 return emitRemovedIntrinsicError(DAG, DL, VT); 5804 5805 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5806 case Intrinsic::amdgcn_rcp_legacy: 5807 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5808 return emitRemovedIntrinsicError(DAG, DL, VT); 5809 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5810 case Intrinsic::amdgcn_rsq_clamp: { 5811 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5812 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5813 5814 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5815 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5816 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5817 5818 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5819 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5820 DAG.getConstantFP(Max, DL, VT)); 5821 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5822 DAG.getConstantFP(Min, DL, VT)); 5823 } 5824 case Intrinsic::r600_read_ngroups_x: 5825 if (Subtarget->isAmdHsaOS()) 5826 return emitNonHSAIntrinsicError(DAG, DL, VT); 5827 5828 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5829 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5830 case Intrinsic::r600_read_ngroups_y: 5831 if (Subtarget->isAmdHsaOS()) 5832 return emitNonHSAIntrinsicError(DAG, DL, VT); 5833 5834 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5835 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5836 case Intrinsic::r600_read_ngroups_z: 5837 if (Subtarget->isAmdHsaOS()) 5838 return emitNonHSAIntrinsicError(DAG, DL, VT); 5839 5840 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5841 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5842 case Intrinsic::r600_read_global_size_x: 5843 if (Subtarget->isAmdHsaOS()) 5844 return emitNonHSAIntrinsicError(DAG, DL, VT); 5845 5846 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5847 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5848 case Intrinsic::r600_read_global_size_y: 5849 if (Subtarget->isAmdHsaOS()) 5850 return emitNonHSAIntrinsicError(DAG, DL, VT); 5851 5852 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5853 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5854 case Intrinsic::r600_read_global_size_z: 5855 if (Subtarget->isAmdHsaOS()) 5856 return emitNonHSAIntrinsicError(DAG, DL, VT); 5857 5858 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5859 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5860 case Intrinsic::r600_read_local_size_x: 5861 if (Subtarget->isAmdHsaOS()) 5862 return emitNonHSAIntrinsicError(DAG, DL, VT); 5863 5864 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5865 SI::KernelInputOffsets::LOCAL_SIZE_X); 5866 case Intrinsic::r600_read_local_size_y: 5867 if (Subtarget->isAmdHsaOS()) 5868 return emitNonHSAIntrinsicError(DAG, DL, VT); 5869 5870 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5871 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5872 case Intrinsic::r600_read_local_size_z: 5873 if (Subtarget->isAmdHsaOS()) 5874 return emitNonHSAIntrinsicError(DAG, DL, VT); 5875 5876 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5877 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5878 case Intrinsic::amdgcn_workgroup_id_x: 5879 case Intrinsic::r600_read_tgid_x: 5880 return getPreloadedValue(DAG, *MFI, VT, 5881 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5882 case Intrinsic::amdgcn_workgroup_id_y: 5883 case Intrinsic::r600_read_tgid_y: 5884 return getPreloadedValue(DAG, *MFI, VT, 5885 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5886 case Intrinsic::amdgcn_workgroup_id_z: 5887 case Intrinsic::r600_read_tgid_z: 5888 return getPreloadedValue(DAG, *MFI, VT, 5889 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5890 case Intrinsic::amdgcn_workitem_id_x: 5891 case Intrinsic::r600_read_tidig_x: 5892 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5893 SDLoc(DAG.getEntryNode()), 5894 MFI->getArgInfo().WorkItemIDX); 5895 case Intrinsic::amdgcn_workitem_id_y: 5896 case Intrinsic::r600_read_tidig_y: 5897 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5898 SDLoc(DAG.getEntryNode()), 5899 MFI->getArgInfo().WorkItemIDY); 5900 case Intrinsic::amdgcn_workitem_id_z: 5901 case Intrinsic::r600_read_tidig_z: 5902 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5903 SDLoc(DAG.getEntryNode()), 5904 MFI->getArgInfo().WorkItemIDZ); 5905 case Intrinsic::amdgcn_wavefrontsize: 5906 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5907 SDLoc(Op), MVT::i32); 5908 case Intrinsic::amdgcn_s_buffer_load: { 5909 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5910 SDValue GLC; 5911 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5912 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5913 IsGFX10 ? &DLC : nullptr)) 5914 return Op; 5915 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC, 5916 DAG); 5917 } 5918 case Intrinsic::amdgcn_fdiv_fast: 5919 return lowerFDIV_FAST(Op, DAG); 5920 case Intrinsic::amdgcn_interp_p1_f16: { 5921 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0, 5922 Op.getOperand(5), SDValue()); 5923 if (getSubtarget()->getLDSBankCount() == 16) { 5924 // 16 bank LDS 5925 5926 // FIXME: This implicitly will insert a second CopyToReg to M0. 5927 SDValue S = DAG.getNode( 5928 ISD::INTRINSIC_WO_CHAIN, DL, MVT::f32, 5929 DAG.getTargetConstant(Intrinsic::amdgcn_interp_mov, DL, MVT::i32), 5930 DAG.getConstant(2, DL, MVT::i32), // P0 5931 Op.getOperand(2), // Attrchan 5932 Op.getOperand(3), // Attr 5933 Op.getOperand(5)); // m0 5934 5935 SDValue Ops[] = { 5936 Op.getOperand(1), // Src0 5937 Op.getOperand(2), // Attrchan 5938 Op.getOperand(3), // Attr 5939 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5940 S, // Src2 - holds two f16 values selected by high 5941 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5942 Op.getOperand(4), // high 5943 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5944 DAG.getTargetConstant(0, DL, MVT::i32) // $omod 5945 }; 5946 return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops); 5947 } else { 5948 // 32 bank LDS 5949 SDValue Ops[] = { 5950 Op.getOperand(1), // Src0 5951 Op.getOperand(2), // Attrchan 5952 Op.getOperand(3), // Attr 5953 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5954 Op.getOperand(4), // high 5955 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5956 DAG.getTargetConstant(0, DL, MVT::i32), // $omod 5957 ToM0.getValue(1) 5958 }; 5959 return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops); 5960 } 5961 } 5962 case Intrinsic::amdgcn_interp_p2_f16: { 5963 SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0, 5964 Op.getOperand(6), SDValue()); 5965 SDValue Ops[] = { 5966 Op.getOperand(2), // Src0 5967 Op.getOperand(3), // Attrchan 5968 Op.getOperand(4), // Attr 5969 DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers 5970 Op.getOperand(1), // Src2 5971 DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers 5972 Op.getOperand(5), // high 5973 DAG.getTargetConstant(0, DL, MVT::i1), // $clamp 5974 ToM0.getValue(1) 5975 }; 5976 return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops); 5977 } 5978 case Intrinsic::amdgcn_sin: 5979 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5980 5981 case Intrinsic::amdgcn_cos: 5982 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5983 5984 case Intrinsic::amdgcn_mul_u24: 5985 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5986 case Intrinsic::amdgcn_mul_i24: 5987 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5988 5989 case Intrinsic::amdgcn_log_clamp: { 5990 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5991 return SDValue(); 5992 5993 DiagnosticInfoUnsupported BadIntrin( 5994 MF.getFunction(), "intrinsic not supported on subtarget", 5995 DL.getDebugLoc()); 5996 DAG.getContext()->diagnose(BadIntrin); 5997 return DAG.getUNDEF(VT); 5998 } 5999 case Intrinsic::amdgcn_ldexp: 6000 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6001 Op.getOperand(1), Op.getOperand(2)); 6002 6003 case Intrinsic::amdgcn_fract: 6004 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6005 6006 case Intrinsic::amdgcn_class: 6007 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6008 Op.getOperand(1), Op.getOperand(2)); 6009 case Intrinsic::amdgcn_div_fmas: 6010 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6011 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6012 Op.getOperand(4)); 6013 6014 case Intrinsic::amdgcn_div_fixup: 6015 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6016 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6017 6018 case Intrinsic::amdgcn_trig_preop: 6019 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 6020 Op.getOperand(1), Op.getOperand(2)); 6021 case Intrinsic::amdgcn_div_scale: { 6022 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6023 6024 // Translate to the operands expected by the machine instruction. The 6025 // first parameter must be the same as the first instruction. 6026 SDValue Numerator = Op.getOperand(1); 6027 SDValue Denominator = Op.getOperand(2); 6028 6029 // Note this order is opposite of the machine instruction's operations, 6030 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6031 // intrinsic has the numerator as the first operand to match a normal 6032 // division operation. 6033 6034 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6035 6036 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6037 Denominator, Numerator); 6038 } 6039 case Intrinsic::amdgcn_icmp: { 6040 // There is a Pat that handles this variant, so return it as-is. 6041 if (Op.getOperand(1).getValueType() == MVT::i1 && 6042 Op.getConstantOperandVal(2) == 0 && 6043 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6044 return Op; 6045 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6046 } 6047 case Intrinsic::amdgcn_fcmp: { 6048 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6049 } 6050 case Intrinsic::amdgcn_fmed3: 6051 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6052 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6053 case Intrinsic::amdgcn_fdot2: 6054 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6055 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6056 Op.getOperand(4)); 6057 case Intrinsic::amdgcn_fmul_legacy: 6058 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6059 Op.getOperand(1), Op.getOperand(2)); 6060 case Intrinsic::amdgcn_sffbh: 6061 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6062 case Intrinsic::amdgcn_sbfe: 6063 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6064 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6065 case Intrinsic::amdgcn_ubfe: 6066 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6067 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6068 case Intrinsic::amdgcn_cvt_pkrtz: 6069 case Intrinsic::amdgcn_cvt_pknorm_i16: 6070 case Intrinsic::amdgcn_cvt_pknorm_u16: 6071 case Intrinsic::amdgcn_cvt_pk_i16: 6072 case Intrinsic::amdgcn_cvt_pk_u16: { 6073 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6074 EVT VT = Op.getValueType(); 6075 unsigned Opcode; 6076 6077 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6078 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6079 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6080 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6081 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6082 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6083 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6084 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6085 else 6086 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6087 6088 if (isTypeLegal(VT)) 6089 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6090 6091 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6092 Op.getOperand(1), Op.getOperand(2)); 6093 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6094 } 6095 case Intrinsic::amdgcn_fmad_ftz: 6096 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6097 Op.getOperand(2), Op.getOperand(3)); 6098 6099 case Intrinsic::amdgcn_if_break: 6100 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6101 Op->getOperand(1), Op->getOperand(2)), 0); 6102 6103 case Intrinsic::amdgcn_groupstaticsize: { 6104 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6105 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6106 return Op; 6107 6108 const Module *M = MF.getFunction().getParent(); 6109 const GlobalValue *GV = 6110 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6111 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6112 SIInstrInfo::MO_ABS32_LO); 6113 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6114 } 6115 case Intrinsic::amdgcn_is_shared: 6116 case Intrinsic::amdgcn_is_private: { 6117 SDLoc SL(Op); 6118 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6119 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6120 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6121 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6122 Op.getOperand(1)); 6123 6124 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6125 DAG.getConstant(1, SL, MVT::i32)); 6126 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6127 } 6128 default: 6129 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6130 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6131 return lowerImage(Op, ImageDimIntr, DAG); 6132 6133 return Op; 6134 } 6135 } 6136 6137 // This function computes an appropriate offset to pass to 6138 // MachineMemOperand::setOffset() based on the offset inputs to 6139 // an intrinsic. If any of the offsets are non-contstant or 6140 // if VIndex is non-zero then this function returns 0. Otherwise, 6141 // it returns the sum of VOffset, SOffset, and Offset. 6142 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6143 SDValue SOffset, 6144 SDValue Offset, 6145 SDValue VIndex = SDValue()) { 6146 6147 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6148 !isa<ConstantSDNode>(Offset)) 6149 return 0; 6150 6151 if (VIndex) { 6152 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6153 return 0; 6154 } 6155 6156 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6157 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6158 cast<ConstantSDNode>(Offset)->getSExtValue(); 6159 } 6160 6161 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6162 SelectionDAG &DAG) const { 6163 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6164 SDLoc DL(Op); 6165 6166 switch (IntrID) { 6167 case Intrinsic::amdgcn_ds_ordered_add: 6168 case Intrinsic::amdgcn_ds_ordered_swap: { 6169 MemSDNode *M = cast<MemSDNode>(Op); 6170 SDValue Chain = M->getOperand(0); 6171 SDValue M0 = M->getOperand(2); 6172 SDValue Value = M->getOperand(3); 6173 unsigned IndexOperand = M->getConstantOperandVal(7); 6174 unsigned WaveRelease = M->getConstantOperandVal(8); 6175 unsigned WaveDone = M->getConstantOperandVal(9); 6176 unsigned ShaderType; 6177 unsigned Instruction; 6178 6179 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6180 IndexOperand &= ~0x3f; 6181 unsigned CountDw = 0; 6182 6183 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6184 CountDw = (IndexOperand >> 24) & 0xf; 6185 IndexOperand &= ~(0xf << 24); 6186 6187 if (CountDw < 1 || CountDw > 4) { 6188 report_fatal_error( 6189 "ds_ordered_count: dword count must be between 1 and 4"); 6190 } 6191 } 6192 6193 if (IndexOperand) 6194 report_fatal_error("ds_ordered_count: bad index operand"); 6195 6196 switch (IntrID) { 6197 case Intrinsic::amdgcn_ds_ordered_add: 6198 Instruction = 0; 6199 break; 6200 case Intrinsic::amdgcn_ds_ordered_swap: 6201 Instruction = 1; 6202 break; 6203 } 6204 6205 if (WaveDone && !WaveRelease) 6206 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6207 6208 switch (DAG.getMachineFunction().getFunction().getCallingConv()) { 6209 case CallingConv::AMDGPU_CS: 6210 case CallingConv::AMDGPU_KERNEL: 6211 ShaderType = 0; 6212 break; 6213 case CallingConv::AMDGPU_PS: 6214 ShaderType = 1; 6215 break; 6216 case CallingConv::AMDGPU_VS: 6217 ShaderType = 2; 6218 break; 6219 case CallingConv::AMDGPU_GS: 6220 ShaderType = 3; 6221 break; 6222 default: 6223 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6224 } 6225 6226 unsigned Offset0 = OrderedCountIndex << 2; 6227 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6228 (Instruction << 4); 6229 6230 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6231 Offset1 |= (CountDw - 1) << 6; 6232 6233 unsigned Offset = Offset0 | (Offset1 << 8); 6234 6235 SDValue Ops[] = { 6236 Chain, 6237 Value, 6238 DAG.getTargetConstant(Offset, DL, MVT::i16), 6239 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6240 }; 6241 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6242 M->getVTList(), Ops, M->getMemoryVT(), 6243 M->getMemOperand()); 6244 } 6245 case Intrinsic::amdgcn_ds_fadd: { 6246 MemSDNode *M = cast<MemSDNode>(Op); 6247 unsigned Opc; 6248 switch (IntrID) { 6249 case Intrinsic::amdgcn_ds_fadd: 6250 Opc = ISD::ATOMIC_LOAD_FADD; 6251 break; 6252 } 6253 6254 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6255 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6256 M->getMemOperand()); 6257 } 6258 case Intrinsic::amdgcn_atomic_inc: 6259 case Intrinsic::amdgcn_atomic_dec: 6260 case Intrinsic::amdgcn_ds_fmin: 6261 case Intrinsic::amdgcn_ds_fmax: { 6262 MemSDNode *M = cast<MemSDNode>(Op); 6263 unsigned Opc; 6264 switch (IntrID) { 6265 case Intrinsic::amdgcn_atomic_inc: 6266 Opc = AMDGPUISD::ATOMIC_INC; 6267 break; 6268 case Intrinsic::amdgcn_atomic_dec: 6269 Opc = AMDGPUISD::ATOMIC_DEC; 6270 break; 6271 case Intrinsic::amdgcn_ds_fmin: 6272 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6273 break; 6274 case Intrinsic::amdgcn_ds_fmax: 6275 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6276 break; 6277 default: 6278 llvm_unreachable("Unknown intrinsic!"); 6279 } 6280 SDValue Ops[] = { 6281 M->getOperand(0), // Chain 6282 M->getOperand(2), // Ptr 6283 M->getOperand(3) // Value 6284 }; 6285 6286 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6287 M->getMemoryVT(), M->getMemOperand()); 6288 } 6289 case Intrinsic::amdgcn_buffer_load: 6290 case Intrinsic::amdgcn_buffer_load_format: { 6291 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6292 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6293 unsigned IdxEn = 1; 6294 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6295 IdxEn = Idx->getZExtValue() != 0; 6296 SDValue Ops[] = { 6297 Op.getOperand(0), // Chain 6298 Op.getOperand(2), // rsrc 6299 Op.getOperand(3), // vindex 6300 SDValue(), // voffset -- will be set by setBufferOffsets 6301 SDValue(), // soffset -- will be set by setBufferOffsets 6302 SDValue(), // offset -- will be set by setBufferOffsets 6303 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6304 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6305 }; 6306 6307 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6308 // We don't know the offset if vindex is non-zero, so clear it. 6309 if (IdxEn) 6310 Offset = 0; 6311 6312 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6313 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6314 6315 EVT VT = Op.getValueType(); 6316 EVT IntVT = VT.changeTypeToInteger(); 6317 auto *M = cast<MemSDNode>(Op); 6318 M->getMemOperand()->setOffset(Offset); 6319 EVT LoadVT = Op.getValueType(); 6320 6321 if (LoadVT.getScalarType() == MVT::f16) 6322 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6323 M, DAG, Ops); 6324 6325 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6326 if (LoadVT.getScalarType() == MVT::i8 || 6327 LoadVT.getScalarType() == MVT::i16) 6328 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6329 6330 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6331 M->getMemOperand(), DAG); 6332 } 6333 case Intrinsic::amdgcn_raw_buffer_load: 6334 case Intrinsic::amdgcn_raw_buffer_load_format: { 6335 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6336 6337 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6338 SDValue Ops[] = { 6339 Op.getOperand(0), // Chain 6340 Op.getOperand(2), // rsrc 6341 DAG.getConstant(0, DL, MVT::i32), // vindex 6342 Offsets.first, // voffset 6343 Op.getOperand(4), // soffset 6344 Offsets.second, // offset 6345 Op.getOperand(5), // cachepolicy, swizzled buffer 6346 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6347 }; 6348 6349 auto *M = cast<MemSDNode>(Op); 6350 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6351 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6352 } 6353 case Intrinsic::amdgcn_struct_buffer_load: 6354 case Intrinsic::amdgcn_struct_buffer_load_format: { 6355 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6356 6357 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6358 SDValue Ops[] = { 6359 Op.getOperand(0), // Chain 6360 Op.getOperand(2), // rsrc 6361 Op.getOperand(3), // vindex 6362 Offsets.first, // voffset 6363 Op.getOperand(5), // soffset 6364 Offsets.second, // offset 6365 Op.getOperand(6), // cachepolicy, swizzled buffer 6366 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6367 }; 6368 6369 auto *M = cast<MemSDNode>(Op); 6370 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6371 Ops[2])); 6372 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6373 } 6374 case Intrinsic::amdgcn_tbuffer_load: { 6375 MemSDNode *M = cast<MemSDNode>(Op); 6376 EVT LoadVT = Op.getValueType(); 6377 6378 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6379 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6380 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6381 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6382 unsigned IdxEn = 1; 6383 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6384 IdxEn = Idx->getZExtValue() != 0; 6385 SDValue Ops[] = { 6386 Op.getOperand(0), // Chain 6387 Op.getOperand(2), // rsrc 6388 Op.getOperand(3), // vindex 6389 Op.getOperand(4), // voffset 6390 Op.getOperand(5), // soffset 6391 Op.getOperand(6), // offset 6392 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6393 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6394 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6395 }; 6396 6397 if (LoadVT.getScalarType() == MVT::f16) 6398 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6399 M, DAG, Ops); 6400 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6401 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6402 DAG); 6403 } 6404 case Intrinsic::amdgcn_raw_tbuffer_load: { 6405 MemSDNode *M = cast<MemSDNode>(Op); 6406 EVT LoadVT = Op.getValueType(); 6407 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6408 6409 SDValue Ops[] = { 6410 Op.getOperand(0), // Chain 6411 Op.getOperand(2), // rsrc 6412 DAG.getConstant(0, DL, MVT::i32), // vindex 6413 Offsets.first, // voffset 6414 Op.getOperand(4), // soffset 6415 Offsets.second, // offset 6416 Op.getOperand(5), // format 6417 Op.getOperand(6), // cachepolicy, swizzled buffer 6418 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6419 }; 6420 6421 if (LoadVT.getScalarType() == MVT::f16) 6422 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6423 M, DAG, Ops); 6424 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6425 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6426 DAG); 6427 } 6428 case Intrinsic::amdgcn_struct_tbuffer_load: { 6429 MemSDNode *M = cast<MemSDNode>(Op); 6430 EVT LoadVT = Op.getValueType(); 6431 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6432 6433 SDValue Ops[] = { 6434 Op.getOperand(0), // Chain 6435 Op.getOperand(2), // rsrc 6436 Op.getOperand(3), // vindex 6437 Offsets.first, // voffset 6438 Op.getOperand(5), // soffset 6439 Offsets.second, // offset 6440 Op.getOperand(6), // format 6441 Op.getOperand(7), // cachepolicy, swizzled buffer 6442 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6443 }; 6444 6445 if (LoadVT.getScalarType() == MVT::f16) 6446 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6447 M, DAG, Ops); 6448 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6449 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6450 DAG); 6451 } 6452 case Intrinsic::amdgcn_buffer_atomic_swap: 6453 case Intrinsic::amdgcn_buffer_atomic_add: 6454 case Intrinsic::amdgcn_buffer_atomic_sub: 6455 case Intrinsic::amdgcn_buffer_atomic_smin: 6456 case Intrinsic::amdgcn_buffer_atomic_umin: 6457 case Intrinsic::amdgcn_buffer_atomic_smax: 6458 case Intrinsic::amdgcn_buffer_atomic_umax: 6459 case Intrinsic::amdgcn_buffer_atomic_and: 6460 case Intrinsic::amdgcn_buffer_atomic_or: 6461 case Intrinsic::amdgcn_buffer_atomic_xor: { 6462 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6463 unsigned IdxEn = 1; 6464 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6465 IdxEn = Idx->getZExtValue() != 0; 6466 SDValue Ops[] = { 6467 Op.getOperand(0), // Chain 6468 Op.getOperand(2), // vdata 6469 Op.getOperand(3), // rsrc 6470 Op.getOperand(4), // vindex 6471 SDValue(), // voffset -- will be set by setBufferOffsets 6472 SDValue(), // soffset -- will be set by setBufferOffsets 6473 SDValue(), // offset -- will be set by setBufferOffsets 6474 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6475 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6476 }; 6477 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6478 // We don't know the offset if vindex is non-zero, so clear it. 6479 if (IdxEn) 6480 Offset = 0; 6481 EVT VT = Op.getValueType(); 6482 6483 auto *M = cast<MemSDNode>(Op); 6484 M->getMemOperand()->setOffset(Offset); 6485 unsigned Opcode = 0; 6486 6487 switch (IntrID) { 6488 case Intrinsic::amdgcn_buffer_atomic_swap: 6489 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6490 break; 6491 case Intrinsic::amdgcn_buffer_atomic_add: 6492 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6493 break; 6494 case Intrinsic::amdgcn_buffer_atomic_sub: 6495 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6496 break; 6497 case Intrinsic::amdgcn_buffer_atomic_smin: 6498 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6499 break; 6500 case Intrinsic::amdgcn_buffer_atomic_umin: 6501 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6502 break; 6503 case Intrinsic::amdgcn_buffer_atomic_smax: 6504 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6505 break; 6506 case Intrinsic::amdgcn_buffer_atomic_umax: 6507 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6508 break; 6509 case Intrinsic::amdgcn_buffer_atomic_and: 6510 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6511 break; 6512 case Intrinsic::amdgcn_buffer_atomic_or: 6513 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6514 break; 6515 case Intrinsic::amdgcn_buffer_atomic_xor: 6516 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6517 break; 6518 default: 6519 llvm_unreachable("unhandled atomic opcode"); 6520 } 6521 6522 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6523 M->getMemOperand()); 6524 } 6525 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6526 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6527 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6528 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6529 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6530 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6531 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6532 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6533 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6534 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6535 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6536 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6537 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6538 SDValue Ops[] = { 6539 Op.getOperand(0), // Chain 6540 Op.getOperand(2), // vdata 6541 Op.getOperand(3), // rsrc 6542 DAG.getConstant(0, DL, MVT::i32), // vindex 6543 Offsets.first, // voffset 6544 Op.getOperand(5), // soffset 6545 Offsets.second, // offset 6546 Op.getOperand(6), // cachepolicy 6547 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6548 }; 6549 EVT VT = Op.getValueType(); 6550 6551 auto *M = cast<MemSDNode>(Op); 6552 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6553 unsigned Opcode = 0; 6554 6555 switch (IntrID) { 6556 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6557 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6558 break; 6559 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6560 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6561 break; 6562 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6563 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6564 break; 6565 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6566 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6567 break; 6568 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6569 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6570 break; 6571 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6572 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6573 break; 6574 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6575 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6576 break; 6577 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6578 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6579 break; 6580 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6581 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6582 break; 6583 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6584 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6585 break; 6586 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6587 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6588 break; 6589 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6590 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6591 break; 6592 default: 6593 llvm_unreachable("unhandled atomic opcode"); 6594 } 6595 6596 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6597 M->getMemOperand()); 6598 } 6599 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6600 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6601 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6602 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6603 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6604 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6605 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6606 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6607 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6608 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6609 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6610 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6611 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6612 SDValue Ops[] = { 6613 Op.getOperand(0), // Chain 6614 Op.getOperand(2), // vdata 6615 Op.getOperand(3), // rsrc 6616 Op.getOperand(4), // vindex 6617 Offsets.first, // voffset 6618 Op.getOperand(6), // soffset 6619 Offsets.second, // offset 6620 Op.getOperand(7), // cachepolicy 6621 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6622 }; 6623 EVT VT = Op.getValueType(); 6624 6625 auto *M = cast<MemSDNode>(Op); 6626 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6627 Ops[3])); 6628 unsigned Opcode = 0; 6629 6630 switch (IntrID) { 6631 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6632 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6633 break; 6634 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6635 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6636 break; 6637 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6638 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6639 break; 6640 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6641 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6642 break; 6643 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6644 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6645 break; 6646 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6647 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6648 break; 6649 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6650 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6651 break; 6652 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6653 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6654 break; 6655 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6656 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6657 break; 6658 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6659 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6660 break; 6661 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6662 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6663 break; 6664 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6665 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6666 break; 6667 default: 6668 llvm_unreachable("unhandled atomic opcode"); 6669 } 6670 6671 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6672 M->getMemOperand()); 6673 } 6674 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6675 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6676 unsigned IdxEn = 1; 6677 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6678 IdxEn = Idx->getZExtValue() != 0; 6679 SDValue Ops[] = { 6680 Op.getOperand(0), // Chain 6681 Op.getOperand(2), // src 6682 Op.getOperand(3), // cmp 6683 Op.getOperand(4), // rsrc 6684 Op.getOperand(5), // vindex 6685 SDValue(), // voffset -- will be set by setBufferOffsets 6686 SDValue(), // soffset -- will be set by setBufferOffsets 6687 SDValue(), // offset -- will be set by setBufferOffsets 6688 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6689 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6690 }; 6691 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6692 // We don't know the offset if vindex is non-zero, so clear it. 6693 if (IdxEn) 6694 Offset = 0; 6695 EVT VT = Op.getValueType(); 6696 auto *M = cast<MemSDNode>(Op); 6697 M->getMemOperand()->setOffset(Offset); 6698 6699 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6700 Op->getVTList(), Ops, VT, M->getMemOperand()); 6701 } 6702 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6703 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6704 SDValue Ops[] = { 6705 Op.getOperand(0), // Chain 6706 Op.getOperand(2), // src 6707 Op.getOperand(3), // cmp 6708 Op.getOperand(4), // rsrc 6709 DAG.getConstant(0, DL, MVT::i32), // vindex 6710 Offsets.first, // voffset 6711 Op.getOperand(6), // soffset 6712 Offsets.second, // offset 6713 Op.getOperand(7), // cachepolicy 6714 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6715 }; 6716 EVT VT = Op.getValueType(); 6717 auto *M = cast<MemSDNode>(Op); 6718 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6719 6720 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6721 Op->getVTList(), Ops, VT, M->getMemOperand()); 6722 } 6723 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6724 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6725 SDValue Ops[] = { 6726 Op.getOperand(0), // Chain 6727 Op.getOperand(2), // src 6728 Op.getOperand(3), // cmp 6729 Op.getOperand(4), // rsrc 6730 Op.getOperand(5), // vindex 6731 Offsets.first, // voffset 6732 Op.getOperand(7), // soffset 6733 Offsets.second, // offset 6734 Op.getOperand(8), // cachepolicy 6735 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6736 }; 6737 EVT VT = Op.getValueType(); 6738 auto *M = cast<MemSDNode>(Op); 6739 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6740 Ops[4])); 6741 6742 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6743 Op->getVTList(), Ops, VT, M->getMemOperand()); 6744 } 6745 6746 default: 6747 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6748 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6749 return lowerImage(Op, ImageDimIntr, DAG); 6750 6751 return SDValue(); 6752 } 6753 } 6754 6755 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6756 // dwordx4 if on SI. 6757 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6758 SDVTList VTList, 6759 ArrayRef<SDValue> Ops, EVT MemVT, 6760 MachineMemOperand *MMO, 6761 SelectionDAG &DAG) const { 6762 EVT VT = VTList.VTs[0]; 6763 EVT WidenedVT = VT; 6764 EVT WidenedMemVT = MemVT; 6765 if (!Subtarget->hasDwordx3LoadStores() && 6766 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6767 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6768 WidenedVT.getVectorElementType(), 4); 6769 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6770 WidenedMemVT.getVectorElementType(), 4); 6771 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6772 } 6773 6774 assert(VTList.NumVTs == 2); 6775 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6776 6777 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6778 WidenedMemVT, MMO); 6779 if (WidenedVT != VT) { 6780 auto Extract = DAG.getNode( 6781 ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6782 DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout()))); 6783 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6784 } 6785 return NewOp; 6786 } 6787 6788 SDValue SITargetLowering::handleD16VData(SDValue VData, 6789 SelectionDAG &DAG) const { 6790 EVT StoreVT = VData.getValueType(); 6791 6792 // No change for f16 and legal vector D16 types. 6793 if (!StoreVT.isVector()) 6794 return VData; 6795 6796 SDLoc DL(VData); 6797 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6798 6799 if (Subtarget->hasUnpackedD16VMem()) { 6800 // We need to unpack the packed data to store. 6801 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6802 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6803 6804 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6805 StoreVT.getVectorNumElements()); 6806 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6807 return DAG.UnrollVectorOp(ZExt.getNode()); 6808 } 6809 6810 assert(isTypeLegal(StoreVT)); 6811 return VData; 6812 } 6813 6814 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6815 SelectionDAG &DAG) const { 6816 SDLoc DL(Op); 6817 SDValue Chain = Op.getOperand(0); 6818 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6819 MachineFunction &MF = DAG.getMachineFunction(); 6820 6821 switch (IntrinsicID) { 6822 case Intrinsic::amdgcn_exp: { 6823 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6824 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6825 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8)); 6826 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9)); 6827 6828 const SDValue Ops[] = { 6829 Chain, 6830 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6831 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6832 Op.getOperand(4), // src0 6833 Op.getOperand(5), // src1 6834 Op.getOperand(6), // src2 6835 Op.getOperand(7), // src3 6836 DAG.getTargetConstant(0, DL, MVT::i1), // compr 6837 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6838 }; 6839 6840 unsigned Opc = Done->isNullValue() ? 6841 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6842 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6843 } 6844 case Intrinsic::amdgcn_exp_compr: { 6845 const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2)); 6846 const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3)); 6847 SDValue Src0 = Op.getOperand(4); 6848 SDValue Src1 = Op.getOperand(5); 6849 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6850 const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7)); 6851 6852 SDValue Undef = DAG.getUNDEF(MVT::f32); 6853 const SDValue Ops[] = { 6854 Chain, 6855 DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt 6856 DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8), // en 6857 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), 6858 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), 6859 Undef, // src2 6860 Undef, // src3 6861 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6862 DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1) 6863 }; 6864 6865 unsigned Opc = Done->isNullValue() ? 6866 AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE; 6867 return DAG.getNode(Opc, DL, Op->getVTList(), Ops); 6868 } 6869 case Intrinsic::amdgcn_s_barrier: { 6870 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6871 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6872 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6873 if (WGSize <= ST.getWavefrontSize()) 6874 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6875 Op.getOperand(0)), 0); 6876 } 6877 return SDValue(); 6878 }; 6879 case Intrinsic::amdgcn_tbuffer_store: { 6880 SDValue VData = Op.getOperand(2); 6881 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6882 if (IsD16) 6883 VData = handleD16VData(VData, DAG); 6884 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6885 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6886 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6887 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6888 unsigned IdxEn = 1; 6889 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6890 IdxEn = Idx->getZExtValue() != 0; 6891 SDValue Ops[] = { 6892 Chain, 6893 VData, // vdata 6894 Op.getOperand(3), // rsrc 6895 Op.getOperand(4), // vindex 6896 Op.getOperand(5), // voffset 6897 Op.getOperand(6), // soffset 6898 Op.getOperand(7), // offset 6899 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6900 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6901 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6902 }; 6903 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6904 AMDGPUISD::TBUFFER_STORE_FORMAT; 6905 MemSDNode *M = cast<MemSDNode>(Op); 6906 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6907 M->getMemoryVT(), M->getMemOperand()); 6908 } 6909 6910 case Intrinsic::amdgcn_struct_tbuffer_store: { 6911 SDValue VData = Op.getOperand(2); 6912 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6913 if (IsD16) 6914 VData = handleD16VData(VData, DAG); 6915 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6916 SDValue Ops[] = { 6917 Chain, 6918 VData, // vdata 6919 Op.getOperand(3), // rsrc 6920 Op.getOperand(4), // vindex 6921 Offsets.first, // voffset 6922 Op.getOperand(6), // soffset 6923 Offsets.second, // offset 6924 Op.getOperand(7), // format 6925 Op.getOperand(8), // cachepolicy, swizzled buffer 6926 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6927 }; 6928 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6929 AMDGPUISD::TBUFFER_STORE_FORMAT; 6930 MemSDNode *M = cast<MemSDNode>(Op); 6931 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6932 M->getMemoryVT(), M->getMemOperand()); 6933 } 6934 6935 case Intrinsic::amdgcn_raw_tbuffer_store: { 6936 SDValue VData = Op.getOperand(2); 6937 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6938 if (IsD16) 6939 VData = handleD16VData(VData, DAG); 6940 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6941 SDValue Ops[] = { 6942 Chain, 6943 VData, // vdata 6944 Op.getOperand(3), // rsrc 6945 DAG.getConstant(0, DL, MVT::i32), // vindex 6946 Offsets.first, // voffset 6947 Op.getOperand(5), // soffset 6948 Offsets.second, // offset 6949 Op.getOperand(6), // format 6950 Op.getOperand(7), // cachepolicy, swizzled buffer 6951 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6952 }; 6953 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6954 AMDGPUISD::TBUFFER_STORE_FORMAT; 6955 MemSDNode *M = cast<MemSDNode>(Op); 6956 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6957 M->getMemoryVT(), M->getMemOperand()); 6958 } 6959 6960 case Intrinsic::amdgcn_buffer_store: 6961 case Intrinsic::amdgcn_buffer_store_format: { 6962 SDValue VData = Op.getOperand(2); 6963 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6964 if (IsD16) 6965 VData = handleD16VData(VData, DAG); 6966 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6967 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6968 unsigned IdxEn = 1; 6969 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6970 IdxEn = Idx->getZExtValue() != 0; 6971 SDValue Ops[] = { 6972 Chain, 6973 VData, 6974 Op.getOperand(3), // rsrc 6975 Op.getOperand(4), // vindex 6976 SDValue(), // voffset -- will be set by setBufferOffsets 6977 SDValue(), // soffset -- will be set by setBufferOffsets 6978 SDValue(), // offset -- will be set by setBufferOffsets 6979 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6980 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6981 }; 6982 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6983 // We don't know the offset if vindex is non-zero, so clear it. 6984 if (IdxEn) 6985 Offset = 0; 6986 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6987 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6988 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6989 MemSDNode *M = cast<MemSDNode>(Op); 6990 M->getMemOperand()->setOffset(Offset); 6991 6992 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6993 EVT VDataType = VData.getValueType().getScalarType(); 6994 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6995 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6996 6997 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6998 M->getMemoryVT(), M->getMemOperand()); 6999 } 7000 7001 case Intrinsic::amdgcn_raw_buffer_store: 7002 case Intrinsic::amdgcn_raw_buffer_store_format: { 7003 const bool IsFormat = 7004 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7005 7006 SDValue VData = Op.getOperand(2); 7007 EVT VDataVT = VData.getValueType(); 7008 EVT EltType = VDataVT.getScalarType(); 7009 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7010 if (IsD16) 7011 VData = handleD16VData(VData, DAG); 7012 7013 if (!isTypeLegal(VDataVT)) { 7014 VData = 7015 DAG.getNode(ISD::BITCAST, DL, 7016 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7017 } 7018 7019 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7020 SDValue Ops[] = { 7021 Chain, 7022 VData, 7023 Op.getOperand(3), // rsrc 7024 DAG.getConstant(0, DL, MVT::i32), // vindex 7025 Offsets.first, // voffset 7026 Op.getOperand(5), // soffset 7027 Offsets.second, // offset 7028 Op.getOperand(6), // cachepolicy, swizzled buffer 7029 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7030 }; 7031 unsigned Opc = 7032 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7033 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7034 MemSDNode *M = cast<MemSDNode>(Op); 7035 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7036 7037 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7038 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7039 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7040 7041 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7042 M->getMemoryVT(), M->getMemOperand()); 7043 } 7044 7045 case Intrinsic::amdgcn_struct_buffer_store: 7046 case Intrinsic::amdgcn_struct_buffer_store_format: { 7047 const bool IsFormat = 7048 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7049 7050 SDValue VData = Op.getOperand(2); 7051 EVT VDataVT = VData.getValueType(); 7052 EVT EltType = VDataVT.getScalarType(); 7053 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7054 7055 if (IsD16) 7056 VData = handleD16VData(VData, DAG); 7057 7058 if (!isTypeLegal(VDataVT)) { 7059 VData = 7060 DAG.getNode(ISD::BITCAST, DL, 7061 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7062 } 7063 7064 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7065 SDValue Ops[] = { 7066 Chain, 7067 VData, 7068 Op.getOperand(3), // rsrc 7069 Op.getOperand(4), // vindex 7070 Offsets.first, // voffset 7071 Op.getOperand(6), // soffset 7072 Offsets.second, // offset 7073 Op.getOperand(7), // cachepolicy, swizzled buffer 7074 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7075 }; 7076 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7077 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7078 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7079 MemSDNode *M = cast<MemSDNode>(Op); 7080 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7081 Ops[3])); 7082 7083 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7084 EVT VDataType = VData.getValueType().getScalarType(); 7085 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7086 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7087 7088 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7089 M->getMemoryVT(), M->getMemOperand()); 7090 } 7091 7092 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7093 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7094 unsigned IdxEn = 1; 7095 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7096 IdxEn = Idx->getZExtValue() != 0; 7097 SDValue Ops[] = { 7098 Chain, 7099 Op.getOperand(2), // vdata 7100 Op.getOperand(3), // rsrc 7101 Op.getOperand(4), // vindex 7102 SDValue(), // voffset -- will be set by setBufferOffsets 7103 SDValue(), // soffset -- will be set by setBufferOffsets 7104 SDValue(), // offset -- will be set by setBufferOffsets 7105 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7106 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7107 }; 7108 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7109 // We don't know the offset if vindex is non-zero, so clear it. 7110 if (IdxEn) 7111 Offset = 0; 7112 EVT VT = Op.getOperand(2).getValueType(); 7113 7114 auto *M = cast<MemSDNode>(Op); 7115 M->getMemOperand()->setOffset(Offset); 7116 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 7117 : AMDGPUISD::BUFFER_ATOMIC_FADD; 7118 7119 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7120 M->getMemOperand()); 7121 } 7122 7123 case Intrinsic::amdgcn_global_atomic_fadd: { 7124 SDValue Ops[] = { 7125 Chain, 7126 Op.getOperand(2), // ptr 7127 Op.getOperand(3) // vdata 7128 }; 7129 EVT VT = Op.getOperand(3).getValueType(); 7130 7131 auto *M = cast<MemSDNode>(Op); 7132 if (VT.isVector()) { 7133 return DAG.getMemIntrinsicNode( 7134 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7135 M->getMemOperand()); 7136 } 7137 7138 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7139 DAG.getVTList(VT, MVT::Other), Ops, 7140 M->getMemOperand()).getValue(1); 7141 } 7142 case Intrinsic::amdgcn_end_cf: 7143 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7144 Op->getOperand(2), Chain), 0); 7145 7146 default: { 7147 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7148 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7149 return lowerImage(Op, ImageDimIntr, DAG); 7150 7151 return Op; 7152 } 7153 } 7154 } 7155 7156 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7157 // offset (the offset that is included in bounds checking and swizzling, to be 7158 // split between the instruction's voffset and immoffset fields) and soffset 7159 // (the offset that is excluded from bounds checking and swizzling, to go in 7160 // the instruction's soffset field). This function takes the first kind of 7161 // offset and figures out how to split it between voffset and immoffset. 7162 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7163 SDValue Offset, SelectionDAG &DAG) const { 7164 SDLoc DL(Offset); 7165 const unsigned MaxImm = 4095; 7166 SDValue N0 = Offset; 7167 ConstantSDNode *C1 = nullptr; 7168 7169 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7170 N0 = SDValue(); 7171 else if (DAG.isBaseWithConstantOffset(N0)) { 7172 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7173 N0 = N0.getOperand(0); 7174 } 7175 7176 if (C1) { 7177 unsigned ImmOffset = C1->getZExtValue(); 7178 // If the immediate value is too big for the immoffset field, put the value 7179 // and -4096 into the immoffset field so that the value that is copied/added 7180 // for the voffset field is a multiple of 4096, and it stands more chance 7181 // of being CSEd with the copy/add for another similar load/store. 7182 // However, do not do that rounding down to a multiple of 4096 if that is a 7183 // negative number, as it appears to be illegal to have a negative offset 7184 // in the vgpr, even if adding the immediate offset makes it positive. 7185 unsigned Overflow = ImmOffset & ~MaxImm; 7186 ImmOffset -= Overflow; 7187 if ((int32_t)Overflow < 0) { 7188 Overflow += ImmOffset; 7189 ImmOffset = 0; 7190 } 7191 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7192 if (Overflow) { 7193 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7194 if (!N0) 7195 N0 = OverflowVal; 7196 else { 7197 SDValue Ops[] = { N0, OverflowVal }; 7198 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7199 } 7200 } 7201 } 7202 if (!N0) 7203 N0 = DAG.getConstant(0, DL, MVT::i32); 7204 if (!C1) 7205 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7206 return {N0, SDValue(C1, 0)}; 7207 } 7208 7209 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7210 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7211 // pointed to by Offsets. 7212 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7213 SelectionDAG &DAG, SDValue *Offsets, 7214 unsigned Align) const { 7215 SDLoc DL(CombinedOffset); 7216 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7217 uint32_t Imm = C->getZExtValue(); 7218 uint32_t SOffset, ImmOffset; 7219 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7220 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7221 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7222 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7223 return SOffset + ImmOffset; 7224 } 7225 } 7226 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7227 SDValue N0 = CombinedOffset.getOperand(0); 7228 SDValue N1 = CombinedOffset.getOperand(1); 7229 uint32_t SOffset, ImmOffset; 7230 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7231 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7232 Subtarget, Align)) { 7233 Offsets[0] = N0; 7234 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7235 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7236 return 0; 7237 } 7238 } 7239 Offsets[0] = CombinedOffset; 7240 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7241 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7242 return 0; 7243 } 7244 7245 // Handle 8 bit and 16 bit buffer loads 7246 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7247 EVT LoadVT, SDLoc DL, 7248 ArrayRef<SDValue> Ops, 7249 MemSDNode *M) const { 7250 EVT IntVT = LoadVT.changeTypeToInteger(); 7251 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7252 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7253 7254 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7255 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7256 Ops, IntVT, 7257 M->getMemOperand()); 7258 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7259 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7260 7261 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7262 } 7263 7264 // Handle 8 bit and 16 bit buffer stores 7265 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7266 EVT VDataType, SDLoc DL, 7267 SDValue Ops[], 7268 MemSDNode *M) const { 7269 if (VDataType == MVT::f16) 7270 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7271 7272 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7273 Ops[1] = BufferStoreExt; 7274 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7275 AMDGPUISD::BUFFER_STORE_SHORT; 7276 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7277 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7278 M->getMemOperand()); 7279 } 7280 7281 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7282 ISD::LoadExtType ExtType, SDValue Op, 7283 const SDLoc &SL, EVT VT) { 7284 if (VT.bitsLT(Op.getValueType())) 7285 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7286 7287 switch (ExtType) { 7288 case ISD::SEXTLOAD: 7289 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7290 case ISD::ZEXTLOAD: 7291 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7292 case ISD::EXTLOAD: 7293 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7294 case ISD::NON_EXTLOAD: 7295 return Op; 7296 } 7297 7298 llvm_unreachable("invalid ext type"); 7299 } 7300 7301 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7302 SelectionDAG &DAG = DCI.DAG; 7303 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7304 return SDValue(); 7305 7306 // FIXME: Constant loads should all be marked invariant. 7307 unsigned AS = Ld->getAddressSpace(); 7308 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7309 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7310 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7311 return SDValue(); 7312 7313 // Don't do this early, since it may interfere with adjacent load merging for 7314 // illegal types. We can avoid losing alignment information for exotic types 7315 // pre-legalize. 7316 EVT MemVT = Ld->getMemoryVT(); 7317 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7318 MemVT.getSizeInBits() >= 32) 7319 return SDValue(); 7320 7321 SDLoc SL(Ld); 7322 7323 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7324 "unexpected vector extload"); 7325 7326 // TODO: Drop only high part of range. 7327 SDValue Ptr = Ld->getBasePtr(); 7328 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7329 MVT::i32, SL, Ld->getChain(), Ptr, 7330 Ld->getOffset(), 7331 Ld->getPointerInfo(), MVT::i32, 7332 Ld->getAlignment(), 7333 Ld->getMemOperand()->getFlags(), 7334 Ld->getAAInfo(), 7335 nullptr); // Drop ranges 7336 7337 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7338 if (MemVT.isFloatingPoint()) { 7339 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7340 "unexpected fp extload"); 7341 TruncVT = MemVT.changeTypeToInteger(); 7342 } 7343 7344 SDValue Cvt = NewLoad; 7345 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7346 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7347 DAG.getValueType(TruncVT)); 7348 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7349 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7350 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7351 } else { 7352 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7353 } 7354 7355 EVT VT = Ld->getValueType(0); 7356 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7357 7358 DCI.AddToWorklist(Cvt.getNode()); 7359 7360 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7361 // the appropriate extension from the 32-bit load. 7362 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7363 DCI.AddToWorklist(Cvt.getNode()); 7364 7365 // Handle conversion back to floating point if necessary. 7366 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7367 7368 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7369 } 7370 7371 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7372 SDLoc DL(Op); 7373 LoadSDNode *Load = cast<LoadSDNode>(Op); 7374 ISD::LoadExtType ExtType = Load->getExtensionType(); 7375 EVT MemVT = Load->getMemoryVT(); 7376 7377 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7378 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7379 return SDValue(); 7380 7381 // FIXME: Copied from PPC 7382 // First, load into 32 bits, then truncate to 1 bit. 7383 7384 SDValue Chain = Load->getChain(); 7385 SDValue BasePtr = Load->getBasePtr(); 7386 MachineMemOperand *MMO = Load->getMemOperand(); 7387 7388 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7389 7390 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7391 BasePtr, RealMemVT, MMO); 7392 7393 if (!MemVT.isVector()) { 7394 SDValue Ops[] = { 7395 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7396 NewLD.getValue(1) 7397 }; 7398 7399 return DAG.getMergeValues(Ops, DL); 7400 } 7401 7402 SmallVector<SDValue, 3> Elts; 7403 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7404 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7405 DAG.getConstant(I, DL, MVT::i32)); 7406 7407 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7408 } 7409 7410 SDValue Ops[] = { 7411 DAG.getBuildVector(MemVT, DL, Elts), 7412 NewLD.getValue(1) 7413 }; 7414 7415 return DAG.getMergeValues(Ops, DL); 7416 } 7417 7418 if (!MemVT.isVector()) 7419 return SDValue(); 7420 7421 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7422 "Custom lowering for non-i32 vectors hasn't been implemented."); 7423 7424 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7425 MemVT, *Load->getMemOperand())) { 7426 SDValue Ops[2]; 7427 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7428 return DAG.getMergeValues(Ops, DL); 7429 } 7430 7431 unsigned Alignment = Load->getAlignment(); 7432 unsigned AS = Load->getAddressSpace(); 7433 if (Subtarget->hasLDSMisalignedBug() && 7434 AS == AMDGPUAS::FLAT_ADDRESS && 7435 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7436 return SplitVectorLoad(Op, DAG); 7437 } 7438 7439 MachineFunction &MF = DAG.getMachineFunction(); 7440 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7441 // If there is a possibilty that flat instruction access scratch memory 7442 // then we need to use the same legalization rules we use for private. 7443 if (AS == AMDGPUAS::FLAT_ADDRESS) 7444 AS = MFI->hasFlatScratchInit() ? 7445 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7446 7447 unsigned NumElements = MemVT.getVectorNumElements(); 7448 7449 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7450 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7451 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7452 if (MemVT.isPow2VectorType()) 7453 return SDValue(); 7454 if (NumElements == 3) 7455 return WidenVectorLoad(Op, DAG); 7456 return SplitVectorLoad(Op, DAG); 7457 } 7458 // Non-uniform loads will be selected to MUBUF instructions, so they 7459 // have the same legalization requirements as global and private 7460 // loads. 7461 // 7462 } 7463 7464 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7465 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7466 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7467 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7468 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7469 Alignment >= 4 && NumElements < 32) { 7470 if (MemVT.isPow2VectorType()) 7471 return SDValue(); 7472 if (NumElements == 3) 7473 return WidenVectorLoad(Op, DAG); 7474 return SplitVectorLoad(Op, DAG); 7475 } 7476 // Non-uniform loads will be selected to MUBUF instructions, so they 7477 // have the same legalization requirements as global and private 7478 // loads. 7479 // 7480 } 7481 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7482 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7483 AS == AMDGPUAS::GLOBAL_ADDRESS || 7484 AS == AMDGPUAS::FLAT_ADDRESS) { 7485 if (NumElements > 4) 7486 return SplitVectorLoad(Op, DAG); 7487 // v3 loads not supported on SI. 7488 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7489 return WidenVectorLoad(Op, DAG); 7490 // v3 and v4 loads are supported for private and global memory. 7491 return SDValue(); 7492 } 7493 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7494 // Depending on the setting of the private_element_size field in the 7495 // resource descriptor, we can only make private accesses up to a certain 7496 // size. 7497 switch (Subtarget->getMaxPrivateElementSize()) { 7498 case 4: 7499 return scalarizeVectorLoad(Load, DAG); 7500 case 8: 7501 if (NumElements > 2) 7502 return SplitVectorLoad(Op, DAG); 7503 return SDValue(); 7504 case 16: 7505 // Same as global/flat 7506 if (NumElements > 4) 7507 return SplitVectorLoad(Op, DAG); 7508 // v3 loads not supported on SI. 7509 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7510 return WidenVectorLoad(Op, DAG); 7511 return SDValue(); 7512 default: 7513 llvm_unreachable("unsupported private_element_size"); 7514 } 7515 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7516 // Use ds_read_b128 if possible. 7517 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7518 MemVT.getStoreSize() == 16) 7519 return SDValue(); 7520 7521 if (NumElements > 2) 7522 return SplitVectorLoad(Op, DAG); 7523 7524 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7525 // address is negative, then the instruction is incorrectly treated as 7526 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7527 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7528 // load later in the SILoadStoreOptimizer. 7529 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7530 NumElements == 2 && MemVT.getStoreSize() == 8 && 7531 Load->getAlignment() < 8) { 7532 return SplitVectorLoad(Op, DAG); 7533 } 7534 } 7535 return SDValue(); 7536 } 7537 7538 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7539 EVT VT = Op.getValueType(); 7540 assert(VT.getSizeInBits() == 64); 7541 7542 SDLoc DL(Op); 7543 SDValue Cond = Op.getOperand(0); 7544 7545 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7546 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7547 7548 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7549 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7550 7551 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7552 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7553 7554 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7555 7556 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7557 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7558 7559 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7560 7561 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7562 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7563 } 7564 7565 // Catch division cases where we can use shortcuts with rcp and rsq 7566 // instructions. 7567 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7568 SelectionDAG &DAG) const { 7569 SDLoc SL(Op); 7570 SDValue LHS = Op.getOperand(0); 7571 SDValue RHS = Op.getOperand(1); 7572 EVT VT = Op.getValueType(); 7573 const SDNodeFlags Flags = Op->getFlags(); 7574 bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal(); 7575 7576 if (!Unsafe && VT == MVT::f32 && hasFP32Denormals(DAG.getMachineFunction())) 7577 return SDValue(); 7578 7579 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7580 if (Unsafe || VT == MVT::f32 || VT == MVT::f16) { 7581 if (CLHS->isExactlyValue(1.0)) { 7582 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7583 // the CI documentation has a worst case error of 1 ulp. 7584 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7585 // use it as long as we aren't trying to use denormals. 7586 // 7587 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7588 7589 // 1.0 / sqrt(x) -> rsq(x) 7590 7591 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7592 // error seems really high at 2^29 ULP. 7593 if (RHS.getOpcode() == ISD::FSQRT) 7594 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7595 7596 // 1.0 / x -> rcp(x) 7597 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7598 } 7599 7600 // Same as for 1.0, but expand the sign out of the constant. 7601 if (CLHS->isExactlyValue(-1.0)) { 7602 // -1.0 / x -> rcp (fneg x) 7603 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7604 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7605 } 7606 } 7607 } 7608 7609 if (Unsafe) { 7610 // Turn into multiply by the reciprocal. 7611 // x / y -> x * (1.0 / y) 7612 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7613 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7614 } 7615 7616 return SDValue(); 7617 } 7618 7619 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7620 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7621 if (GlueChain->getNumValues() <= 1) { 7622 return DAG.getNode(Opcode, SL, VT, A, B); 7623 } 7624 7625 assert(GlueChain->getNumValues() == 3); 7626 7627 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7628 switch (Opcode) { 7629 default: llvm_unreachable("no chain equivalent for opcode"); 7630 case ISD::FMUL: 7631 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7632 break; 7633 } 7634 7635 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7636 GlueChain.getValue(2)); 7637 } 7638 7639 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7640 EVT VT, SDValue A, SDValue B, SDValue C, 7641 SDValue GlueChain) { 7642 if (GlueChain->getNumValues() <= 1) { 7643 return DAG.getNode(Opcode, SL, VT, A, B, C); 7644 } 7645 7646 assert(GlueChain->getNumValues() == 3); 7647 7648 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7649 switch (Opcode) { 7650 default: llvm_unreachable("no chain equivalent for opcode"); 7651 case ISD::FMA: 7652 Opcode = AMDGPUISD::FMA_W_CHAIN; 7653 break; 7654 } 7655 7656 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7657 GlueChain.getValue(2)); 7658 } 7659 7660 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7661 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7662 return FastLowered; 7663 7664 SDLoc SL(Op); 7665 SDValue Src0 = Op.getOperand(0); 7666 SDValue Src1 = Op.getOperand(1); 7667 7668 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7669 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7670 7671 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7672 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7673 7674 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7675 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7676 7677 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7678 } 7679 7680 // Faster 2.5 ULP division that does not support denormals. 7681 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7682 SDLoc SL(Op); 7683 SDValue LHS = Op.getOperand(1); 7684 SDValue RHS = Op.getOperand(2); 7685 7686 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7687 7688 const APFloat K0Val(BitsToFloat(0x6f800000)); 7689 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7690 7691 const APFloat K1Val(BitsToFloat(0x2f800000)); 7692 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7693 7694 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7695 7696 EVT SetCCVT = 7697 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7698 7699 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7700 7701 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7702 7703 // TODO: Should this propagate fast-math-flags? 7704 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7705 7706 // rcp does not support denormals. 7707 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7708 7709 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7710 7711 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7712 } 7713 7714 // Returns immediate value for setting the F32 denorm mode when using the 7715 // S_DENORM_MODE instruction. 7716 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7717 const SDLoc &SL, const GCNSubtarget *ST) { 7718 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7719 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7720 ? FP_DENORM_FLUSH_NONE 7721 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7722 7723 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7724 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7725 } 7726 7727 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7728 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7729 return FastLowered; 7730 7731 SDLoc SL(Op); 7732 SDValue LHS = Op.getOperand(0); 7733 SDValue RHS = Op.getOperand(1); 7734 7735 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7736 7737 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7738 7739 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7740 RHS, RHS, LHS); 7741 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7742 LHS, RHS, LHS); 7743 7744 // Denominator is scaled to not be denormal, so using rcp is ok. 7745 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7746 DenominatorScaled); 7747 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7748 DenominatorScaled); 7749 7750 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7751 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7752 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7753 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7754 7755 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7756 7757 if (!HasFP32Denormals) { 7758 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7759 7760 SDValue EnableDenorm; 7761 if (Subtarget->hasDenormModeInst()) { 7762 const SDValue EnableDenormValue = 7763 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7764 7765 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7766 DAG.getEntryNode(), EnableDenormValue); 7767 } else { 7768 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7769 SL, MVT::i32); 7770 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7771 DAG.getEntryNode(), EnableDenormValue, 7772 BitField); 7773 } 7774 7775 SDValue Ops[3] = { 7776 NegDivScale0, 7777 EnableDenorm.getValue(0), 7778 EnableDenorm.getValue(1) 7779 }; 7780 7781 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7782 } 7783 7784 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7785 ApproxRcp, One, NegDivScale0); 7786 7787 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7788 ApproxRcp, Fma0); 7789 7790 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7791 Fma1, Fma1); 7792 7793 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7794 NumeratorScaled, Mul); 7795 7796 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7797 7798 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7799 NumeratorScaled, Fma3); 7800 7801 if (!HasFP32Denormals) { 7802 SDValue DisableDenorm; 7803 if (Subtarget->hasDenormModeInst()) { 7804 const SDValue DisableDenormValue = 7805 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7806 7807 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7808 Fma4.getValue(1), DisableDenormValue, 7809 Fma4.getValue(2)); 7810 } else { 7811 const SDValue DisableDenormValue = 7812 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7813 7814 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7815 Fma4.getValue(1), DisableDenormValue, 7816 BitField, Fma4.getValue(2)); 7817 } 7818 7819 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7820 DisableDenorm, DAG.getRoot()); 7821 DAG.setRoot(OutputChain); 7822 } 7823 7824 SDValue Scale = NumeratorScaled.getValue(1); 7825 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7826 Fma4, Fma1, Fma3, Scale); 7827 7828 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7829 } 7830 7831 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7832 if (DAG.getTarget().Options.UnsafeFPMath) 7833 return lowerFastUnsafeFDIV(Op, DAG); 7834 7835 SDLoc SL(Op); 7836 SDValue X = Op.getOperand(0); 7837 SDValue Y = Op.getOperand(1); 7838 7839 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7840 7841 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7842 7843 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7844 7845 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7846 7847 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7848 7849 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7850 7851 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7852 7853 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7854 7855 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7856 7857 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7858 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7859 7860 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7861 NegDivScale0, Mul, DivScale1); 7862 7863 SDValue Scale; 7864 7865 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7866 // Workaround a hardware bug on SI where the condition output from div_scale 7867 // is not usable. 7868 7869 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7870 7871 // Figure out if the scale to use for div_fmas. 7872 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7873 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7874 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7875 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7876 7877 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7878 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7879 7880 SDValue Scale0Hi 7881 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7882 SDValue Scale1Hi 7883 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7884 7885 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7886 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7887 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7888 } else { 7889 Scale = DivScale1.getValue(1); 7890 } 7891 7892 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7893 Fma4, Fma3, Mul, Scale); 7894 7895 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7896 } 7897 7898 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7899 EVT VT = Op.getValueType(); 7900 7901 if (VT == MVT::f32) 7902 return LowerFDIV32(Op, DAG); 7903 7904 if (VT == MVT::f64) 7905 return LowerFDIV64(Op, DAG); 7906 7907 if (VT == MVT::f16) 7908 return LowerFDIV16(Op, DAG); 7909 7910 llvm_unreachable("Unexpected type for fdiv"); 7911 } 7912 7913 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7914 SDLoc DL(Op); 7915 StoreSDNode *Store = cast<StoreSDNode>(Op); 7916 EVT VT = Store->getMemoryVT(); 7917 7918 if (VT == MVT::i1) { 7919 return DAG.getTruncStore(Store->getChain(), DL, 7920 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7921 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7922 } 7923 7924 assert(VT.isVector() && 7925 Store->getValue().getValueType().getScalarType() == MVT::i32); 7926 7927 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7928 VT, *Store->getMemOperand())) { 7929 return expandUnalignedStore(Store, DAG); 7930 } 7931 7932 unsigned AS = Store->getAddressSpace(); 7933 if (Subtarget->hasLDSMisalignedBug() && 7934 AS == AMDGPUAS::FLAT_ADDRESS && 7935 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7936 return SplitVectorStore(Op, DAG); 7937 } 7938 7939 MachineFunction &MF = DAG.getMachineFunction(); 7940 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7941 // If there is a possibilty that flat instruction access scratch memory 7942 // then we need to use the same legalization rules we use for private. 7943 if (AS == AMDGPUAS::FLAT_ADDRESS) 7944 AS = MFI->hasFlatScratchInit() ? 7945 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7946 7947 unsigned NumElements = VT.getVectorNumElements(); 7948 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7949 AS == AMDGPUAS::FLAT_ADDRESS) { 7950 if (NumElements > 4) 7951 return SplitVectorStore(Op, DAG); 7952 // v3 stores not supported on SI. 7953 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7954 return SplitVectorStore(Op, DAG); 7955 return SDValue(); 7956 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7957 switch (Subtarget->getMaxPrivateElementSize()) { 7958 case 4: 7959 return scalarizeVectorStore(Store, DAG); 7960 case 8: 7961 if (NumElements > 2) 7962 return SplitVectorStore(Op, DAG); 7963 return SDValue(); 7964 case 16: 7965 if (NumElements > 4 || NumElements == 3) 7966 return SplitVectorStore(Op, DAG); 7967 return SDValue(); 7968 default: 7969 llvm_unreachable("unsupported private_element_size"); 7970 } 7971 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7972 // Use ds_write_b128 if possible. 7973 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7974 VT.getStoreSize() == 16 && NumElements != 3) 7975 return SDValue(); 7976 7977 if (NumElements > 2) 7978 return SplitVectorStore(Op, DAG); 7979 7980 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7981 // address is negative, then the instruction is incorrectly treated as 7982 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7983 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7984 // store later in the SILoadStoreOptimizer. 7985 if (!Subtarget->hasUsableDSOffset() && 7986 NumElements == 2 && VT.getStoreSize() == 8 && 7987 Store->getAlignment() < 8) { 7988 return SplitVectorStore(Op, DAG); 7989 } 7990 7991 return SDValue(); 7992 } else { 7993 llvm_unreachable("unhandled address space"); 7994 } 7995 } 7996 7997 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7998 SDLoc DL(Op); 7999 EVT VT = Op.getValueType(); 8000 SDValue Arg = Op.getOperand(0); 8001 SDValue TrigVal; 8002 8003 // TODO: Should this propagate fast-math-flags? 8004 8005 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 8006 8007 if (Subtarget->hasTrigReducedRange()) { 8008 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8009 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 8010 } else { 8011 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 8012 } 8013 8014 switch (Op.getOpcode()) { 8015 case ISD::FCOS: 8016 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 8017 case ISD::FSIN: 8018 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 8019 default: 8020 llvm_unreachable("Wrong trig opcode"); 8021 } 8022 } 8023 8024 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8025 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8026 assert(AtomicNode->isCompareAndSwap()); 8027 unsigned AS = AtomicNode->getAddressSpace(); 8028 8029 // No custom lowering required for local address space 8030 if (!isFlatGlobalAddrSpace(AS)) 8031 return Op; 8032 8033 // Non-local address space requires custom lowering for atomic compare 8034 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8035 SDLoc DL(Op); 8036 SDValue ChainIn = Op.getOperand(0); 8037 SDValue Addr = Op.getOperand(1); 8038 SDValue Old = Op.getOperand(2); 8039 SDValue New = Op.getOperand(3); 8040 EVT VT = Op.getValueType(); 8041 MVT SimpleVT = VT.getSimpleVT(); 8042 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8043 8044 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8045 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8046 8047 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8048 Ops, VT, AtomicNode->getMemOperand()); 8049 } 8050 8051 //===----------------------------------------------------------------------===// 8052 // Custom DAG optimizations 8053 //===----------------------------------------------------------------------===// 8054 8055 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8056 DAGCombinerInfo &DCI) const { 8057 EVT VT = N->getValueType(0); 8058 EVT ScalarVT = VT.getScalarType(); 8059 if (ScalarVT != MVT::f32) 8060 return SDValue(); 8061 8062 SelectionDAG &DAG = DCI.DAG; 8063 SDLoc DL(N); 8064 8065 SDValue Src = N->getOperand(0); 8066 EVT SrcVT = Src.getValueType(); 8067 8068 // TODO: We could try to match extracting the higher bytes, which would be 8069 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8070 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8071 // about in practice. 8072 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8073 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8074 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 8075 DCI.AddToWorklist(Cvt.getNode()); 8076 return Cvt; 8077 } 8078 } 8079 8080 return SDValue(); 8081 } 8082 8083 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8084 8085 // This is a variant of 8086 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8087 // 8088 // The normal DAG combiner will do this, but only if the add has one use since 8089 // that would increase the number of instructions. 8090 // 8091 // This prevents us from seeing a constant offset that can be folded into a 8092 // memory instruction's addressing mode. If we know the resulting add offset of 8093 // a pointer can be folded into an addressing offset, we can replace the pointer 8094 // operand with the add of new constant offset. This eliminates one of the uses, 8095 // and may allow the remaining use to also be simplified. 8096 // 8097 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8098 unsigned AddrSpace, 8099 EVT MemVT, 8100 DAGCombinerInfo &DCI) const { 8101 SDValue N0 = N->getOperand(0); 8102 SDValue N1 = N->getOperand(1); 8103 8104 // We only do this to handle cases where it's profitable when there are 8105 // multiple uses of the add, so defer to the standard combine. 8106 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8107 N0->hasOneUse()) 8108 return SDValue(); 8109 8110 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8111 if (!CN1) 8112 return SDValue(); 8113 8114 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8115 if (!CAdd) 8116 return SDValue(); 8117 8118 // If the resulting offset is too large, we can't fold it into the addressing 8119 // mode offset. 8120 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8121 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8122 8123 AddrMode AM; 8124 AM.HasBaseReg = true; 8125 AM.BaseOffs = Offset.getSExtValue(); 8126 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8127 return SDValue(); 8128 8129 SelectionDAG &DAG = DCI.DAG; 8130 SDLoc SL(N); 8131 EVT VT = N->getValueType(0); 8132 8133 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8134 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8135 8136 SDNodeFlags Flags; 8137 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8138 (N0.getOpcode() == ISD::OR || 8139 N0->getFlags().hasNoUnsignedWrap())); 8140 8141 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8142 } 8143 8144 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8145 DAGCombinerInfo &DCI) const { 8146 SDValue Ptr = N->getBasePtr(); 8147 SelectionDAG &DAG = DCI.DAG; 8148 SDLoc SL(N); 8149 8150 // TODO: We could also do this for multiplies. 8151 if (Ptr.getOpcode() == ISD::SHL) { 8152 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8153 N->getMemoryVT(), DCI); 8154 if (NewPtr) { 8155 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8156 8157 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8158 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8159 } 8160 } 8161 8162 return SDValue(); 8163 } 8164 8165 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8166 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8167 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8168 (Opc == ISD::XOR && Val == 0); 8169 } 8170 8171 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8172 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8173 // integer combine opportunities since most 64-bit operations are decomposed 8174 // this way. TODO: We won't want this for SALU especially if it is an inline 8175 // immediate. 8176 SDValue SITargetLowering::splitBinaryBitConstantOp( 8177 DAGCombinerInfo &DCI, 8178 const SDLoc &SL, 8179 unsigned Opc, SDValue LHS, 8180 const ConstantSDNode *CRHS) const { 8181 uint64_t Val = CRHS->getZExtValue(); 8182 uint32_t ValLo = Lo_32(Val); 8183 uint32_t ValHi = Hi_32(Val); 8184 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8185 8186 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8187 bitOpWithConstantIsReducible(Opc, ValHi)) || 8188 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8189 // If we need to materialize a 64-bit immediate, it will be split up later 8190 // anyway. Avoid creating the harder to understand 64-bit immediate 8191 // materialization. 8192 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8193 } 8194 8195 return SDValue(); 8196 } 8197 8198 // Returns true if argument is a boolean value which is not serialized into 8199 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8200 static bool isBoolSGPR(SDValue V) { 8201 if (V.getValueType() != MVT::i1) 8202 return false; 8203 switch (V.getOpcode()) { 8204 default: break; 8205 case ISD::SETCC: 8206 case ISD::AND: 8207 case ISD::OR: 8208 case ISD::XOR: 8209 case AMDGPUISD::FP_CLASS: 8210 return true; 8211 } 8212 return false; 8213 } 8214 8215 // If a constant has all zeroes or all ones within each byte return it. 8216 // Otherwise return 0. 8217 static uint32_t getConstantPermuteMask(uint32_t C) { 8218 // 0xff for any zero byte in the mask 8219 uint32_t ZeroByteMask = 0; 8220 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8221 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8222 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8223 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8224 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8225 if ((NonZeroByteMask & C) != NonZeroByteMask) 8226 return 0; // Partial bytes selected. 8227 return C; 8228 } 8229 8230 // Check if a node selects whole bytes from its operand 0 starting at a byte 8231 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8232 // or -1 if not succeeded. 8233 // Note byte select encoding: 8234 // value 0-3 selects corresponding source byte; 8235 // value 0xc selects zero; 8236 // value 0xff selects 0xff. 8237 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8238 assert(V.getValueSizeInBits() == 32); 8239 8240 if (V.getNumOperands() != 2) 8241 return ~0; 8242 8243 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8244 if (!N1) 8245 return ~0; 8246 8247 uint32_t C = N1->getZExtValue(); 8248 8249 switch (V.getOpcode()) { 8250 default: 8251 break; 8252 case ISD::AND: 8253 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8254 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8255 } 8256 break; 8257 8258 case ISD::OR: 8259 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8260 return (0x03020100 & ~ConstMask) | ConstMask; 8261 } 8262 break; 8263 8264 case ISD::SHL: 8265 if (C % 8) 8266 return ~0; 8267 8268 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8269 8270 case ISD::SRL: 8271 if (C % 8) 8272 return ~0; 8273 8274 return uint32_t(0x0c0c0c0c03020100ull >> C); 8275 } 8276 8277 return ~0; 8278 } 8279 8280 SDValue SITargetLowering::performAndCombine(SDNode *N, 8281 DAGCombinerInfo &DCI) const { 8282 if (DCI.isBeforeLegalize()) 8283 return SDValue(); 8284 8285 SelectionDAG &DAG = DCI.DAG; 8286 EVT VT = N->getValueType(0); 8287 SDValue LHS = N->getOperand(0); 8288 SDValue RHS = N->getOperand(1); 8289 8290 8291 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8292 if (VT == MVT::i64 && CRHS) { 8293 if (SDValue Split 8294 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8295 return Split; 8296 } 8297 8298 if (CRHS && VT == MVT::i32) { 8299 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8300 // nb = number of trailing zeroes in mask 8301 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8302 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8303 uint64_t Mask = CRHS->getZExtValue(); 8304 unsigned Bits = countPopulation(Mask); 8305 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8306 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8307 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8308 unsigned Shift = CShift->getZExtValue(); 8309 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8310 unsigned Offset = NB + Shift; 8311 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8312 SDLoc SL(N); 8313 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8314 LHS->getOperand(0), 8315 DAG.getConstant(Offset, SL, MVT::i32), 8316 DAG.getConstant(Bits, SL, MVT::i32)); 8317 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8318 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8319 DAG.getValueType(NarrowVT)); 8320 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8321 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8322 return Shl; 8323 } 8324 } 8325 } 8326 8327 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8328 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8329 isa<ConstantSDNode>(LHS.getOperand(2))) { 8330 uint32_t Sel = getConstantPermuteMask(Mask); 8331 if (!Sel) 8332 return SDValue(); 8333 8334 // Select 0xc for all zero bytes 8335 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8336 SDLoc DL(N); 8337 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8338 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8339 } 8340 } 8341 8342 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8343 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8344 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8345 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8346 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8347 8348 SDValue X = LHS.getOperand(0); 8349 SDValue Y = RHS.getOperand(0); 8350 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8351 return SDValue(); 8352 8353 if (LCC == ISD::SETO) { 8354 if (X != LHS.getOperand(1)) 8355 return SDValue(); 8356 8357 if (RCC == ISD::SETUNE) { 8358 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8359 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8360 return SDValue(); 8361 8362 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8363 SIInstrFlags::N_SUBNORMAL | 8364 SIInstrFlags::N_ZERO | 8365 SIInstrFlags::P_ZERO | 8366 SIInstrFlags::P_SUBNORMAL | 8367 SIInstrFlags::P_NORMAL; 8368 8369 static_assert(((~(SIInstrFlags::S_NAN | 8370 SIInstrFlags::Q_NAN | 8371 SIInstrFlags::N_INFINITY | 8372 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8373 "mask not equal"); 8374 8375 SDLoc DL(N); 8376 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8377 X, DAG.getConstant(Mask, DL, MVT::i32)); 8378 } 8379 } 8380 } 8381 8382 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8383 std::swap(LHS, RHS); 8384 8385 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8386 RHS.hasOneUse()) { 8387 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8388 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8389 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8390 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8391 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8392 (RHS.getOperand(0) == LHS.getOperand(0) && 8393 LHS.getOperand(0) == LHS.getOperand(1))) { 8394 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8395 unsigned NewMask = LCC == ISD::SETO ? 8396 Mask->getZExtValue() & ~OrdMask : 8397 Mask->getZExtValue() & OrdMask; 8398 8399 SDLoc DL(N); 8400 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8401 DAG.getConstant(NewMask, DL, MVT::i32)); 8402 } 8403 } 8404 8405 if (VT == MVT::i32 && 8406 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8407 // and x, (sext cc from i1) => select cc, x, 0 8408 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8409 std::swap(LHS, RHS); 8410 if (isBoolSGPR(RHS.getOperand(0))) 8411 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8412 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8413 } 8414 8415 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8416 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8417 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8418 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8419 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8420 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8421 if (LHSMask != ~0u && RHSMask != ~0u) { 8422 // Canonicalize the expression in an attempt to have fewer unique masks 8423 // and therefore fewer registers used to hold the masks. 8424 if (LHSMask > RHSMask) { 8425 std::swap(LHSMask, RHSMask); 8426 std::swap(LHS, RHS); 8427 } 8428 8429 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8430 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8431 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8432 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8433 8434 // Check of we need to combine values from two sources within a byte. 8435 if (!(LHSUsedLanes & RHSUsedLanes) && 8436 // If we select high and lower word keep it for SDWA. 8437 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8438 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8439 // Each byte in each mask is either selector mask 0-3, or has higher 8440 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8441 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8442 // mask which is not 0xff wins. By anding both masks we have a correct 8443 // result except that 0x0c shall be corrected to give 0x0c only. 8444 uint32_t Mask = LHSMask & RHSMask; 8445 for (unsigned I = 0; I < 32; I += 8) { 8446 uint32_t ByteSel = 0xff << I; 8447 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8448 Mask &= (0x0c << I) & 0xffffffff; 8449 } 8450 8451 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8452 // or 0x0c. 8453 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8454 SDLoc DL(N); 8455 8456 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8457 LHS.getOperand(0), RHS.getOperand(0), 8458 DAG.getConstant(Sel, DL, MVT::i32)); 8459 } 8460 } 8461 } 8462 8463 return SDValue(); 8464 } 8465 8466 SDValue SITargetLowering::performOrCombine(SDNode *N, 8467 DAGCombinerInfo &DCI) const { 8468 SelectionDAG &DAG = DCI.DAG; 8469 SDValue LHS = N->getOperand(0); 8470 SDValue RHS = N->getOperand(1); 8471 8472 EVT VT = N->getValueType(0); 8473 if (VT == MVT::i1) { 8474 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8475 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8476 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8477 SDValue Src = LHS.getOperand(0); 8478 if (Src != RHS.getOperand(0)) 8479 return SDValue(); 8480 8481 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8482 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8483 if (!CLHS || !CRHS) 8484 return SDValue(); 8485 8486 // Only 10 bits are used. 8487 static const uint32_t MaxMask = 0x3ff; 8488 8489 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8490 SDLoc DL(N); 8491 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8492 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8493 } 8494 8495 return SDValue(); 8496 } 8497 8498 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8499 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8500 LHS.getOpcode() == AMDGPUISD::PERM && 8501 isa<ConstantSDNode>(LHS.getOperand(2))) { 8502 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8503 if (!Sel) 8504 return SDValue(); 8505 8506 Sel |= LHS.getConstantOperandVal(2); 8507 SDLoc DL(N); 8508 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8509 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8510 } 8511 8512 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8513 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8514 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8515 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8516 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8517 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8518 if (LHSMask != ~0u && RHSMask != ~0u) { 8519 // Canonicalize the expression in an attempt to have fewer unique masks 8520 // and therefore fewer registers used to hold the masks. 8521 if (LHSMask > RHSMask) { 8522 std::swap(LHSMask, RHSMask); 8523 std::swap(LHS, RHS); 8524 } 8525 8526 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8527 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8528 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8529 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8530 8531 // Check of we need to combine values from two sources within a byte. 8532 if (!(LHSUsedLanes & RHSUsedLanes) && 8533 // If we select high and lower word keep it for SDWA. 8534 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8535 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8536 // Kill zero bytes selected by other mask. Zero value is 0xc. 8537 LHSMask &= ~RHSUsedLanes; 8538 RHSMask &= ~LHSUsedLanes; 8539 // Add 4 to each active LHS lane 8540 LHSMask |= LHSUsedLanes & 0x04040404; 8541 // Combine masks 8542 uint32_t Sel = LHSMask | RHSMask; 8543 SDLoc DL(N); 8544 8545 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8546 LHS.getOperand(0), RHS.getOperand(0), 8547 DAG.getConstant(Sel, DL, MVT::i32)); 8548 } 8549 } 8550 } 8551 8552 if (VT != MVT::i64) 8553 return SDValue(); 8554 8555 // TODO: This could be a generic combine with a predicate for extracting the 8556 // high half of an integer being free. 8557 8558 // (or i64:x, (zero_extend i32:y)) -> 8559 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8560 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8561 RHS.getOpcode() != ISD::ZERO_EXTEND) 8562 std::swap(LHS, RHS); 8563 8564 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8565 SDValue ExtSrc = RHS.getOperand(0); 8566 EVT SrcVT = ExtSrc.getValueType(); 8567 if (SrcVT == MVT::i32) { 8568 SDLoc SL(N); 8569 SDValue LowLHS, HiBits; 8570 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8571 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8572 8573 DCI.AddToWorklist(LowOr.getNode()); 8574 DCI.AddToWorklist(HiBits.getNode()); 8575 8576 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8577 LowOr, HiBits); 8578 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8579 } 8580 } 8581 8582 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8583 if (CRHS) { 8584 if (SDValue Split 8585 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8586 return Split; 8587 } 8588 8589 return SDValue(); 8590 } 8591 8592 SDValue SITargetLowering::performXorCombine(SDNode *N, 8593 DAGCombinerInfo &DCI) const { 8594 EVT VT = N->getValueType(0); 8595 if (VT != MVT::i64) 8596 return SDValue(); 8597 8598 SDValue LHS = N->getOperand(0); 8599 SDValue RHS = N->getOperand(1); 8600 8601 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8602 if (CRHS) { 8603 if (SDValue Split 8604 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8605 return Split; 8606 } 8607 8608 return SDValue(); 8609 } 8610 8611 // Instructions that will be lowered with a final instruction that zeros the 8612 // high result bits. 8613 // XXX - probably only need to list legal operations. 8614 static bool fp16SrcZerosHighBits(unsigned Opc) { 8615 switch (Opc) { 8616 case ISD::FADD: 8617 case ISD::FSUB: 8618 case ISD::FMUL: 8619 case ISD::FDIV: 8620 case ISD::FREM: 8621 case ISD::FMA: 8622 case ISD::FMAD: 8623 case ISD::FCANONICALIZE: 8624 case ISD::FP_ROUND: 8625 case ISD::UINT_TO_FP: 8626 case ISD::SINT_TO_FP: 8627 case ISD::FABS: 8628 // Fabs is lowered to a bit operation, but it's an and which will clear the 8629 // high bits anyway. 8630 case ISD::FSQRT: 8631 case ISD::FSIN: 8632 case ISD::FCOS: 8633 case ISD::FPOWI: 8634 case ISD::FPOW: 8635 case ISD::FLOG: 8636 case ISD::FLOG2: 8637 case ISD::FLOG10: 8638 case ISD::FEXP: 8639 case ISD::FEXP2: 8640 case ISD::FCEIL: 8641 case ISD::FTRUNC: 8642 case ISD::FRINT: 8643 case ISD::FNEARBYINT: 8644 case ISD::FROUND: 8645 case ISD::FFLOOR: 8646 case ISD::FMINNUM: 8647 case ISD::FMAXNUM: 8648 case AMDGPUISD::FRACT: 8649 case AMDGPUISD::CLAMP: 8650 case AMDGPUISD::COS_HW: 8651 case AMDGPUISD::SIN_HW: 8652 case AMDGPUISD::FMIN3: 8653 case AMDGPUISD::FMAX3: 8654 case AMDGPUISD::FMED3: 8655 case AMDGPUISD::FMAD_FTZ: 8656 case AMDGPUISD::RCP: 8657 case AMDGPUISD::RSQ: 8658 case AMDGPUISD::RCP_IFLAG: 8659 case AMDGPUISD::LDEXP: 8660 return true; 8661 default: 8662 // fcopysign, select and others may be lowered to 32-bit bit operations 8663 // which don't zero the high bits. 8664 return false; 8665 } 8666 } 8667 8668 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8669 DAGCombinerInfo &DCI) const { 8670 if (!Subtarget->has16BitInsts() || 8671 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8672 return SDValue(); 8673 8674 EVT VT = N->getValueType(0); 8675 if (VT != MVT::i32) 8676 return SDValue(); 8677 8678 SDValue Src = N->getOperand(0); 8679 if (Src.getValueType() != MVT::i16) 8680 return SDValue(); 8681 8682 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8683 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8684 if (Src.getOpcode() == ISD::BITCAST) { 8685 SDValue BCSrc = Src.getOperand(0); 8686 if (BCSrc.getValueType() == MVT::f16 && 8687 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8688 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8689 } 8690 8691 return SDValue(); 8692 } 8693 8694 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8695 DAGCombinerInfo &DCI) 8696 const { 8697 SDValue Src = N->getOperand(0); 8698 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8699 8700 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8701 VTSign->getVT() == MVT::i8) || 8702 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8703 VTSign->getVT() == MVT::i16)) && 8704 Src.hasOneUse()) { 8705 auto *M = cast<MemSDNode>(Src); 8706 SDValue Ops[] = { 8707 Src.getOperand(0), // Chain 8708 Src.getOperand(1), // rsrc 8709 Src.getOperand(2), // vindex 8710 Src.getOperand(3), // voffset 8711 Src.getOperand(4), // soffset 8712 Src.getOperand(5), // offset 8713 Src.getOperand(6), 8714 Src.getOperand(7) 8715 }; 8716 // replace with BUFFER_LOAD_BYTE/SHORT 8717 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8718 Src.getOperand(0).getValueType()); 8719 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8720 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8721 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8722 ResList, 8723 Ops, M->getMemoryVT(), 8724 M->getMemOperand()); 8725 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8726 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8727 } 8728 return SDValue(); 8729 } 8730 8731 SDValue SITargetLowering::performClassCombine(SDNode *N, 8732 DAGCombinerInfo &DCI) const { 8733 SelectionDAG &DAG = DCI.DAG; 8734 SDValue Mask = N->getOperand(1); 8735 8736 // fp_class x, 0 -> false 8737 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8738 if (CMask->isNullValue()) 8739 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8740 } 8741 8742 if (N->getOperand(0).isUndef()) 8743 return DAG.getUNDEF(MVT::i1); 8744 8745 return SDValue(); 8746 } 8747 8748 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8749 DAGCombinerInfo &DCI) const { 8750 EVT VT = N->getValueType(0); 8751 SDValue N0 = N->getOperand(0); 8752 8753 if (N0.isUndef()) 8754 return N0; 8755 8756 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8757 N0.getOpcode() == ISD::SINT_TO_FP)) { 8758 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8759 N->getFlags()); 8760 } 8761 8762 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8763 } 8764 8765 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8766 unsigned MaxDepth) const { 8767 unsigned Opcode = Op.getOpcode(); 8768 if (Opcode == ISD::FCANONICALIZE) 8769 return true; 8770 8771 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8772 auto F = CFP->getValueAPF(); 8773 if (F.isNaN() && F.isSignaling()) 8774 return false; 8775 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8776 } 8777 8778 // If source is a result of another standard FP operation it is already in 8779 // canonical form. 8780 if (MaxDepth == 0) 8781 return false; 8782 8783 switch (Opcode) { 8784 // These will flush denorms if required. 8785 case ISD::FADD: 8786 case ISD::FSUB: 8787 case ISD::FMUL: 8788 case ISD::FCEIL: 8789 case ISD::FFLOOR: 8790 case ISD::FMA: 8791 case ISD::FMAD: 8792 case ISD::FSQRT: 8793 case ISD::FDIV: 8794 case ISD::FREM: 8795 case ISD::FP_ROUND: 8796 case ISD::FP_EXTEND: 8797 case AMDGPUISD::FMUL_LEGACY: 8798 case AMDGPUISD::FMAD_FTZ: 8799 case AMDGPUISD::RCP: 8800 case AMDGPUISD::RSQ: 8801 case AMDGPUISD::RSQ_CLAMP: 8802 case AMDGPUISD::RCP_LEGACY: 8803 case AMDGPUISD::RSQ_LEGACY: 8804 case AMDGPUISD::RCP_IFLAG: 8805 case AMDGPUISD::TRIG_PREOP: 8806 case AMDGPUISD::DIV_SCALE: 8807 case AMDGPUISD::DIV_FMAS: 8808 case AMDGPUISD::DIV_FIXUP: 8809 case AMDGPUISD::FRACT: 8810 case AMDGPUISD::LDEXP: 8811 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8812 case AMDGPUISD::CVT_F32_UBYTE0: 8813 case AMDGPUISD::CVT_F32_UBYTE1: 8814 case AMDGPUISD::CVT_F32_UBYTE2: 8815 case AMDGPUISD::CVT_F32_UBYTE3: 8816 return true; 8817 8818 // It can/will be lowered or combined as a bit operation. 8819 // Need to check their input recursively to handle. 8820 case ISD::FNEG: 8821 case ISD::FABS: 8822 case ISD::FCOPYSIGN: 8823 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8824 8825 case ISD::FSIN: 8826 case ISD::FCOS: 8827 case ISD::FSINCOS: 8828 return Op.getValueType().getScalarType() != MVT::f16; 8829 8830 case ISD::FMINNUM: 8831 case ISD::FMAXNUM: 8832 case ISD::FMINNUM_IEEE: 8833 case ISD::FMAXNUM_IEEE: 8834 case AMDGPUISD::CLAMP: 8835 case AMDGPUISD::FMED3: 8836 case AMDGPUISD::FMAX3: 8837 case AMDGPUISD::FMIN3: { 8838 // FIXME: Shouldn't treat the generic operations different based these. 8839 // However, we aren't really required to flush the result from 8840 // minnum/maxnum.. 8841 8842 // snans will be quieted, so we only need to worry about denormals. 8843 if (Subtarget->supportsMinMaxDenormModes() || 8844 denormalsEnabledForType(DAG, Op.getValueType())) 8845 return true; 8846 8847 // Flushing may be required. 8848 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8849 // targets need to check their input recursively. 8850 8851 // FIXME: Does this apply with clamp? It's implemented with max. 8852 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8853 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8854 return false; 8855 } 8856 8857 return true; 8858 } 8859 case ISD::SELECT: { 8860 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8861 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8862 } 8863 case ISD::BUILD_VECTOR: { 8864 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8865 SDValue SrcOp = Op.getOperand(i); 8866 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8867 return false; 8868 } 8869 8870 return true; 8871 } 8872 case ISD::EXTRACT_VECTOR_ELT: 8873 case ISD::EXTRACT_SUBVECTOR: { 8874 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8875 } 8876 case ISD::INSERT_VECTOR_ELT: { 8877 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8878 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8879 } 8880 case ISD::UNDEF: 8881 // Could be anything. 8882 return false; 8883 8884 case ISD::BITCAST: { 8885 // Hack round the mess we make when legalizing extract_vector_elt 8886 SDValue Src = Op.getOperand(0); 8887 if (Src.getValueType() == MVT::i16 && 8888 Src.getOpcode() == ISD::TRUNCATE) { 8889 SDValue TruncSrc = Src.getOperand(0); 8890 if (TruncSrc.getValueType() == MVT::i32 && 8891 TruncSrc.getOpcode() == ISD::BITCAST && 8892 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8893 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8894 } 8895 } 8896 8897 return false; 8898 } 8899 case ISD::INTRINSIC_WO_CHAIN: { 8900 unsigned IntrinsicID 8901 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8902 // TODO: Handle more intrinsics 8903 switch (IntrinsicID) { 8904 case Intrinsic::amdgcn_cvt_pkrtz: 8905 case Intrinsic::amdgcn_cubeid: 8906 case Intrinsic::amdgcn_frexp_mant: 8907 case Intrinsic::amdgcn_fdot2: 8908 return true; 8909 default: 8910 break; 8911 } 8912 8913 LLVM_FALLTHROUGH; 8914 } 8915 default: 8916 return denormalsEnabledForType(DAG, Op.getValueType()) && 8917 DAG.isKnownNeverSNaN(Op); 8918 } 8919 8920 llvm_unreachable("invalid operation"); 8921 } 8922 8923 // Constant fold canonicalize. 8924 SDValue SITargetLowering::getCanonicalConstantFP( 8925 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8926 // Flush denormals to 0 if not enabled. 8927 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8928 return DAG.getConstantFP(0.0, SL, VT); 8929 8930 if (C.isNaN()) { 8931 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8932 if (C.isSignaling()) { 8933 // Quiet a signaling NaN. 8934 // FIXME: Is this supposed to preserve payload bits? 8935 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8936 } 8937 8938 // Make sure it is the canonical NaN bitpattern. 8939 // 8940 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8941 // immediate? 8942 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8943 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8944 } 8945 8946 // Already canonical. 8947 return DAG.getConstantFP(C, SL, VT); 8948 } 8949 8950 static bool vectorEltWillFoldAway(SDValue Op) { 8951 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8952 } 8953 8954 SDValue SITargetLowering::performFCanonicalizeCombine( 8955 SDNode *N, 8956 DAGCombinerInfo &DCI) const { 8957 SelectionDAG &DAG = DCI.DAG; 8958 SDValue N0 = N->getOperand(0); 8959 EVT VT = N->getValueType(0); 8960 8961 // fcanonicalize undef -> qnan 8962 if (N0.isUndef()) { 8963 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8964 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8965 } 8966 8967 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8968 EVT VT = N->getValueType(0); 8969 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8970 } 8971 8972 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8973 // (fcanonicalize k) 8974 // 8975 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8976 8977 // TODO: This could be better with wider vectors that will be split to v2f16, 8978 // and to consider uses since there aren't that many packed operations. 8979 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8980 isTypeLegal(MVT::v2f16)) { 8981 SDLoc SL(N); 8982 SDValue NewElts[2]; 8983 SDValue Lo = N0.getOperand(0); 8984 SDValue Hi = N0.getOperand(1); 8985 EVT EltVT = Lo.getValueType(); 8986 8987 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8988 for (unsigned I = 0; I != 2; ++I) { 8989 SDValue Op = N0.getOperand(I); 8990 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8991 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8992 CFP->getValueAPF()); 8993 } else if (Op.isUndef()) { 8994 // Handled below based on what the other operand is. 8995 NewElts[I] = Op; 8996 } else { 8997 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8998 } 8999 } 9000 9001 // If one half is undef, and one is constant, perfer a splat vector rather 9002 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9003 // cheaper to use and may be free with a packed operation. 9004 if (NewElts[0].isUndef()) { 9005 if (isa<ConstantFPSDNode>(NewElts[1])) 9006 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9007 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9008 } 9009 9010 if (NewElts[1].isUndef()) { 9011 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9012 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9013 } 9014 9015 return DAG.getBuildVector(VT, SL, NewElts); 9016 } 9017 } 9018 9019 unsigned SrcOpc = N0.getOpcode(); 9020 9021 // If it's free to do so, push canonicalizes further up the source, which may 9022 // find a canonical source. 9023 // 9024 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9025 // sNaNs. 9026 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9027 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9028 if (CRHS && N0.hasOneUse()) { 9029 SDLoc SL(N); 9030 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9031 N0.getOperand(0)); 9032 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9033 DCI.AddToWorklist(Canon0.getNode()); 9034 9035 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9036 } 9037 } 9038 9039 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9040 } 9041 9042 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9043 switch (Opc) { 9044 case ISD::FMAXNUM: 9045 case ISD::FMAXNUM_IEEE: 9046 return AMDGPUISD::FMAX3; 9047 case ISD::SMAX: 9048 return AMDGPUISD::SMAX3; 9049 case ISD::UMAX: 9050 return AMDGPUISD::UMAX3; 9051 case ISD::FMINNUM: 9052 case ISD::FMINNUM_IEEE: 9053 return AMDGPUISD::FMIN3; 9054 case ISD::SMIN: 9055 return AMDGPUISD::SMIN3; 9056 case ISD::UMIN: 9057 return AMDGPUISD::UMIN3; 9058 default: 9059 llvm_unreachable("Not a min/max opcode"); 9060 } 9061 } 9062 9063 SDValue SITargetLowering::performIntMed3ImmCombine( 9064 SelectionDAG &DAG, const SDLoc &SL, 9065 SDValue Op0, SDValue Op1, bool Signed) const { 9066 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9067 if (!K1) 9068 return SDValue(); 9069 9070 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9071 if (!K0) 9072 return SDValue(); 9073 9074 if (Signed) { 9075 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9076 return SDValue(); 9077 } else { 9078 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9079 return SDValue(); 9080 } 9081 9082 EVT VT = K0->getValueType(0); 9083 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9084 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9085 return DAG.getNode(Med3Opc, SL, VT, 9086 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9087 } 9088 9089 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9090 MVT NVT = MVT::i32; 9091 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9092 9093 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9094 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9095 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9096 9097 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9098 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9099 } 9100 9101 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9102 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9103 return C; 9104 9105 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9106 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9107 return C; 9108 } 9109 9110 return nullptr; 9111 } 9112 9113 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9114 const SDLoc &SL, 9115 SDValue Op0, 9116 SDValue Op1) const { 9117 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9118 if (!K1) 9119 return SDValue(); 9120 9121 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9122 if (!K0) 9123 return SDValue(); 9124 9125 // Ordered >= (although NaN inputs should have folded away by now). 9126 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 9127 if (Cmp == APFloat::cmpGreaterThan) 9128 return SDValue(); 9129 9130 const MachineFunction &MF = DAG.getMachineFunction(); 9131 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9132 9133 // TODO: Check IEEE bit enabled? 9134 EVT VT = Op0.getValueType(); 9135 if (Info->getMode().DX10Clamp) { 9136 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9137 // hardware fmed3 behavior converting to a min. 9138 // FIXME: Should this be allowing -0.0? 9139 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9140 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9141 } 9142 9143 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9144 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9145 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9146 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9147 // then give the other result, which is different from med3 with a NaN 9148 // input. 9149 SDValue Var = Op0.getOperand(0); 9150 if (!DAG.isKnownNeverSNaN(Var)) 9151 return SDValue(); 9152 9153 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9154 9155 if ((!K0->hasOneUse() || 9156 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9157 (!K1->hasOneUse() || 9158 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9159 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9160 Var, SDValue(K0, 0), SDValue(K1, 0)); 9161 } 9162 } 9163 9164 return SDValue(); 9165 } 9166 9167 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9168 DAGCombinerInfo &DCI) const { 9169 SelectionDAG &DAG = DCI.DAG; 9170 9171 EVT VT = N->getValueType(0); 9172 unsigned Opc = N->getOpcode(); 9173 SDValue Op0 = N->getOperand(0); 9174 SDValue Op1 = N->getOperand(1); 9175 9176 // Only do this if the inner op has one use since this will just increases 9177 // register pressure for no benefit. 9178 9179 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9180 !VT.isVector() && 9181 (VT == MVT::i32 || VT == MVT::f32 || 9182 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9183 // max(max(a, b), c) -> max3(a, b, c) 9184 // min(min(a, b), c) -> min3(a, b, c) 9185 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9186 SDLoc DL(N); 9187 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9188 DL, 9189 N->getValueType(0), 9190 Op0.getOperand(0), 9191 Op0.getOperand(1), 9192 Op1); 9193 } 9194 9195 // Try commuted. 9196 // max(a, max(b, c)) -> max3(a, b, c) 9197 // min(a, min(b, c)) -> min3(a, b, c) 9198 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9199 SDLoc DL(N); 9200 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9201 DL, 9202 N->getValueType(0), 9203 Op0, 9204 Op1.getOperand(0), 9205 Op1.getOperand(1)); 9206 } 9207 } 9208 9209 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9210 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9211 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9212 return Med3; 9213 } 9214 9215 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9216 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9217 return Med3; 9218 } 9219 9220 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9221 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9222 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9223 (Opc == AMDGPUISD::FMIN_LEGACY && 9224 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9225 (VT == MVT::f32 || VT == MVT::f64 || 9226 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9227 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9228 Op0.hasOneUse()) { 9229 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9230 return Res; 9231 } 9232 9233 return SDValue(); 9234 } 9235 9236 static bool isClampZeroToOne(SDValue A, SDValue B) { 9237 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9238 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9239 // FIXME: Should this be allowing -0.0? 9240 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9241 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9242 } 9243 } 9244 9245 return false; 9246 } 9247 9248 // FIXME: Should only worry about snans for version with chain. 9249 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9250 DAGCombinerInfo &DCI) const { 9251 EVT VT = N->getValueType(0); 9252 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9253 // NaNs. With a NaN input, the order of the operands may change the result. 9254 9255 SelectionDAG &DAG = DCI.DAG; 9256 SDLoc SL(N); 9257 9258 SDValue Src0 = N->getOperand(0); 9259 SDValue Src1 = N->getOperand(1); 9260 SDValue Src2 = N->getOperand(2); 9261 9262 if (isClampZeroToOne(Src0, Src1)) { 9263 // const_a, const_b, x -> clamp is safe in all cases including signaling 9264 // nans. 9265 // FIXME: Should this be allowing -0.0? 9266 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9267 } 9268 9269 const MachineFunction &MF = DAG.getMachineFunction(); 9270 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9271 9272 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9273 // handling no dx10-clamp? 9274 if (Info->getMode().DX10Clamp) { 9275 // If NaNs is clamped to 0, we are free to reorder the inputs. 9276 9277 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9278 std::swap(Src0, Src1); 9279 9280 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9281 std::swap(Src1, Src2); 9282 9283 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9284 std::swap(Src0, Src1); 9285 9286 if (isClampZeroToOne(Src1, Src2)) 9287 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9288 } 9289 9290 return SDValue(); 9291 } 9292 9293 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9294 DAGCombinerInfo &DCI) const { 9295 SDValue Src0 = N->getOperand(0); 9296 SDValue Src1 = N->getOperand(1); 9297 if (Src0.isUndef() && Src1.isUndef()) 9298 return DCI.DAG.getUNDEF(N->getValueType(0)); 9299 return SDValue(); 9300 } 9301 9302 SDValue SITargetLowering::performExtractVectorEltCombine( 9303 SDNode *N, DAGCombinerInfo &DCI) const { 9304 SDValue Vec = N->getOperand(0); 9305 SelectionDAG &DAG = DCI.DAG; 9306 9307 EVT VecVT = Vec.getValueType(); 9308 EVT EltVT = VecVT.getVectorElementType(); 9309 9310 if ((Vec.getOpcode() == ISD::FNEG || 9311 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9312 SDLoc SL(N); 9313 EVT EltVT = N->getValueType(0); 9314 SDValue Idx = N->getOperand(1); 9315 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9316 Vec.getOperand(0), Idx); 9317 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9318 } 9319 9320 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9321 // => 9322 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9323 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9324 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9325 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9326 SDLoc SL(N); 9327 EVT EltVT = N->getValueType(0); 9328 SDValue Idx = N->getOperand(1); 9329 unsigned Opc = Vec.getOpcode(); 9330 9331 switch(Opc) { 9332 default: 9333 break; 9334 // TODO: Support other binary operations. 9335 case ISD::FADD: 9336 case ISD::FSUB: 9337 case ISD::FMUL: 9338 case ISD::ADD: 9339 case ISD::UMIN: 9340 case ISD::UMAX: 9341 case ISD::SMIN: 9342 case ISD::SMAX: 9343 case ISD::FMAXNUM: 9344 case ISD::FMINNUM: 9345 case ISD::FMAXNUM_IEEE: 9346 case ISD::FMINNUM_IEEE: { 9347 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9348 Vec.getOperand(0), Idx); 9349 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9350 Vec.getOperand(1), Idx); 9351 9352 DCI.AddToWorklist(Elt0.getNode()); 9353 DCI.AddToWorklist(Elt1.getNode()); 9354 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9355 } 9356 } 9357 } 9358 9359 unsigned VecSize = VecVT.getSizeInBits(); 9360 unsigned EltSize = EltVT.getSizeInBits(); 9361 9362 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9363 // This elminates non-constant index and subsequent movrel or scratch access. 9364 // Sub-dword vectors of size 2 dword or less have better implementation. 9365 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9366 // instructions. 9367 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9368 !isa<ConstantSDNode>(N->getOperand(1))) { 9369 SDLoc SL(N); 9370 SDValue Idx = N->getOperand(1); 9371 EVT IdxVT = Idx.getValueType(); 9372 SDValue V; 9373 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9374 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9375 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9376 if (I == 0) 9377 V = Elt; 9378 else 9379 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9380 } 9381 return V; 9382 } 9383 9384 if (!DCI.isBeforeLegalize()) 9385 return SDValue(); 9386 9387 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9388 // elements. This exposes more load reduction opportunities by replacing 9389 // multiple small extract_vector_elements with a single 32-bit extract. 9390 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9391 if (isa<MemSDNode>(Vec) && 9392 EltSize <= 16 && 9393 EltVT.isByteSized() && 9394 VecSize > 32 && 9395 VecSize % 32 == 0 && 9396 Idx) { 9397 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9398 9399 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9400 unsigned EltIdx = BitIndex / 32; 9401 unsigned LeftoverBitIdx = BitIndex % 32; 9402 SDLoc SL(N); 9403 9404 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9405 DCI.AddToWorklist(Cast.getNode()); 9406 9407 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9408 DAG.getConstant(EltIdx, SL, MVT::i32)); 9409 DCI.AddToWorklist(Elt.getNode()); 9410 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9411 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9412 DCI.AddToWorklist(Srl.getNode()); 9413 9414 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9415 DCI.AddToWorklist(Trunc.getNode()); 9416 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9417 } 9418 9419 return SDValue(); 9420 } 9421 9422 SDValue 9423 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9424 DAGCombinerInfo &DCI) const { 9425 SDValue Vec = N->getOperand(0); 9426 SDValue Idx = N->getOperand(2); 9427 EVT VecVT = Vec.getValueType(); 9428 EVT EltVT = VecVT.getVectorElementType(); 9429 unsigned VecSize = VecVT.getSizeInBits(); 9430 unsigned EltSize = EltVT.getSizeInBits(); 9431 9432 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9433 // => BUILD_VECTOR n x select (e, const-idx) 9434 // This elminates non-constant index and subsequent movrel or scratch access. 9435 // Sub-dword vectors of size 2 dword or less have better implementation. 9436 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9437 // instructions. 9438 if (isa<ConstantSDNode>(Idx) || 9439 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9440 return SDValue(); 9441 9442 SelectionDAG &DAG = DCI.DAG; 9443 SDLoc SL(N); 9444 SDValue Ins = N->getOperand(1); 9445 EVT IdxVT = Idx.getValueType(); 9446 9447 SmallVector<SDValue, 16> Ops; 9448 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9449 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9450 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9451 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9452 Ops.push_back(V); 9453 } 9454 9455 return DAG.getBuildVector(VecVT, SL, Ops); 9456 } 9457 9458 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9459 const SDNode *N0, 9460 const SDNode *N1) const { 9461 EVT VT = N0->getValueType(0); 9462 9463 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9464 // support denormals ever. 9465 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9466 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9467 getSubtarget()->hasMadF16())) && 9468 isOperationLegal(ISD::FMAD, VT)) 9469 return ISD::FMAD; 9470 9471 const TargetOptions &Options = DAG.getTarget().Options; 9472 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9473 (N0->getFlags().hasAllowContract() && 9474 N1->getFlags().hasAllowContract())) && 9475 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9476 return ISD::FMA; 9477 } 9478 9479 return 0; 9480 } 9481 9482 // For a reassociatable opcode perform: 9483 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9484 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9485 SelectionDAG &DAG) const { 9486 EVT VT = N->getValueType(0); 9487 if (VT != MVT::i32 && VT != MVT::i64) 9488 return SDValue(); 9489 9490 unsigned Opc = N->getOpcode(); 9491 SDValue Op0 = N->getOperand(0); 9492 SDValue Op1 = N->getOperand(1); 9493 9494 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9495 return SDValue(); 9496 9497 if (Op0->isDivergent()) 9498 std::swap(Op0, Op1); 9499 9500 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9501 return SDValue(); 9502 9503 SDValue Op2 = Op1.getOperand(1); 9504 Op1 = Op1.getOperand(0); 9505 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9506 return SDValue(); 9507 9508 if (Op1->isDivergent()) 9509 std::swap(Op1, Op2); 9510 9511 // If either operand is constant this will conflict with 9512 // DAGCombiner::ReassociateOps(). 9513 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9514 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9515 return SDValue(); 9516 9517 SDLoc SL(N); 9518 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9519 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9520 } 9521 9522 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9523 EVT VT, 9524 SDValue N0, SDValue N1, SDValue N2, 9525 bool Signed) { 9526 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9527 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9528 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9529 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9530 } 9531 9532 SDValue SITargetLowering::performAddCombine(SDNode *N, 9533 DAGCombinerInfo &DCI) const { 9534 SelectionDAG &DAG = DCI.DAG; 9535 EVT VT = N->getValueType(0); 9536 SDLoc SL(N); 9537 SDValue LHS = N->getOperand(0); 9538 SDValue RHS = N->getOperand(1); 9539 9540 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9541 && Subtarget->hasMad64_32() && 9542 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9543 VT.getScalarSizeInBits() <= 64) { 9544 if (LHS.getOpcode() != ISD::MUL) 9545 std::swap(LHS, RHS); 9546 9547 SDValue MulLHS = LHS.getOperand(0); 9548 SDValue MulRHS = LHS.getOperand(1); 9549 SDValue AddRHS = RHS; 9550 9551 // TODO: Maybe restrict if SGPR inputs. 9552 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9553 numBitsUnsigned(MulRHS, DAG) <= 32) { 9554 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9555 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9556 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9557 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9558 } 9559 9560 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9561 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9562 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9563 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9564 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9565 } 9566 9567 return SDValue(); 9568 } 9569 9570 if (SDValue V = reassociateScalarOps(N, DAG)) { 9571 return V; 9572 } 9573 9574 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9575 return SDValue(); 9576 9577 // add x, zext (setcc) => addcarry x, 0, setcc 9578 // add x, sext (setcc) => subcarry x, 0, setcc 9579 unsigned Opc = LHS.getOpcode(); 9580 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9581 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9582 std::swap(RHS, LHS); 9583 9584 Opc = RHS.getOpcode(); 9585 switch (Opc) { 9586 default: break; 9587 case ISD::ZERO_EXTEND: 9588 case ISD::SIGN_EXTEND: 9589 case ISD::ANY_EXTEND: { 9590 auto Cond = RHS.getOperand(0); 9591 // If this won't be a real VOPC output, we would still need to insert an 9592 // extra instruction anyway. 9593 if (!isBoolSGPR(Cond)) 9594 break; 9595 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9596 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9597 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9598 return DAG.getNode(Opc, SL, VTList, Args); 9599 } 9600 case ISD::ADDCARRY: { 9601 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9602 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9603 if (!C || C->getZExtValue() != 0) break; 9604 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9605 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9606 } 9607 } 9608 return SDValue(); 9609 } 9610 9611 SDValue SITargetLowering::performSubCombine(SDNode *N, 9612 DAGCombinerInfo &DCI) const { 9613 SelectionDAG &DAG = DCI.DAG; 9614 EVT VT = N->getValueType(0); 9615 9616 if (VT != MVT::i32) 9617 return SDValue(); 9618 9619 SDLoc SL(N); 9620 SDValue LHS = N->getOperand(0); 9621 SDValue RHS = N->getOperand(1); 9622 9623 // sub x, zext (setcc) => subcarry x, 0, setcc 9624 // sub x, sext (setcc) => addcarry x, 0, setcc 9625 9626 bool Commuted = false; 9627 unsigned Opc = LHS.getOpcode(); 9628 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9629 Opc == ISD::ANY_EXTEND) { 9630 std::swap(RHS, LHS); 9631 Commuted = true; 9632 } 9633 9634 Opc = RHS.getOpcode(); 9635 switch (Opc) { 9636 default: break; 9637 case ISD::ZERO_EXTEND: 9638 case ISD::SIGN_EXTEND: 9639 case ISD::ANY_EXTEND: { 9640 auto Cond = RHS.getOperand(0); 9641 // If this won't be a real VOPC output, we would still need to insert an 9642 // extra instruction anyway. 9643 if (!isBoolSGPR(Cond)) 9644 break; 9645 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9646 SDValue Zero = DAG.getConstant(0, SL, MVT::i32); 9647 SDValue Args[3]; 9648 Args[2] = Cond; 9649 9650 if (Commuted) { 9651 // sub zext (setcc), x => addcarry 0, x, setcc 9652 // sub sext (setcc), x => subcarry 0, x, setcc 9653 Args[0] = Zero; 9654 Args[1] = LHS; 9655 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9656 } else { 9657 Args[0] = LHS; 9658 Args[1] = Zero; 9659 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9660 } 9661 9662 return DAG.getNode(Opc, SL, VTList, Args); 9663 } 9664 } 9665 9666 if (LHS.getOpcode() == ISD::SUBCARRY) { 9667 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9668 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9669 if (!C || !C->isNullValue()) 9670 return SDValue(); 9671 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9672 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9673 } 9674 return SDValue(); 9675 } 9676 9677 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9678 DAGCombinerInfo &DCI) const { 9679 9680 if (N->getValueType(0) != MVT::i32) 9681 return SDValue(); 9682 9683 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9684 if (!C || C->getZExtValue() != 0) 9685 return SDValue(); 9686 9687 SelectionDAG &DAG = DCI.DAG; 9688 SDValue LHS = N->getOperand(0); 9689 9690 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9691 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9692 unsigned LHSOpc = LHS.getOpcode(); 9693 unsigned Opc = N->getOpcode(); 9694 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9695 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9696 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9697 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9698 } 9699 return SDValue(); 9700 } 9701 9702 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9703 DAGCombinerInfo &DCI) const { 9704 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9705 return SDValue(); 9706 9707 SelectionDAG &DAG = DCI.DAG; 9708 EVT VT = N->getValueType(0); 9709 9710 SDLoc SL(N); 9711 SDValue LHS = N->getOperand(0); 9712 SDValue RHS = N->getOperand(1); 9713 9714 // These should really be instruction patterns, but writing patterns with 9715 // source modiifiers is a pain. 9716 9717 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9718 if (LHS.getOpcode() == ISD::FADD) { 9719 SDValue A = LHS.getOperand(0); 9720 if (A == LHS.getOperand(1)) { 9721 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9722 if (FusedOp != 0) { 9723 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9724 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9725 } 9726 } 9727 } 9728 9729 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9730 if (RHS.getOpcode() == ISD::FADD) { 9731 SDValue A = RHS.getOperand(0); 9732 if (A == RHS.getOperand(1)) { 9733 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9734 if (FusedOp != 0) { 9735 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9736 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9737 } 9738 } 9739 } 9740 9741 return SDValue(); 9742 } 9743 9744 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9745 DAGCombinerInfo &DCI) const { 9746 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9747 return SDValue(); 9748 9749 SelectionDAG &DAG = DCI.DAG; 9750 SDLoc SL(N); 9751 EVT VT = N->getValueType(0); 9752 assert(!VT.isVector()); 9753 9754 // Try to get the fneg to fold into the source modifier. This undoes generic 9755 // DAG combines and folds them into the mad. 9756 // 9757 // Only do this if we are not trying to support denormals. v_mad_f32 does 9758 // not support denormals ever. 9759 SDValue LHS = N->getOperand(0); 9760 SDValue RHS = N->getOperand(1); 9761 if (LHS.getOpcode() == ISD::FADD) { 9762 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9763 SDValue A = LHS.getOperand(0); 9764 if (A == LHS.getOperand(1)) { 9765 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9766 if (FusedOp != 0){ 9767 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9768 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9769 9770 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9771 } 9772 } 9773 } 9774 9775 if (RHS.getOpcode() == ISD::FADD) { 9776 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9777 9778 SDValue A = RHS.getOperand(0); 9779 if (A == RHS.getOperand(1)) { 9780 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9781 if (FusedOp != 0){ 9782 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9783 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9784 } 9785 } 9786 } 9787 9788 return SDValue(); 9789 } 9790 9791 SDValue SITargetLowering::performFMACombine(SDNode *N, 9792 DAGCombinerInfo &DCI) const { 9793 SelectionDAG &DAG = DCI.DAG; 9794 EVT VT = N->getValueType(0); 9795 SDLoc SL(N); 9796 9797 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9798 return SDValue(); 9799 9800 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9801 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9802 SDValue Op1 = N->getOperand(0); 9803 SDValue Op2 = N->getOperand(1); 9804 SDValue FMA = N->getOperand(2); 9805 9806 if (FMA.getOpcode() != ISD::FMA || 9807 Op1.getOpcode() != ISD::FP_EXTEND || 9808 Op2.getOpcode() != ISD::FP_EXTEND) 9809 return SDValue(); 9810 9811 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9812 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9813 // is sufficient to allow generaing fdot2. 9814 const TargetOptions &Options = DAG.getTarget().Options; 9815 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9816 (N->getFlags().hasAllowContract() && 9817 FMA->getFlags().hasAllowContract())) { 9818 Op1 = Op1.getOperand(0); 9819 Op2 = Op2.getOperand(0); 9820 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9821 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9822 return SDValue(); 9823 9824 SDValue Vec1 = Op1.getOperand(0); 9825 SDValue Idx1 = Op1.getOperand(1); 9826 SDValue Vec2 = Op2.getOperand(0); 9827 9828 SDValue FMAOp1 = FMA.getOperand(0); 9829 SDValue FMAOp2 = FMA.getOperand(1); 9830 SDValue FMAAcc = FMA.getOperand(2); 9831 9832 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9833 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9834 return SDValue(); 9835 9836 FMAOp1 = FMAOp1.getOperand(0); 9837 FMAOp2 = FMAOp2.getOperand(0); 9838 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9839 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9840 return SDValue(); 9841 9842 SDValue Vec3 = FMAOp1.getOperand(0); 9843 SDValue Vec4 = FMAOp2.getOperand(0); 9844 SDValue Idx2 = FMAOp1.getOperand(1); 9845 9846 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9847 // Idx1 and Idx2 cannot be the same. 9848 Idx1 == Idx2) 9849 return SDValue(); 9850 9851 if (Vec1 == Vec2 || Vec3 == Vec4) 9852 return SDValue(); 9853 9854 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9855 return SDValue(); 9856 9857 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9858 (Vec1 == Vec4 && Vec2 == Vec3)) { 9859 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9860 DAG.getTargetConstant(0, SL, MVT::i1)); 9861 } 9862 } 9863 return SDValue(); 9864 } 9865 9866 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9867 DAGCombinerInfo &DCI) const { 9868 SelectionDAG &DAG = DCI.DAG; 9869 SDLoc SL(N); 9870 9871 SDValue LHS = N->getOperand(0); 9872 SDValue RHS = N->getOperand(1); 9873 EVT VT = LHS.getValueType(); 9874 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9875 9876 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9877 if (!CRHS) { 9878 CRHS = dyn_cast<ConstantSDNode>(LHS); 9879 if (CRHS) { 9880 std::swap(LHS, RHS); 9881 CC = getSetCCSwappedOperands(CC); 9882 } 9883 } 9884 9885 if (CRHS) { 9886 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9887 isBoolSGPR(LHS.getOperand(0))) { 9888 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9889 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9890 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9891 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9892 if ((CRHS->isAllOnesValue() && 9893 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9894 (CRHS->isNullValue() && 9895 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9896 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9897 DAG.getConstant(-1, SL, MVT::i1)); 9898 if ((CRHS->isAllOnesValue() && 9899 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9900 (CRHS->isNullValue() && 9901 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9902 return LHS.getOperand(0); 9903 } 9904 9905 uint64_t CRHSVal = CRHS->getZExtValue(); 9906 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9907 LHS.getOpcode() == ISD::SELECT && 9908 isa<ConstantSDNode>(LHS.getOperand(1)) && 9909 isa<ConstantSDNode>(LHS.getOperand(2)) && 9910 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9911 isBoolSGPR(LHS.getOperand(0))) { 9912 // Given CT != FT: 9913 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9914 // setcc (select cc, CT, CF), CF, ne => cc 9915 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9916 // setcc (select cc, CT, CF), CT, eq => cc 9917 uint64_t CT = LHS.getConstantOperandVal(1); 9918 uint64_t CF = LHS.getConstantOperandVal(2); 9919 9920 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9921 (CT == CRHSVal && CC == ISD::SETNE)) 9922 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9923 DAG.getConstant(-1, SL, MVT::i1)); 9924 if ((CF == CRHSVal && CC == ISD::SETNE) || 9925 (CT == CRHSVal && CC == ISD::SETEQ)) 9926 return LHS.getOperand(0); 9927 } 9928 } 9929 9930 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9931 VT != MVT::f16)) 9932 return SDValue(); 9933 9934 // Match isinf/isfinite pattern 9935 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9936 // (fcmp one (fabs x), inf) -> (fp_class x, 9937 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9938 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9939 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9940 if (!CRHS) 9941 return SDValue(); 9942 9943 const APFloat &APF = CRHS->getValueAPF(); 9944 if (APF.isInfinity() && !APF.isNegative()) { 9945 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9946 SIInstrFlags::N_INFINITY; 9947 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9948 SIInstrFlags::P_ZERO | 9949 SIInstrFlags::N_NORMAL | 9950 SIInstrFlags::P_NORMAL | 9951 SIInstrFlags::N_SUBNORMAL | 9952 SIInstrFlags::P_SUBNORMAL; 9953 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9954 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9955 DAG.getConstant(Mask, SL, MVT::i32)); 9956 } 9957 } 9958 9959 return SDValue(); 9960 } 9961 9962 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9963 DAGCombinerInfo &DCI) const { 9964 SelectionDAG &DAG = DCI.DAG; 9965 SDLoc SL(N); 9966 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9967 9968 SDValue Src = N->getOperand(0); 9969 SDValue Srl = N->getOperand(0); 9970 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9971 Srl = Srl.getOperand(0); 9972 9973 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9974 if (Srl.getOpcode() == ISD::SRL) { 9975 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9976 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9977 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9978 9979 if (const ConstantSDNode *C = 9980 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9981 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9982 EVT(MVT::i32)); 9983 9984 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9985 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9986 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9987 MVT::f32, Srl); 9988 } 9989 } 9990 } 9991 9992 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9993 9994 KnownBits Known; 9995 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9996 !DCI.isBeforeLegalizeOps()); 9997 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9998 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9999 DCI.CommitTargetLoweringOpt(TLO); 10000 } 10001 10002 return SDValue(); 10003 } 10004 10005 SDValue SITargetLowering::performClampCombine(SDNode *N, 10006 DAGCombinerInfo &DCI) const { 10007 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10008 if (!CSrc) 10009 return SDValue(); 10010 10011 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10012 const APFloat &F = CSrc->getValueAPF(); 10013 APFloat Zero = APFloat::getZero(F.getSemantics()); 10014 APFloat::cmpResult Cmp0 = F.compare(Zero); 10015 if (Cmp0 == APFloat::cmpLessThan || 10016 (Cmp0 == APFloat::cmpUnordered && 10017 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10018 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10019 } 10020 10021 APFloat One(F.getSemantics(), "1.0"); 10022 APFloat::cmpResult Cmp1 = F.compare(One); 10023 if (Cmp1 == APFloat::cmpGreaterThan) 10024 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10025 10026 return SDValue(CSrc, 0); 10027 } 10028 10029 10030 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10031 DAGCombinerInfo &DCI) const { 10032 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10033 return SDValue(); 10034 switch (N->getOpcode()) { 10035 default: 10036 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10037 case ISD::ADD: 10038 return performAddCombine(N, DCI); 10039 case ISD::SUB: 10040 return performSubCombine(N, DCI); 10041 case ISD::ADDCARRY: 10042 case ISD::SUBCARRY: 10043 return performAddCarrySubCarryCombine(N, DCI); 10044 case ISD::FADD: 10045 return performFAddCombine(N, DCI); 10046 case ISD::FSUB: 10047 return performFSubCombine(N, DCI); 10048 case ISD::SETCC: 10049 return performSetCCCombine(N, DCI); 10050 case ISD::FMAXNUM: 10051 case ISD::FMINNUM: 10052 case ISD::FMAXNUM_IEEE: 10053 case ISD::FMINNUM_IEEE: 10054 case ISD::SMAX: 10055 case ISD::SMIN: 10056 case ISD::UMAX: 10057 case ISD::UMIN: 10058 case AMDGPUISD::FMIN_LEGACY: 10059 case AMDGPUISD::FMAX_LEGACY: 10060 return performMinMaxCombine(N, DCI); 10061 case ISD::FMA: 10062 return performFMACombine(N, DCI); 10063 case ISD::LOAD: { 10064 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10065 return Widended; 10066 LLVM_FALLTHROUGH; 10067 } 10068 case ISD::STORE: 10069 case ISD::ATOMIC_LOAD: 10070 case ISD::ATOMIC_STORE: 10071 case ISD::ATOMIC_CMP_SWAP: 10072 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 10073 case ISD::ATOMIC_SWAP: 10074 case ISD::ATOMIC_LOAD_ADD: 10075 case ISD::ATOMIC_LOAD_SUB: 10076 case ISD::ATOMIC_LOAD_AND: 10077 case ISD::ATOMIC_LOAD_OR: 10078 case ISD::ATOMIC_LOAD_XOR: 10079 case ISD::ATOMIC_LOAD_NAND: 10080 case ISD::ATOMIC_LOAD_MIN: 10081 case ISD::ATOMIC_LOAD_MAX: 10082 case ISD::ATOMIC_LOAD_UMIN: 10083 case ISD::ATOMIC_LOAD_UMAX: 10084 case ISD::ATOMIC_LOAD_FADD: 10085 case AMDGPUISD::ATOMIC_INC: 10086 case AMDGPUISD::ATOMIC_DEC: 10087 case AMDGPUISD::ATOMIC_LOAD_FMIN: 10088 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 10089 if (DCI.isBeforeLegalize()) 10090 break; 10091 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 10092 case ISD::AND: 10093 return performAndCombine(N, DCI); 10094 case ISD::OR: 10095 return performOrCombine(N, DCI); 10096 case ISD::XOR: 10097 return performXorCombine(N, DCI); 10098 case ISD::ZERO_EXTEND: 10099 return performZeroExtendCombine(N, DCI); 10100 case ISD::SIGN_EXTEND_INREG: 10101 return performSignExtendInRegCombine(N , DCI); 10102 case AMDGPUISD::FP_CLASS: 10103 return performClassCombine(N, DCI); 10104 case ISD::FCANONICALIZE: 10105 return performFCanonicalizeCombine(N, DCI); 10106 case AMDGPUISD::RCP: 10107 return performRcpCombine(N, DCI); 10108 case AMDGPUISD::FRACT: 10109 case AMDGPUISD::RSQ: 10110 case AMDGPUISD::RCP_LEGACY: 10111 case AMDGPUISD::RSQ_LEGACY: 10112 case AMDGPUISD::RCP_IFLAG: 10113 case AMDGPUISD::RSQ_CLAMP: 10114 case AMDGPUISD::LDEXP: { 10115 SDValue Src = N->getOperand(0); 10116 if (Src.isUndef()) 10117 return Src; 10118 break; 10119 } 10120 case ISD::SINT_TO_FP: 10121 case ISD::UINT_TO_FP: 10122 return performUCharToFloatCombine(N, DCI); 10123 case AMDGPUISD::CVT_F32_UBYTE0: 10124 case AMDGPUISD::CVT_F32_UBYTE1: 10125 case AMDGPUISD::CVT_F32_UBYTE2: 10126 case AMDGPUISD::CVT_F32_UBYTE3: 10127 return performCvtF32UByteNCombine(N, DCI); 10128 case AMDGPUISD::FMED3: 10129 return performFMed3Combine(N, DCI); 10130 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10131 return performCvtPkRTZCombine(N, DCI); 10132 case AMDGPUISD::CLAMP: 10133 return performClampCombine(N, DCI); 10134 case ISD::SCALAR_TO_VECTOR: { 10135 SelectionDAG &DAG = DCI.DAG; 10136 EVT VT = N->getValueType(0); 10137 10138 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10139 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10140 SDLoc SL(N); 10141 SDValue Src = N->getOperand(0); 10142 EVT EltVT = Src.getValueType(); 10143 if (EltVT == MVT::f16) 10144 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10145 10146 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10147 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10148 } 10149 10150 break; 10151 } 10152 case ISD::EXTRACT_VECTOR_ELT: 10153 return performExtractVectorEltCombine(N, DCI); 10154 case ISD::INSERT_VECTOR_ELT: 10155 return performInsertVectorEltCombine(N, DCI); 10156 } 10157 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10158 } 10159 10160 /// Helper function for adjustWritemask 10161 static unsigned SubIdx2Lane(unsigned Idx) { 10162 switch (Idx) { 10163 default: return 0; 10164 case AMDGPU::sub0: return 0; 10165 case AMDGPU::sub1: return 1; 10166 case AMDGPU::sub2: return 2; 10167 case AMDGPU::sub3: return 3; 10168 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10169 } 10170 } 10171 10172 /// Adjust the writemask of MIMG instructions 10173 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10174 SelectionDAG &DAG) const { 10175 unsigned Opcode = Node->getMachineOpcode(); 10176 10177 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10178 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10179 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10180 return Node; // not implemented for D16 10181 10182 SDNode *Users[5] = { nullptr }; 10183 unsigned Lane = 0; 10184 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10185 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10186 unsigned NewDmask = 0; 10187 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10188 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10189 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10190 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10191 unsigned TFCLane = 0; 10192 bool HasChain = Node->getNumValues() > 1; 10193 10194 if (OldDmask == 0) { 10195 // These are folded out, but on the chance it happens don't assert. 10196 return Node; 10197 } 10198 10199 unsigned OldBitsSet = countPopulation(OldDmask); 10200 // Work out which is the TFE/LWE lane if that is enabled. 10201 if (UsesTFC) { 10202 TFCLane = OldBitsSet; 10203 } 10204 10205 // Try to figure out the used register components 10206 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10207 I != E; ++I) { 10208 10209 // Don't look at users of the chain. 10210 if (I.getUse().getResNo() != 0) 10211 continue; 10212 10213 // Abort if we can't understand the usage 10214 if (!I->isMachineOpcode() || 10215 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10216 return Node; 10217 10218 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10219 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10220 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10221 // set, etc. 10222 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10223 10224 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10225 if (UsesTFC && Lane == TFCLane) { 10226 Users[Lane] = *I; 10227 } else { 10228 // Set which texture component corresponds to the lane. 10229 unsigned Comp; 10230 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10231 Comp = countTrailingZeros(Dmask); 10232 Dmask &= ~(1 << Comp); 10233 } 10234 10235 // Abort if we have more than one user per component. 10236 if (Users[Lane]) 10237 return Node; 10238 10239 Users[Lane] = *I; 10240 NewDmask |= 1 << Comp; 10241 } 10242 } 10243 10244 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10245 bool NoChannels = !NewDmask; 10246 if (NoChannels) { 10247 if (!UsesTFC) { 10248 // No uses of the result and not using TFC. Then do nothing. 10249 return Node; 10250 } 10251 // If the original dmask has one channel - then nothing to do 10252 if (OldBitsSet == 1) 10253 return Node; 10254 // Use an arbitrary dmask - required for the instruction to work 10255 NewDmask = 1; 10256 } 10257 // Abort if there's no change 10258 if (NewDmask == OldDmask) 10259 return Node; 10260 10261 unsigned BitsSet = countPopulation(NewDmask); 10262 10263 // Check for TFE or LWE - increase the number of channels by one to account 10264 // for the extra return value 10265 // This will need adjustment for D16 if this is also included in 10266 // adjustWriteMask (this function) but at present D16 are excluded. 10267 unsigned NewChannels = BitsSet + UsesTFC; 10268 10269 int NewOpcode = 10270 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10271 assert(NewOpcode != -1 && 10272 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10273 "failed to find equivalent MIMG op"); 10274 10275 // Adjust the writemask in the node 10276 SmallVector<SDValue, 12> Ops; 10277 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10278 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10279 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10280 10281 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10282 10283 MVT ResultVT = NewChannels == 1 ? 10284 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10285 NewChannels == 5 ? 8 : NewChannels); 10286 SDVTList NewVTList = HasChain ? 10287 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10288 10289 10290 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10291 NewVTList, Ops); 10292 10293 if (HasChain) { 10294 // Update chain. 10295 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10296 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10297 } 10298 10299 if (NewChannels == 1) { 10300 assert(Node->hasNUsesOfValue(1, 0)); 10301 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10302 SDLoc(Node), Users[Lane]->getValueType(0), 10303 SDValue(NewNode, 0)); 10304 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10305 return nullptr; 10306 } 10307 10308 // Update the users of the node with the new indices 10309 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10310 SDNode *User = Users[i]; 10311 if (!User) { 10312 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10313 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10314 if (i || !NoChannels) 10315 continue; 10316 } else { 10317 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10318 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10319 } 10320 10321 switch (Idx) { 10322 default: break; 10323 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10324 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10325 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10326 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10327 } 10328 } 10329 10330 DAG.RemoveDeadNode(Node); 10331 return nullptr; 10332 } 10333 10334 static bool isFrameIndexOp(SDValue Op) { 10335 if (Op.getOpcode() == ISD::AssertZext) 10336 Op = Op.getOperand(0); 10337 10338 return isa<FrameIndexSDNode>(Op); 10339 } 10340 10341 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10342 /// with frame index operands. 10343 /// LLVM assumes that inputs are to these instructions are registers. 10344 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10345 SelectionDAG &DAG) const { 10346 if (Node->getOpcode() == ISD::CopyToReg) { 10347 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10348 SDValue SrcVal = Node->getOperand(2); 10349 10350 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10351 // to try understanding copies to physical registers. 10352 if (SrcVal.getValueType() == MVT::i1 && 10353 Register::isPhysicalRegister(DestReg->getReg())) { 10354 SDLoc SL(Node); 10355 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10356 SDValue VReg = DAG.getRegister( 10357 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10358 10359 SDNode *Glued = Node->getGluedNode(); 10360 SDValue ToVReg 10361 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10362 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10363 SDValue ToResultReg 10364 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10365 VReg, ToVReg.getValue(1)); 10366 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10367 DAG.RemoveDeadNode(Node); 10368 return ToResultReg.getNode(); 10369 } 10370 } 10371 10372 SmallVector<SDValue, 8> Ops; 10373 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10374 if (!isFrameIndexOp(Node->getOperand(i))) { 10375 Ops.push_back(Node->getOperand(i)); 10376 continue; 10377 } 10378 10379 SDLoc DL(Node); 10380 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10381 Node->getOperand(i).getValueType(), 10382 Node->getOperand(i)), 0)); 10383 } 10384 10385 return DAG.UpdateNodeOperands(Node, Ops); 10386 } 10387 10388 /// Fold the instructions after selecting them. 10389 /// Returns null if users were already updated. 10390 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10391 SelectionDAG &DAG) const { 10392 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10393 unsigned Opcode = Node->getMachineOpcode(); 10394 10395 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10396 !TII->isGather4(Opcode)) { 10397 return adjustWritemask(Node, DAG); 10398 } 10399 10400 if (Opcode == AMDGPU::INSERT_SUBREG || 10401 Opcode == AMDGPU::REG_SEQUENCE) { 10402 legalizeTargetIndependentNode(Node, DAG); 10403 return Node; 10404 } 10405 10406 switch (Opcode) { 10407 case AMDGPU::V_DIV_SCALE_F32: 10408 case AMDGPU::V_DIV_SCALE_F64: { 10409 // Satisfy the operand register constraint when one of the inputs is 10410 // undefined. Ordinarily each undef value will have its own implicit_def of 10411 // a vreg, so force these to use a single register. 10412 SDValue Src0 = Node->getOperand(0); 10413 SDValue Src1 = Node->getOperand(1); 10414 SDValue Src2 = Node->getOperand(2); 10415 10416 if ((Src0.isMachineOpcode() && 10417 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10418 (Src0 == Src1 || Src0 == Src2)) 10419 break; 10420 10421 MVT VT = Src0.getValueType().getSimpleVT(); 10422 const TargetRegisterClass *RC = 10423 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10424 10425 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10426 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10427 10428 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10429 UndefReg, Src0, SDValue()); 10430 10431 // src0 must be the same register as src1 or src2, even if the value is 10432 // undefined, so make sure we don't violate this constraint. 10433 if (Src0.isMachineOpcode() && 10434 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10435 if (Src1.isMachineOpcode() && 10436 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10437 Src0 = Src1; 10438 else if (Src2.isMachineOpcode() && 10439 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10440 Src0 = Src2; 10441 else { 10442 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10443 Src0 = UndefReg; 10444 Src1 = UndefReg; 10445 } 10446 } else 10447 break; 10448 10449 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10450 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10451 Ops.push_back(Node->getOperand(I)); 10452 10453 Ops.push_back(ImpDef.getValue(1)); 10454 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10455 } 10456 case AMDGPU::V_PERMLANE16_B32: 10457 case AMDGPU::V_PERMLANEX16_B32: { 10458 ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0)); 10459 ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2)); 10460 if (!FI->getZExtValue() && !BC->getZExtValue()) 10461 break; 10462 SDValue VDstIn = Node->getOperand(6); 10463 if (VDstIn.isMachineOpcode() 10464 && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) 10465 break; 10466 MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, 10467 SDLoc(Node), MVT::i32); 10468 SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1), 10469 SDValue(BC, 0), Node->getOperand(3), 10470 Node->getOperand(4), Node->getOperand(5), 10471 SDValue(ImpDef, 0), Node->getOperand(7) }; 10472 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10473 } 10474 default: 10475 break; 10476 } 10477 10478 return Node; 10479 } 10480 10481 /// Assign the register class depending on the number of 10482 /// bits set in the writemask 10483 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10484 SDNode *Node) const { 10485 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10486 10487 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10488 10489 if (TII->isVOP3(MI.getOpcode())) { 10490 // Make sure constant bus requirements are respected. 10491 TII->legalizeOperandsVOP3(MRI, MI); 10492 10493 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10494 // This saves a chain-copy of registers and better ballance register 10495 // use between vgpr and agpr as agpr tuples tend to be big. 10496 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10497 unsigned Opc = MI.getOpcode(); 10498 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10499 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10500 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10501 if (I == -1) 10502 break; 10503 MachineOperand &Op = MI.getOperand(I); 10504 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10505 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10506 !Register::isVirtualRegister(Op.getReg()) || 10507 !TRI->isAGPR(MRI, Op.getReg())) 10508 continue; 10509 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10510 if (!Src || !Src->isCopy() || 10511 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10512 continue; 10513 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10514 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10515 // All uses of agpr64 and agpr32 can also accept vgpr except for 10516 // v_accvgpr_read, but we do not produce agpr reads during selection, 10517 // so no use checks are needed. 10518 MRI.setRegClass(Op.getReg(), NewRC); 10519 } 10520 } 10521 10522 return; 10523 } 10524 10525 // Replace unused atomics with the no return version. 10526 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10527 if (NoRetAtomicOp != -1) { 10528 if (!Node->hasAnyUseOfValue(0)) { 10529 MI.setDesc(TII->get(NoRetAtomicOp)); 10530 MI.RemoveOperand(0); 10531 return; 10532 } 10533 10534 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10535 // instruction, because the return type of these instructions is a vec2 of 10536 // the memory type, so it can be tied to the input operand. 10537 // This means these instructions always have a use, so we need to add a 10538 // special case to check if the atomic has only one extract_subreg use, 10539 // which itself has no uses. 10540 if ((Node->hasNUsesOfValue(1, 0) && 10541 Node->use_begin()->isMachineOpcode() && 10542 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10543 !Node->use_begin()->hasAnyUseOfValue(0))) { 10544 Register Def = MI.getOperand(0).getReg(); 10545 10546 // Change this into a noret atomic. 10547 MI.setDesc(TII->get(NoRetAtomicOp)); 10548 MI.RemoveOperand(0); 10549 10550 // If we only remove the def operand from the atomic instruction, the 10551 // extract_subreg will be left with a use of a vreg without a def. 10552 // So we need to insert an implicit_def to avoid machine verifier 10553 // errors. 10554 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10555 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10556 } 10557 return; 10558 } 10559 } 10560 10561 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10562 uint64_t Val) { 10563 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10564 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10565 } 10566 10567 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10568 const SDLoc &DL, 10569 SDValue Ptr) const { 10570 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10571 10572 // Build the half of the subregister with the constants before building the 10573 // full 128-bit register. If we are building multiple resource descriptors, 10574 // this will allow CSEing of the 2-component register. 10575 const SDValue Ops0[] = { 10576 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10577 buildSMovImm32(DAG, DL, 0), 10578 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10579 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10580 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10581 }; 10582 10583 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10584 MVT::v2i32, Ops0), 0); 10585 10586 // Combine the constants and the pointer. 10587 const SDValue Ops1[] = { 10588 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10589 Ptr, 10590 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10591 SubRegHi, 10592 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10593 }; 10594 10595 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10596 } 10597 10598 /// Return a resource descriptor with the 'Add TID' bit enabled 10599 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10600 /// of the resource descriptor) to create an offset, which is added to 10601 /// the resource pointer. 10602 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10603 SDValue Ptr, uint32_t RsrcDword1, 10604 uint64_t RsrcDword2And3) const { 10605 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10606 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10607 if (RsrcDword1) { 10608 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10609 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10610 0); 10611 } 10612 10613 SDValue DataLo = buildSMovImm32(DAG, DL, 10614 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10615 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10616 10617 const SDValue Ops[] = { 10618 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10619 PtrLo, 10620 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10621 PtrHi, 10622 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10623 DataLo, 10624 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10625 DataHi, 10626 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10627 }; 10628 10629 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10630 } 10631 10632 //===----------------------------------------------------------------------===// 10633 // SI Inline Assembly Support 10634 //===----------------------------------------------------------------------===// 10635 10636 std::pair<unsigned, const TargetRegisterClass *> 10637 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10638 StringRef Constraint, 10639 MVT VT) const { 10640 const TargetRegisterClass *RC = nullptr; 10641 if (Constraint.size() == 1) { 10642 switch (Constraint[0]) { 10643 default: 10644 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10645 case 's': 10646 case 'r': 10647 switch (VT.getSizeInBits()) { 10648 default: 10649 return std::make_pair(0U, nullptr); 10650 case 32: 10651 case 16: 10652 RC = &AMDGPU::SReg_32RegClass; 10653 break; 10654 case 64: 10655 RC = &AMDGPU::SGPR_64RegClass; 10656 break; 10657 case 96: 10658 RC = &AMDGPU::SReg_96RegClass; 10659 break; 10660 case 128: 10661 RC = &AMDGPU::SGPR_128RegClass; 10662 break; 10663 case 160: 10664 RC = &AMDGPU::SReg_160RegClass; 10665 break; 10666 case 256: 10667 RC = &AMDGPU::SReg_256RegClass; 10668 break; 10669 case 512: 10670 RC = &AMDGPU::SReg_512RegClass; 10671 break; 10672 } 10673 break; 10674 case 'v': 10675 switch (VT.getSizeInBits()) { 10676 default: 10677 return std::make_pair(0U, nullptr); 10678 case 32: 10679 case 16: 10680 RC = &AMDGPU::VGPR_32RegClass; 10681 break; 10682 case 64: 10683 RC = &AMDGPU::VReg_64RegClass; 10684 break; 10685 case 96: 10686 RC = &AMDGPU::VReg_96RegClass; 10687 break; 10688 case 128: 10689 RC = &AMDGPU::VReg_128RegClass; 10690 break; 10691 case 160: 10692 RC = &AMDGPU::VReg_160RegClass; 10693 break; 10694 case 256: 10695 RC = &AMDGPU::VReg_256RegClass; 10696 break; 10697 case 512: 10698 RC = &AMDGPU::VReg_512RegClass; 10699 break; 10700 } 10701 break; 10702 case 'a': 10703 if (!Subtarget->hasMAIInsts()) 10704 break; 10705 switch (VT.getSizeInBits()) { 10706 default: 10707 return std::make_pair(0U, nullptr); 10708 case 32: 10709 case 16: 10710 RC = &AMDGPU::AGPR_32RegClass; 10711 break; 10712 case 64: 10713 RC = &AMDGPU::AReg_64RegClass; 10714 break; 10715 case 128: 10716 RC = &AMDGPU::AReg_128RegClass; 10717 break; 10718 case 512: 10719 RC = &AMDGPU::AReg_512RegClass; 10720 break; 10721 case 1024: 10722 RC = &AMDGPU::AReg_1024RegClass; 10723 // v32 types are not legal but we support them here. 10724 return std::make_pair(0U, RC); 10725 } 10726 break; 10727 } 10728 // We actually support i128, i16 and f16 as inline parameters 10729 // even if they are not reported as legal 10730 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10731 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10732 return std::make_pair(0U, RC); 10733 } 10734 10735 if (Constraint.size() > 1) { 10736 if (Constraint[1] == 'v') { 10737 RC = &AMDGPU::VGPR_32RegClass; 10738 } else if (Constraint[1] == 's') { 10739 RC = &AMDGPU::SGPR_32RegClass; 10740 } else if (Constraint[1] == 'a') { 10741 RC = &AMDGPU::AGPR_32RegClass; 10742 } 10743 10744 if (RC) { 10745 uint32_t Idx; 10746 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10747 if (!Failed && Idx < RC->getNumRegs()) 10748 return std::make_pair(RC->getRegister(Idx), RC); 10749 } 10750 } 10751 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10752 } 10753 10754 SITargetLowering::ConstraintType 10755 SITargetLowering::getConstraintType(StringRef Constraint) const { 10756 if (Constraint.size() == 1) { 10757 switch (Constraint[0]) { 10758 default: break; 10759 case 's': 10760 case 'v': 10761 case 'a': 10762 return C_RegisterClass; 10763 } 10764 } 10765 return TargetLowering::getConstraintType(Constraint); 10766 } 10767 10768 // Figure out which registers should be reserved for stack access. Only after 10769 // the function is legalized do we know all of the non-spill stack objects or if 10770 // calls are present. 10771 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10772 MachineRegisterInfo &MRI = MF.getRegInfo(); 10773 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10774 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10775 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10776 10777 if (Info->isEntryFunction()) { 10778 // Callable functions have fixed registers used for stack access. 10779 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10780 } 10781 10782 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10783 Info->getStackPtrOffsetReg())); 10784 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10785 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10786 10787 // We need to worry about replacing the default register with itself in case 10788 // of MIR testcases missing the MFI. 10789 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10790 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10791 10792 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10793 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10794 10795 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10796 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10797 Info->getScratchWaveOffsetReg()); 10798 } 10799 10800 Info->limitOccupancy(MF); 10801 10802 if (ST.isWave32() && !MF.empty()) { 10803 // Add VCC_HI def because many instructions marked as imp-use VCC where 10804 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10805 // having a use of undef. 10806 10807 const SIInstrInfo *TII = ST.getInstrInfo(); 10808 DebugLoc DL; 10809 10810 MachineBasicBlock &MBB = MF.front(); 10811 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10812 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10813 10814 for (auto &MBB : MF) { 10815 for (auto &MI : MBB) { 10816 TII->fixImplicitOperands(MI); 10817 } 10818 } 10819 } 10820 10821 TargetLoweringBase::finalizeLowering(MF); 10822 } 10823 10824 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10825 KnownBits &Known, 10826 const APInt &DemandedElts, 10827 const SelectionDAG &DAG, 10828 unsigned Depth) const { 10829 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10830 DAG, Depth); 10831 10832 // Set the high bits to zero based on the maximum allowed scratch size per 10833 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10834 // calculation won't overflow, so assume the sign bit is never set. 10835 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10836 } 10837 10838 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10839 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10840 const Align CacheLineAlign = Align(64); 10841 10842 // Pre-GFX10 target did not benefit from loop alignment 10843 if (!ML || DisableLoopAlignment || 10844 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10845 getSubtarget()->hasInstFwdPrefetchBug()) 10846 return PrefAlign; 10847 10848 // On GFX10 I$ is 4 x 64 bytes cache lines. 10849 // By default prefetcher keeps one cache line behind and reads two ahead. 10850 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10851 // behind and one ahead. 10852 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10853 // If loop fits 64 bytes it always spans no more than two cache lines and 10854 // does not need an alignment. 10855 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10856 // Else if loop is less or equal 192 bytes we need two lines behind. 10857 10858 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10859 const MachineBasicBlock *Header = ML->getHeader(); 10860 if (Header->getAlignment() != PrefAlign) 10861 return Header->getAlignment(); // Already processed. 10862 10863 unsigned LoopSize = 0; 10864 for (const MachineBasicBlock *MBB : ML->blocks()) { 10865 // If inner loop block is aligned assume in average half of the alignment 10866 // size to be added as nops. 10867 if (MBB != Header) 10868 LoopSize += MBB->getAlignment().value() / 2; 10869 10870 for (const MachineInstr &MI : *MBB) { 10871 LoopSize += TII->getInstSizeInBytes(MI); 10872 if (LoopSize > 192) 10873 return PrefAlign; 10874 } 10875 } 10876 10877 if (LoopSize <= 64) 10878 return PrefAlign; 10879 10880 if (LoopSize <= 128) 10881 return CacheLineAlign; 10882 10883 // If any of parent loops is surrounded by prefetch instructions do not 10884 // insert new for inner loop, which would reset parent's settings. 10885 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10886 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10887 auto I = Exit->getFirstNonDebugInstr(); 10888 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10889 return CacheLineAlign; 10890 } 10891 } 10892 10893 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10894 MachineBasicBlock *Exit = ML->getExitBlock(); 10895 10896 if (Pre && Exit) { 10897 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10898 TII->get(AMDGPU::S_INST_PREFETCH)) 10899 .addImm(1); // prefetch 2 lines behind PC 10900 10901 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10902 TII->get(AMDGPU::S_INST_PREFETCH)) 10903 .addImm(2); // prefetch 1 line behind PC 10904 } 10905 10906 return CacheLineAlign; 10907 } 10908 10909 LLVM_ATTRIBUTE_UNUSED 10910 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10911 assert(N->getOpcode() == ISD::CopyFromReg); 10912 do { 10913 // Follow the chain until we find an INLINEASM node. 10914 N = N->getOperand(0).getNode(); 10915 if (N->getOpcode() == ISD::INLINEASM || 10916 N->getOpcode() == ISD::INLINEASM_BR) 10917 return true; 10918 } while (N->getOpcode() == ISD::CopyFromReg); 10919 return false; 10920 } 10921 10922 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10923 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10924 { 10925 switch (N->getOpcode()) { 10926 case ISD::CopyFromReg: 10927 { 10928 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10929 const MachineFunction * MF = FLI->MF; 10930 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10931 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10932 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10933 unsigned Reg = R->getReg(); 10934 if (Register::isPhysicalRegister(Reg)) 10935 return !TRI.isSGPRReg(MRI, Reg); 10936 10937 if (MRI.isLiveIn(Reg)) { 10938 // workitem.id.x workitem.id.y workitem.id.z 10939 // Any VGPR formal argument is also considered divergent 10940 if (!TRI.isSGPRReg(MRI, Reg)) 10941 return true; 10942 // Formal arguments of non-entry functions 10943 // are conservatively considered divergent 10944 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10945 return true; 10946 return false; 10947 } 10948 const Value *V = FLI->getValueFromVirtualReg(Reg); 10949 if (V) 10950 return KDA->isDivergent(V); 10951 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10952 return !TRI.isSGPRReg(MRI, Reg); 10953 } 10954 break; 10955 case ISD::LOAD: { 10956 const LoadSDNode *L = cast<LoadSDNode>(N); 10957 unsigned AS = L->getAddressSpace(); 10958 // A flat load may access private memory. 10959 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10960 } break; 10961 case ISD::CALLSEQ_END: 10962 return true; 10963 break; 10964 case ISD::INTRINSIC_WO_CHAIN: 10965 { 10966 10967 } 10968 return AMDGPU::isIntrinsicSourceOfDivergence( 10969 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10970 case ISD::INTRINSIC_W_CHAIN: 10971 return AMDGPU::isIntrinsicSourceOfDivergence( 10972 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10973 } 10974 return false; 10975 } 10976 10977 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10978 EVT VT) const { 10979 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10980 case MVT::f32: 10981 return hasFP32Denormals(DAG.getMachineFunction()); 10982 case MVT::f64: 10983 case MVT::f16: 10984 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10985 default: 10986 return false; 10987 } 10988 } 10989 10990 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10991 const SelectionDAG &DAG, 10992 bool SNaN, 10993 unsigned Depth) const { 10994 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10995 const MachineFunction &MF = DAG.getMachineFunction(); 10996 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10997 10998 if (Info->getMode().DX10Clamp) 10999 return true; // Clamped to 0. 11000 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11001 } 11002 11003 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11004 SNaN, Depth); 11005 } 11006 11007 TargetLowering::AtomicExpansionKind 11008 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11009 switch (RMW->getOperation()) { 11010 case AtomicRMWInst::FAdd: { 11011 Type *Ty = RMW->getType(); 11012 11013 // We don't have a way to support 16-bit atomics now, so just leave them 11014 // as-is. 11015 if (Ty->isHalfTy()) 11016 return AtomicExpansionKind::None; 11017 11018 if (!Ty->isFloatTy()) 11019 return AtomicExpansionKind::CmpXChg; 11020 11021 // TODO: Do have these for flat. Older targets also had them for buffers. 11022 unsigned AS = RMW->getPointerAddressSpace(); 11023 11024 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 11025 return RMW->use_empty() ? AtomicExpansionKind::None : 11026 AtomicExpansionKind::CmpXChg; 11027 } 11028 11029 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 11030 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 11031 } 11032 default: 11033 break; 11034 } 11035 11036 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11037 } 11038 11039 const TargetRegisterClass * 11040 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11041 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11042 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11043 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11044 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11045 : &AMDGPU::SReg_32RegClass; 11046 if (!TRI->isSGPRClass(RC) && !isDivergent) 11047 return TRI->getEquivalentSGPRClass(RC); 11048 else if (TRI->isSGPRClass(RC) && isDivergent) 11049 return TRI->getEquivalentVGPRClass(RC); 11050 11051 return RC; 11052 } 11053 11054 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) { 11055 if (!Visited.insert(V).second) 11056 return false; 11057 bool Result = false; 11058 for (auto U : V->users()) { 11059 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 11060 if (V == U->getOperand(1)) { 11061 switch (Intrinsic->getIntrinsicID()) { 11062 default: 11063 Result = false; 11064 break; 11065 case Intrinsic::amdgcn_if_break: 11066 case Intrinsic::amdgcn_if: 11067 case Intrinsic::amdgcn_else: 11068 Result = true; 11069 break; 11070 } 11071 } 11072 if (V == U->getOperand(0)) { 11073 switch (Intrinsic->getIntrinsicID()) { 11074 default: 11075 Result = false; 11076 break; 11077 case Intrinsic::amdgcn_end_cf: 11078 case Intrinsic::amdgcn_loop: 11079 Result = true; 11080 break; 11081 } 11082 } 11083 } else { 11084 Result = hasCFUser(U, Visited); 11085 } 11086 if (Result) 11087 break; 11088 } 11089 return Result; 11090 } 11091 11092 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 11093 const Value *V) const { 11094 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 11095 switch (Intrinsic->getIntrinsicID()) { 11096 default: 11097 return false; 11098 case Intrinsic::amdgcn_if_break: 11099 return true; 11100 } 11101 } 11102 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 11103 if (const IntrinsicInst *Intrinsic = 11104 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 11105 switch (Intrinsic->getIntrinsicID()) { 11106 default: 11107 return false; 11108 case Intrinsic::amdgcn_if: 11109 case Intrinsic::amdgcn_else: { 11110 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 11111 if (Indices.size() == 1 && Indices[0] == 1) { 11112 return true; 11113 } 11114 } 11115 } 11116 } 11117 } 11118 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 11119 if (isa<InlineAsm>(CI->getCalledValue())) { 11120 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 11121 ImmutableCallSite CS(CI); 11122 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 11123 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 11124 for (auto &TC : TargetConstraints) { 11125 if (TC.Type == InlineAsm::isOutput) { 11126 ComputeConstraintToUse(TC, SDValue()); 11127 unsigned AssignedReg; 11128 const TargetRegisterClass *RC; 11129 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 11130 SIRI, TC.ConstraintCode, TC.ConstraintVT); 11131 if (RC) { 11132 MachineRegisterInfo &MRI = MF.getRegInfo(); 11133 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 11134 return true; 11135 else if (SIRI->isSGPRClass(RC)) 11136 return true; 11137 } 11138 } 11139 } 11140 } 11141 } 11142 SmallPtrSet<const Value *, 16> Visited; 11143 return hasCFUser(V, Visited); 11144 } 11145