1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 /// \file 10 /// Custom DAG lowering for SI 11 // 12 //===----------------------------------------------------------------------===// 13 14 #if defined(_MSC_VER) || defined(__MINGW32__) 15 // Provide M_PI. 16 #define _USE_MATH_DEFINES 17 #endif 18 19 #include "SIISelLowering.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "SIDefines.h" 25 #include "SIInstrInfo.h" 26 #include "SIMachineFunctionInfo.h" 27 #include "SIRegisterInfo.h" 28 #include "Utils/AMDGPUBaseInfo.h" 29 #include "llvm/ADT/APFloat.h" 30 #include "llvm/ADT/APInt.h" 31 #include "llvm/ADT/ArrayRef.h" 32 #include "llvm/ADT/BitVector.h" 33 #include "llvm/ADT/SmallVector.h" 34 #include "llvm/ADT/Statistic.h" 35 #include "llvm/ADT/StringRef.h" 36 #include "llvm/ADT/StringSwitch.h" 37 #include "llvm/ADT/Twine.h" 38 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 39 #include "llvm/CodeGen/Analysis.h" 40 #include "llvm/CodeGen/CallingConvLower.h" 41 #include "llvm/CodeGen/DAGCombine.h" 42 #include "llvm/CodeGen/ISDOpcodes.h" 43 #include "llvm/CodeGen/MachineBasicBlock.h" 44 #include "llvm/CodeGen/MachineFrameInfo.h" 45 #include "llvm/CodeGen/MachineFunction.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBuilder.h" 48 #include "llvm/CodeGen/MachineLoopInfo.h" 49 #include "llvm/CodeGen/MachineMemOperand.h" 50 #include "llvm/CodeGen/MachineModuleInfo.h" 51 #include "llvm/CodeGen/MachineOperand.h" 52 #include "llvm/CodeGen/MachineRegisterInfo.h" 53 #include "llvm/CodeGen/SelectionDAG.h" 54 #include "llvm/CodeGen/SelectionDAGNodes.h" 55 #include "llvm/CodeGen/TargetCallingConv.h" 56 #include "llvm/CodeGen/TargetRegisterInfo.h" 57 #include "llvm/CodeGen/ValueTypes.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugLoc.h" 61 #include "llvm/IR/DerivedTypes.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Function.h" 64 #include "llvm/IR/GlobalValue.h" 65 #include "llvm/IR/InstrTypes.h" 66 #include "llvm/IR/Instruction.h" 67 #include "llvm/IR/Instructions.h" 68 #include "llvm/IR/IntrinsicInst.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/Support/Casting.h" 71 #include "llvm/Support/CodeGen.h" 72 #include "llvm/Support/CommandLine.h" 73 #include "llvm/Support/Compiler.h" 74 #include "llvm/Support/ErrorHandling.h" 75 #include "llvm/Support/KnownBits.h" 76 #include "llvm/Support/MachineValueType.h" 77 #include "llvm/Support/MathExtras.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <cassert> 80 #include <cmath> 81 #include <cstdint> 82 #include <iterator> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 #define DEBUG_TYPE "si-lower" 90 91 STATISTIC(NumTailCalls, "Number of tail calls"); 92 93 static cl::opt<bool> DisableLoopAlignment( 94 "amdgpu-disable-loop-alignment", 95 cl::desc("Do not align and prefetch loops"), 96 cl::init(false)); 97 98 static bool hasFP32Denormals(const MachineFunction &MF) { 99 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 100 return Info->getMode().FP32Denormals; 101 } 102 103 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 104 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 105 return Info->getMode().FP64FP16Denormals; 106 } 107 108 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 109 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 110 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 111 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 112 return AMDGPU::SGPR0 + Reg; 113 } 114 } 115 llvm_unreachable("Cannot allocate sgpr"); 116 } 117 118 SITargetLowering::SITargetLowering(const TargetMachine &TM, 119 const GCNSubtarget &STI) 120 : AMDGPUTargetLowering(TM, STI), 121 Subtarget(&STI) { 122 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 123 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 124 125 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 126 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 127 128 addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass); 129 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 130 addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass); 131 132 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 133 addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass); 134 135 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 136 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 137 138 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 139 addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass); 140 141 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 142 addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass); 143 144 addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass); 145 addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass); 146 147 addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass); 148 addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass); 149 150 if (Subtarget->has16BitInsts()) { 151 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 152 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 153 154 // Unless there are also VOP3P operations, not operations are really legal. 155 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 156 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 157 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 158 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 159 } 160 161 if (Subtarget->hasMAIInsts()) { 162 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 163 addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass); 164 } 165 166 computeRegisterProperties(Subtarget->getRegisterInfo()); 167 168 // The boolean content concept here is too inflexible. Compares only ever 169 // really produce a 1-bit result. Any copy/extend from these will turn into a 170 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 171 // it's what most targets use. 172 setBooleanContents(ZeroOrOneBooleanContent); 173 setBooleanVectorContents(ZeroOrOneBooleanContent); 174 175 // We need to custom lower vector stores from local memory 176 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 177 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 178 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 179 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 180 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 181 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 182 setOperationAction(ISD::LOAD, MVT::i1, Custom); 183 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 184 185 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 186 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 187 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 188 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 189 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 190 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 191 setOperationAction(ISD::STORE, MVT::i1, Custom); 192 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 193 194 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 195 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 196 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 197 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 198 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 199 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 200 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 201 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 202 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 203 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 204 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 205 206 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 208 209 setOperationAction(ISD::SELECT, MVT::i1, Promote); 210 setOperationAction(ISD::SELECT, MVT::i64, Custom); 211 setOperationAction(ISD::SELECT, MVT::f64, Promote); 212 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 213 214 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 215 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 216 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 217 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 218 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 219 220 setOperationAction(ISD::SETCC, MVT::i1, Promote); 221 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 222 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 223 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 224 225 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 226 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 227 228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 236 237 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 238 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 239 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 240 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 241 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 242 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 243 244 setOperationAction(ISD::UADDO, MVT::i32, Legal); 245 setOperationAction(ISD::USUBO, MVT::i32, Legal); 246 247 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 248 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 249 250 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 251 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 252 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 253 254 #if 0 255 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 256 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 257 #endif 258 259 // We only support LOAD/STORE and vector manipulation ops for vectors 260 // with > 4 elements. 261 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 262 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 263 MVT::v32i32, MVT::v32f32 }) { 264 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 265 switch (Op) { 266 case ISD::LOAD: 267 case ISD::STORE: 268 case ISD::BUILD_VECTOR: 269 case ISD::BITCAST: 270 case ISD::EXTRACT_VECTOR_ELT: 271 case ISD::INSERT_VECTOR_ELT: 272 case ISD::INSERT_SUBVECTOR: 273 case ISD::EXTRACT_SUBVECTOR: 274 case ISD::SCALAR_TO_VECTOR: 275 break; 276 case ISD::CONCAT_VECTORS: 277 setOperationAction(Op, VT, Custom); 278 break; 279 default: 280 setOperationAction(Op, VT, Expand); 281 break; 282 } 283 } 284 } 285 286 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 287 288 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 289 // is expanded to avoid having two separate loops in case the index is a VGPR. 290 291 // Most operations are naturally 32-bit vector operations. We only support 292 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 293 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 294 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 295 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 296 297 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 298 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 299 300 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 301 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 302 303 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 304 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 305 } 306 307 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 308 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 309 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 310 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 311 312 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 313 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 314 315 // Avoid stack access for these. 316 // TODO: Generalize to more vector types. 317 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 318 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 319 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 320 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 321 322 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 324 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 325 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 326 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 327 328 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 329 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 330 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 331 332 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 333 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 334 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 335 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 336 337 // Deal with vec3 vector operations when widened to vec4. 338 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 339 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 340 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 341 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 342 343 // Deal with vec5 vector operations when widened to vec8. 344 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 345 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 346 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 347 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 348 349 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 350 // and output demarshalling 351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 352 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 353 354 // We can't return success/failure, only the old value, 355 // let LLVM add the comparison 356 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 357 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 358 359 if (Subtarget->hasFlatAddressSpace()) { 360 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 361 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 362 } 363 364 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 365 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 366 367 // On SI this is s_memtime and s_memrealtime on VI. 368 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 369 setOperationAction(ISD::TRAP, MVT::Other, Custom); 370 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 371 372 if (Subtarget->has16BitInsts()) { 373 setOperationAction(ISD::FPOW, MVT::f16, Promote); 374 setOperationAction(ISD::FLOG, MVT::f16, Custom); 375 setOperationAction(ISD::FEXP, MVT::f16, Custom); 376 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 377 } 378 379 // v_mad_f32 does not support denormals. We report it as unconditionally 380 // legal, and the context where it is formed will disallow it when fp32 381 // denormals are enabled. 382 setOperationAction(ISD::FMAD, MVT::f32, Legal); 383 384 if (!Subtarget->hasBFI()) { 385 // fcopysign can be done in a single instruction with BFI. 386 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 387 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 388 } 389 390 if (!Subtarget->hasBCNT(32)) 391 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 392 393 if (!Subtarget->hasBCNT(64)) 394 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 395 396 if (Subtarget->hasFFBH()) 397 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 398 399 if (Subtarget->hasFFBL()) 400 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 401 402 // We only really have 32-bit BFE instructions (and 16-bit on VI). 403 // 404 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 405 // effort to match them now. We want this to be false for i64 cases when the 406 // extraction isn't restricted to the upper or lower half. Ideally we would 407 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 408 // span the midpoint are probably relatively rare, so don't worry about them 409 // for now. 410 if (Subtarget->hasBFE()) 411 setHasExtractBitsInsn(true); 412 413 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 414 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 415 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 416 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 417 418 419 // These are really only legal for ieee_mode functions. We should be avoiding 420 // them for functions that don't have ieee_mode enabled, so just say they are 421 // legal. 422 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 423 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 424 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 425 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 426 427 428 if (Subtarget->haveRoundOpsF64()) { 429 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 430 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 431 setOperationAction(ISD::FRINT, MVT::f64, Legal); 432 } else { 433 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 434 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 435 setOperationAction(ISD::FRINT, MVT::f64, Custom); 436 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 437 } 438 439 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 440 441 setOperationAction(ISD::FSIN, MVT::f32, Custom); 442 setOperationAction(ISD::FCOS, MVT::f32, Custom); 443 setOperationAction(ISD::FDIV, MVT::f32, Custom); 444 setOperationAction(ISD::FDIV, MVT::f64, Custom); 445 446 if (Subtarget->has16BitInsts()) { 447 setOperationAction(ISD::Constant, MVT::i16, Legal); 448 449 setOperationAction(ISD::SMIN, MVT::i16, Legal); 450 setOperationAction(ISD::SMAX, MVT::i16, Legal); 451 452 setOperationAction(ISD::UMIN, MVT::i16, Legal); 453 setOperationAction(ISD::UMAX, MVT::i16, Legal); 454 455 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 456 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 457 458 setOperationAction(ISD::ROTR, MVT::i16, Promote); 459 setOperationAction(ISD::ROTL, MVT::i16, Promote); 460 461 setOperationAction(ISD::SDIV, MVT::i16, Promote); 462 setOperationAction(ISD::UDIV, MVT::i16, Promote); 463 setOperationAction(ISD::SREM, MVT::i16, Promote); 464 setOperationAction(ISD::UREM, MVT::i16, Promote); 465 466 setOperationAction(ISD::BSWAP, MVT::i16, Promote); 467 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 468 469 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 470 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 471 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 472 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 473 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 474 475 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 476 477 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 478 479 setOperationAction(ISD::LOAD, MVT::i16, Custom); 480 481 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 482 483 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 484 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 485 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 486 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 487 488 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 489 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 490 491 // F16 - Constant Actions. 492 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 493 494 // F16 - Load/Store Actions. 495 setOperationAction(ISD::LOAD, MVT::f16, Promote); 496 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 497 setOperationAction(ISD::STORE, MVT::f16, Promote); 498 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 499 500 // F16 - VOP1 Actions. 501 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 502 setOperationAction(ISD::FCOS, MVT::f16, Custom); 503 setOperationAction(ISD::FSIN, MVT::f16, Custom); 504 505 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 506 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 507 508 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 509 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 510 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 511 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 512 setOperationAction(ISD::FROUND, MVT::f16, Custom); 513 514 // F16 - VOP2 Actions. 515 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 516 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 517 518 setOperationAction(ISD::FDIV, MVT::f16, Custom); 519 520 // F16 - VOP3 Actions. 521 setOperationAction(ISD::FMA, MVT::f16, Legal); 522 if (STI.hasMadF16()) 523 setOperationAction(ISD::FMAD, MVT::f16, Legal); 524 525 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 526 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 527 switch (Op) { 528 case ISD::LOAD: 529 case ISD::STORE: 530 case ISD::BUILD_VECTOR: 531 case ISD::BITCAST: 532 case ISD::EXTRACT_VECTOR_ELT: 533 case ISD::INSERT_VECTOR_ELT: 534 case ISD::INSERT_SUBVECTOR: 535 case ISD::EXTRACT_SUBVECTOR: 536 case ISD::SCALAR_TO_VECTOR: 537 break; 538 case ISD::CONCAT_VECTORS: 539 setOperationAction(Op, VT, Custom); 540 break; 541 default: 542 setOperationAction(Op, VT, Expand); 543 break; 544 } 545 } 546 } 547 548 // XXX - Do these do anything? Vector constants turn into build_vector. 549 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 550 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 551 552 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 553 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 554 555 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 556 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 557 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 558 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 559 560 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 561 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 562 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 563 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 564 565 setOperationAction(ISD::AND, MVT::v2i16, Promote); 566 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 567 setOperationAction(ISD::OR, MVT::v2i16, Promote); 568 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 569 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 570 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 571 572 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 573 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 574 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 575 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 576 577 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 578 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 579 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 580 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 581 582 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 583 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 584 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 585 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 586 587 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 588 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 589 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 590 591 if (!Subtarget->hasVOP3PInsts()) { 592 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 593 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 594 } 595 596 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 597 // This isn't really legal, but this avoids the legalizer unrolling it (and 598 // allows matching fneg (fabs x) patterns) 599 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 600 601 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 602 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 603 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 604 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 605 606 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 607 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 608 609 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 610 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 611 } 612 613 if (Subtarget->hasVOP3PInsts()) { 614 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 615 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 616 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 617 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 618 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 619 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 620 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 621 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 622 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 623 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 624 625 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 626 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 627 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 628 629 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 630 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 631 632 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 633 634 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 635 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 636 637 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 638 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 639 640 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 641 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 642 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 643 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 644 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 645 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 646 647 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 648 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 649 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 650 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 651 652 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 653 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 654 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 655 656 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 657 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 658 659 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 660 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 661 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 662 663 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 664 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 665 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 666 } 667 668 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 669 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 670 671 if (Subtarget->has16BitInsts()) { 672 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 673 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 674 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 675 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 676 } else { 677 // Legalization hack. 678 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 679 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 680 681 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 682 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 683 } 684 685 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 686 setOperationAction(ISD::SELECT, VT, Custom); 687 } 688 689 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 690 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 691 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 692 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 693 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 694 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 695 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 696 697 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 698 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 699 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 700 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 701 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 702 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 703 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 704 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 705 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 706 707 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 708 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 709 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 710 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 711 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 712 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 713 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 714 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 715 716 setTargetDAGCombine(ISD::ADD); 717 setTargetDAGCombine(ISD::ADDCARRY); 718 setTargetDAGCombine(ISD::SUB); 719 setTargetDAGCombine(ISD::SUBCARRY); 720 setTargetDAGCombine(ISD::FADD); 721 setTargetDAGCombine(ISD::FSUB); 722 setTargetDAGCombine(ISD::FMINNUM); 723 setTargetDAGCombine(ISD::FMAXNUM); 724 setTargetDAGCombine(ISD::FMINNUM_IEEE); 725 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 726 setTargetDAGCombine(ISD::FMA); 727 setTargetDAGCombine(ISD::SMIN); 728 setTargetDAGCombine(ISD::SMAX); 729 setTargetDAGCombine(ISD::UMIN); 730 setTargetDAGCombine(ISD::UMAX); 731 setTargetDAGCombine(ISD::SETCC); 732 setTargetDAGCombine(ISD::AND); 733 setTargetDAGCombine(ISD::OR); 734 setTargetDAGCombine(ISD::XOR); 735 setTargetDAGCombine(ISD::SINT_TO_FP); 736 setTargetDAGCombine(ISD::UINT_TO_FP); 737 setTargetDAGCombine(ISD::FCANONICALIZE); 738 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 739 setTargetDAGCombine(ISD::ZERO_EXTEND); 740 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 741 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 742 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 743 744 // All memory operations. Some folding on the pointer operand is done to help 745 // matching the constant offsets in the addressing modes. 746 setTargetDAGCombine(ISD::LOAD); 747 setTargetDAGCombine(ISD::STORE); 748 setTargetDAGCombine(ISD::ATOMIC_LOAD); 749 setTargetDAGCombine(ISD::ATOMIC_STORE); 750 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 751 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 752 setTargetDAGCombine(ISD::ATOMIC_SWAP); 753 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 754 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 755 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 756 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 757 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 758 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 759 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 760 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 761 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 762 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 763 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 764 765 setSchedulingPreference(Sched::RegPressure); 766 } 767 768 const GCNSubtarget *SITargetLowering::getSubtarget() const { 769 return Subtarget; 770 } 771 772 //===----------------------------------------------------------------------===// 773 // TargetLowering queries 774 //===----------------------------------------------------------------------===// 775 776 // v_mad_mix* support a conversion from f16 to f32. 777 // 778 // There is only one special case when denormals are enabled we don't currently, 779 // where this is OK to use. 780 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 781 EVT DestVT, EVT SrcVT) const { 782 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 783 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 784 DestVT.getScalarType() == MVT::f32 && 785 SrcVT.getScalarType() == MVT::f16 && 786 !hasFP32Denormals(DAG.getMachineFunction()); 787 } 788 789 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 790 // SI has some legal vector types, but no legal vector operations. Say no 791 // shuffles are legal in order to prefer scalarizing some vector operations. 792 return false; 793 } 794 795 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 796 CallingConv::ID CC, 797 EVT VT) const { 798 if (CC == CallingConv::AMDGPU_KERNEL) 799 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 800 801 if (VT.isVector()) { 802 EVT ScalarVT = VT.getScalarType(); 803 unsigned Size = ScalarVT.getSizeInBits(); 804 if (Size == 32) 805 return ScalarVT.getSimpleVT(); 806 807 if (Size > 32) 808 return MVT::i32; 809 810 if (Size == 16 && Subtarget->has16BitInsts()) 811 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 812 } else if (VT.getSizeInBits() > 32) 813 return MVT::i32; 814 815 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 816 } 817 818 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 819 CallingConv::ID CC, 820 EVT VT) const { 821 if (CC == CallingConv::AMDGPU_KERNEL) 822 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 823 824 if (VT.isVector()) { 825 unsigned NumElts = VT.getVectorNumElements(); 826 EVT ScalarVT = VT.getScalarType(); 827 unsigned Size = ScalarVT.getSizeInBits(); 828 829 if (Size == 32) 830 return NumElts; 831 832 if (Size > 32) 833 return NumElts * ((Size + 31) / 32); 834 835 if (Size == 16 && Subtarget->has16BitInsts()) 836 return (NumElts + 1) / 2; 837 } else if (VT.getSizeInBits() > 32) 838 return (VT.getSizeInBits() + 31) / 32; 839 840 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 841 } 842 843 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 844 LLVMContext &Context, CallingConv::ID CC, 845 EVT VT, EVT &IntermediateVT, 846 unsigned &NumIntermediates, MVT &RegisterVT) const { 847 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 848 unsigned NumElts = VT.getVectorNumElements(); 849 EVT ScalarVT = VT.getScalarType(); 850 unsigned Size = ScalarVT.getSizeInBits(); 851 if (Size == 32) { 852 RegisterVT = ScalarVT.getSimpleVT(); 853 IntermediateVT = RegisterVT; 854 NumIntermediates = NumElts; 855 return NumIntermediates; 856 } 857 858 if (Size > 32) { 859 RegisterVT = MVT::i32; 860 IntermediateVT = RegisterVT; 861 NumIntermediates = NumElts * ((Size + 31) / 32); 862 return NumIntermediates; 863 } 864 865 // FIXME: We should fix the ABI to be the same on targets without 16-bit 866 // support, but unless we can properly handle 3-vectors, it will be still be 867 // inconsistent. 868 if (Size == 16 && Subtarget->has16BitInsts()) { 869 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 870 IntermediateVT = RegisterVT; 871 NumIntermediates = (NumElts + 1) / 2; 872 return NumIntermediates; 873 } 874 } 875 876 return TargetLowering::getVectorTypeBreakdownForCallingConv( 877 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 878 } 879 880 static MVT memVTFromAggregate(Type *Ty) { 881 // Only limited forms of aggregate type currently expected. 882 assert(Ty->isStructTy() && "Expected struct type"); 883 884 885 Type *ElementType = nullptr; 886 unsigned NumElts; 887 if (Ty->getContainedType(0)->isVectorTy()) { 888 VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0)); 889 ElementType = VecComponent->getElementType(); 890 NumElts = VecComponent->getNumElements(); 891 } else { 892 ElementType = Ty->getContainedType(0); 893 NumElts = 1; 894 } 895 896 assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type"); 897 898 // Calculate the size of the memVT type from the aggregate 899 unsigned Pow2Elts = 0; 900 unsigned ElementSize; 901 switch (ElementType->getTypeID()) { 902 default: 903 llvm_unreachable("Unknown type!"); 904 case Type::IntegerTyID: 905 ElementSize = cast<IntegerType>(ElementType)->getBitWidth(); 906 break; 907 case Type::HalfTyID: 908 ElementSize = 16; 909 break; 910 case Type::FloatTyID: 911 ElementSize = 32; 912 break; 913 } 914 unsigned AdditionalElts = ElementSize == 16 ? 2 : 1; 915 Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts); 916 917 return MVT::getVectorVT(MVT::getVT(ElementType, false), 918 Pow2Elts); 919 } 920 921 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 922 const CallInst &CI, 923 MachineFunction &MF, 924 unsigned IntrID) const { 925 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 926 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 927 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 928 (Intrinsic::ID)IntrID); 929 if (Attr.hasFnAttribute(Attribute::ReadNone)) 930 return false; 931 932 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 933 934 if (RsrcIntr->IsImage) { 935 Info.ptrVal = MFI->getImagePSV( 936 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 937 CI.getArgOperand(RsrcIntr->RsrcArg)); 938 Info.align.reset(); 939 } else { 940 Info.ptrVal = MFI->getBufferPSV( 941 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 942 CI.getArgOperand(RsrcIntr->RsrcArg)); 943 } 944 945 Info.flags = MachineMemOperand::MODereferenceable; 946 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 947 Info.opc = ISD::INTRINSIC_W_CHAIN; 948 Info.memVT = MVT::getVT(CI.getType(), true); 949 if (Info.memVT == MVT::Other) { 950 // Some intrinsics return an aggregate type - special case to work out 951 // the correct memVT 952 Info.memVT = memVTFromAggregate(CI.getType()); 953 } 954 Info.flags |= MachineMemOperand::MOLoad; 955 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 956 Info.opc = ISD::INTRINSIC_VOID; 957 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 958 Info.flags |= MachineMemOperand::MOStore; 959 } else { 960 // Atomic 961 Info.opc = ISD::INTRINSIC_W_CHAIN; 962 Info.memVT = MVT::getVT(CI.getType()); 963 Info.flags = MachineMemOperand::MOLoad | 964 MachineMemOperand::MOStore | 965 MachineMemOperand::MODereferenceable; 966 967 // XXX - Should this be volatile without known ordering? 968 Info.flags |= MachineMemOperand::MOVolatile; 969 } 970 return true; 971 } 972 973 switch (IntrID) { 974 case Intrinsic::amdgcn_atomic_inc: 975 case Intrinsic::amdgcn_atomic_dec: 976 case Intrinsic::amdgcn_ds_ordered_add: 977 case Intrinsic::amdgcn_ds_ordered_swap: 978 case Intrinsic::amdgcn_ds_fadd: 979 case Intrinsic::amdgcn_ds_fmin: 980 case Intrinsic::amdgcn_ds_fmax: { 981 Info.opc = ISD::INTRINSIC_W_CHAIN; 982 Info.memVT = MVT::getVT(CI.getType()); 983 Info.ptrVal = CI.getOperand(0); 984 Info.align.reset(); 985 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 986 987 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 988 if (!Vol->isZero()) 989 Info.flags |= MachineMemOperand::MOVolatile; 990 991 return true; 992 } 993 case Intrinsic::amdgcn_buffer_atomic_fadd: { 994 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 995 996 Info.opc = ISD::INTRINSIC_VOID; 997 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 998 Info.ptrVal = MFI->getBufferPSV( 999 *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), 1000 CI.getArgOperand(1)); 1001 Info.align.reset(); 1002 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1003 1004 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1005 if (!Vol || !Vol->isZero()) 1006 Info.flags |= MachineMemOperand::MOVolatile; 1007 1008 return true; 1009 } 1010 case Intrinsic::amdgcn_global_atomic_fadd: { 1011 Info.opc = ISD::INTRINSIC_VOID; 1012 Info.memVT = MVT::getVT(CI.getOperand(0)->getType() 1013 ->getPointerElementType()); 1014 Info.ptrVal = CI.getOperand(0); 1015 Info.align.reset(); 1016 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1017 1018 return true; 1019 } 1020 case Intrinsic::amdgcn_ds_append: 1021 case Intrinsic::amdgcn_ds_consume: { 1022 Info.opc = ISD::INTRINSIC_W_CHAIN; 1023 Info.memVT = MVT::getVT(CI.getType()); 1024 Info.ptrVal = CI.getOperand(0); 1025 Info.align.reset(); 1026 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1027 1028 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1029 if (!Vol->isZero()) 1030 Info.flags |= MachineMemOperand::MOVolatile; 1031 1032 return true; 1033 } 1034 case Intrinsic::amdgcn_ds_gws_init: 1035 case Intrinsic::amdgcn_ds_gws_barrier: 1036 case Intrinsic::amdgcn_ds_gws_sema_v: 1037 case Intrinsic::amdgcn_ds_gws_sema_br: 1038 case Intrinsic::amdgcn_ds_gws_sema_p: 1039 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1040 Info.opc = ISD::INTRINSIC_VOID; 1041 1042 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1043 Info.ptrVal = 1044 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1045 1046 // This is an abstract access, but we need to specify a type and size. 1047 Info.memVT = MVT::i32; 1048 Info.size = 4; 1049 Info.align = Align(4); 1050 1051 Info.flags = MachineMemOperand::MOStore; 1052 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1053 Info.flags = MachineMemOperand::MOLoad; 1054 return true; 1055 } 1056 default: 1057 return false; 1058 } 1059 } 1060 1061 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1062 SmallVectorImpl<Value*> &Ops, 1063 Type *&AccessTy) const { 1064 switch (II->getIntrinsicID()) { 1065 case Intrinsic::amdgcn_atomic_inc: 1066 case Intrinsic::amdgcn_atomic_dec: 1067 case Intrinsic::amdgcn_ds_ordered_add: 1068 case Intrinsic::amdgcn_ds_ordered_swap: 1069 case Intrinsic::amdgcn_ds_fadd: 1070 case Intrinsic::amdgcn_ds_fmin: 1071 case Intrinsic::amdgcn_ds_fmax: { 1072 Value *Ptr = II->getArgOperand(0); 1073 AccessTy = II->getType(); 1074 Ops.push_back(Ptr); 1075 return true; 1076 } 1077 default: 1078 return false; 1079 } 1080 } 1081 1082 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1083 if (!Subtarget->hasFlatInstOffsets()) { 1084 // Flat instructions do not have offsets, and only have the register 1085 // address. 1086 return AM.BaseOffs == 0 && AM.Scale == 0; 1087 } 1088 1089 return AM.Scale == 0 && 1090 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1091 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1092 /*Signed=*/false)); 1093 } 1094 1095 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1096 if (Subtarget->hasFlatGlobalInsts()) 1097 return AM.Scale == 0 && 1098 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1099 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1100 /*Signed=*/true)); 1101 1102 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1103 // Assume the we will use FLAT for all global memory accesses 1104 // on VI. 1105 // FIXME: This assumption is currently wrong. On VI we still use 1106 // MUBUF instructions for the r + i addressing mode. As currently 1107 // implemented, the MUBUF instructions only work on buffer < 4GB. 1108 // It may be possible to support > 4GB buffers with MUBUF instructions, 1109 // by setting the stride value in the resource descriptor which would 1110 // increase the size limit to (stride * 4GB). However, this is risky, 1111 // because it has never been validated. 1112 return isLegalFlatAddressingMode(AM); 1113 } 1114 1115 return isLegalMUBUFAddressingMode(AM); 1116 } 1117 1118 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1119 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1120 // additionally can do r + r + i with addr64. 32-bit has more addressing 1121 // mode options. Depending on the resource constant, it can also do 1122 // (i64 r0) + (i32 r1) * (i14 i). 1123 // 1124 // Private arrays end up using a scratch buffer most of the time, so also 1125 // assume those use MUBUF instructions. Scratch loads / stores are currently 1126 // implemented as mubuf instructions with offen bit set, so slightly 1127 // different than the normal addr64. 1128 if (!isUInt<12>(AM.BaseOffs)) 1129 return false; 1130 1131 // FIXME: Since we can split immediate into soffset and immediate offset, 1132 // would it make sense to allow any immediate? 1133 1134 switch (AM.Scale) { 1135 case 0: // r + i or just i, depending on HasBaseReg. 1136 return true; 1137 case 1: 1138 return true; // We have r + r or r + i. 1139 case 2: 1140 if (AM.HasBaseReg) { 1141 // Reject 2 * r + r. 1142 return false; 1143 } 1144 1145 // Allow 2 * r as r + r 1146 // Or 2 * r + i is allowed as r + r + i. 1147 return true; 1148 default: // Don't allow n * r 1149 return false; 1150 } 1151 } 1152 1153 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1154 const AddrMode &AM, Type *Ty, 1155 unsigned AS, Instruction *I) const { 1156 // No global is ever allowed as a base. 1157 if (AM.BaseGV) 1158 return false; 1159 1160 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1161 return isLegalGlobalAddressingMode(AM); 1162 1163 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1164 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1165 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1166 // If the offset isn't a multiple of 4, it probably isn't going to be 1167 // correctly aligned. 1168 // FIXME: Can we get the real alignment here? 1169 if (AM.BaseOffs % 4 != 0) 1170 return isLegalMUBUFAddressingMode(AM); 1171 1172 // There are no SMRD extloads, so if we have to do a small type access we 1173 // will use a MUBUF load. 1174 // FIXME?: We also need to do this if unaligned, but we don't know the 1175 // alignment here. 1176 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1177 return isLegalGlobalAddressingMode(AM); 1178 1179 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1180 // SMRD instructions have an 8-bit, dword offset on SI. 1181 if (!isUInt<8>(AM.BaseOffs / 4)) 1182 return false; 1183 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1184 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1185 // in 8-bits, it can use a smaller encoding. 1186 if (!isUInt<32>(AM.BaseOffs / 4)) 1187 return false; 1188 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1189 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1190 if (!isUInt<20>(AM.BaseOffs)) 1191 return false; 1192 } else 1193 llvm_unreachable("unhandled generation"); 1194 1195 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1196 return true; 1197 1198 if (AM.Scale == 1 && AM.HasBaseReg) 1199 return true; 1200 1201 return false; 1202 1203 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1204 return isLegalMUBUFAddressingMode(AM); 1205 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1206 AS == AMDGPUAS::REGION_ADDRESS) { 1207 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1208 // field. 1209 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1210 // an 8-bit dword offset but we don't know the alignment here. 1211 if (!isUInt<16>(AM.BaseOffs)) 1212 return false; 1213 1214 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1215 return true; 1216 1217 if (AM.Scale == 1 && AM.HasBaseReg) 1218 return true; 1219 1220 return false; 1221 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1222 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1223 // For an unknown address space, this usually means that this is for some 1224 // reason being used for pure arithmetic, and not based on some addressing 1225 // computation. We don't have instructions that compute pointers with any 1226 // addressing modes, so treat them as having no offset like flat 1227 // instructions. 1228 return isLegalFlatAddressingMode(AM); 1229 } else { 1230 llvm_unreachable("unhandled address space"); 1231 } 1232 } 1233 1234 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1235 const SelectionDAG &DAG) const { 1236 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1237 return (MemVT.getSizeInBits() <= 4 * 32); 1238 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1239 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1240 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1241 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1242 return (MemVT.getSizeInBits() <= 2 * 32); 1243 } 1244 return true; 1245 } 1246 1247 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1248 unsigned Size, unsigned AddrSpace, unsigned Align, 1249 MachineMemOperand::Flags Flags, bool *IsFast) const { 1250 if (IsFast) 1251 *IsFast = false; 1252 1253 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1254 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1255 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1256 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1257 // with adjacent offsets. 1258 bool AlignedBy4 = (Align % 4 == 0); 1259 if (IsFast) 1260 *IsFast = AlignedBy4; 1261 1262 return AlignedBy4; 1263 } 1264 1265 // FIXME: We have to be conservative here and assume that flat operations 1266 // will access scratch. If we had access to the IR function, then we 1267 // could determine if any private memory was used in the function. 1268 if (!Subtarget->hasUnalignedScratchAccess() && 1269 (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS || 1270 AddrSpace == AMDGPUAS::FLAT_ADDRESS)) { 1271 bool AlignedBy4 = Align >= 4; 1272 if (IsFast) 1273 *IsFast = AlignedBy4; 1274 1275 return AlignedBy4; 1276 } 1277 1278 if (Subtarget->hasUnalignedBufferAccess()) { 1279 // If we have an uniform constant load, it still requires using a slow 1280 // buffer instruction if unaligned. 1281 if (IsFast) { 1282 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1283 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1284 (Align % 4 == 0) : true; 1285 } 1286 1287 return true; 1288 } 1289 1290 // Smaller than dword value must be aligned. 1291 if (Size < 32) 1292 return false; 1293 1294 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1295 // byte-address are ignored, thus forcing Dword alignment. 1296 // This applies to private, global, and constant memory. 1297 if (IsFast) 1298 *IsFast = true; 1299 1300 return Size >= 32 && Align >= 4; 1301 } 1302 1303 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1304 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1305 bool *IsFast) const { 1306 if (IsFast) 1307 *IsFast = false; 1308 1309 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1310 // which isn't a simple VT. 1311 // Until MVT is extended to handle this, simply check for the size and 1312 // rely on the condition below: allow accesses if the size is a multiple of 4. 1313 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1314 VT.getStoreSize() > 16)) { 1315 return false; 1316 } 1317 1318 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1319 Align, Flags, IsFast); 1320 } 1321 1322 EVT SITargetLowering::getOptimalMemOpType( 1323 const MemOp &Op, const AttributeList &FuncAttributes) const { 1324 // FIXME: Should account for address space here. 1325 1326 // The default fallback uses the private pointer size as a guess for a type to 1327 // use. Make sure we switch these to 64-bit accesses. 1328 1329 if (Op.size() >= 16 && 1330 Op.getDstAlign() >= 4) // XXX: Should only do for global 1331 return MVT::v4i32; 1332 1333 if (Op.size() >= 8 && Op.getDstAlign() >= 4) 1334 return MVT::v2i32; 1335 1336 // Use the default. 1337 return MVT::Other; 1338 } 1339 1340 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS, 1341 unsigned DestAS) const { 1342 return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS); 1343 } 1344 1345 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1346 const MemSDNode *MemNode = cast<MemSDNode>(N); 1347 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1348 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1349 return I && I->getMetadata("amdgpu.noclobber"); 1350 } 1351 1352 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1353 unsigned DestAS) const { 1354 // Flat -> private/local is a simple truncate. 1355 // Flat -> global is no-op 1356 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1357 return true; 1358 1359 return isNoopAddrSpaceCast(SrcAS, DestAS); 1360 } 1361 1362 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1363 const MemSDNode *MemNode = cast<MemSDNode>(N); 1364 1365 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1366 } 1367 1368 TargetLoweringBase::LegalizeTypeAction 1369 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1370 int NumElts = VT.getVectorNumElements(); 1371 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1372 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1373 return TargetLoweringBase::getPreferredVectorAction(VT); 1374 } 1375 1376 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1377 Type *Ty) const { 1378 // FIXME: Could be smarter if called for vector constants. 1379 return true; 1380 } 1381 1382 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1383 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1384 switch (Op) { 1385 case ISD::LOAD: 1386 case ISD::STORE: 1387 1388 // These operations are done with 32-bit instructions anyway. 1389 case ISD::AND: 1390 case ISD::OR: 1391 case ISD::XOR: 1392 case ISD::SELECT: 1393 // TODO: Extensions? 1394 return true; 1395 default: 1396 return false; 1397 } 1398 } 1399 1400 // SimplifySetCC uses this function to determine whether or not it should 1401 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1402 if (VT == MVT::i1 && Op == ISD::SETCC) 1403 return false; 1404 1405 return TargetLowering::isTypeDesirableForOp(Op, VT); 1406 } 1407 1408 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1409 const SDLoc &SL, 1410 SDValue Chain, 1411 uint64_t Offset) const { 1412 const DataLayout &DL = DAG.getDataLayout(); 1413 MachineFunction &MF = DAG.getMachineFunction(); 1414 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1415 1416 const ArgDescriptor *InputPtrReg; 1417 const TargetRegisterClass *RC; 1418 1419 std::tie(InputPtrReg, RC) 1420 = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1421 1422 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1423 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1424 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1425 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1426 1427 return DAG.getObjectPtrOffset(SL, BasePtr, Offset); 1428 } 1429 1430 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1431 const SDLoc &SL) const { 1432 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1433 FIRST_IMPLICIT); 1434 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1435 } 1436 1437 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1438 const SDLoc &SL, SDValue Val, 1439 bool Signed, 1440 const ISD::InputArg *Arg) const { 1441 // First, if it is a widened vector, narrow it. 1442 if (VT.isVector() && 1443 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1444 EVT NarrowedVT = 1445 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1446 VT.getVectorNumElements()); 1447 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1448 DAG.getConstant(0, SL, MVT::i32)); 1449 } 1450 1451 // Then convert the vector elements or scalar value. 1452 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1453 VT.bitsLT(MemVT)) { 1454 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1455 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1456 } 1457 1458 if (MemVT.isFloatingPoint()) 1459 Val = getFPExtOrFPTrunc(DAG, Val, SL, VT); 1460 else if (Signed) 1461 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1462 else 1463 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1464 1465 return Val; 1466 } 1467 1468 SDValue SITargetLowering::lowerKernargMemParameter( 1469 SelectionDAG &DAG, EVT VT, EVT MemVT, 1470 const SDLoc &SL, SDValue Chain, 1471 uint64_t Offset, unsigned Align, bool Signed, 1472 const ISD::InputArg *Arg) const { 1473 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1474 1475 // Try to avoid using an extload by loading earlier than the argument address, 1476 // and extracting the relevant bits. The load should hopefully be merged with 1477 // the previous argument. 1478 if (MemVT.getStoreSize() < 4 && Align < 4) { 1479 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1480 int64_t AlignDownOffset = alignDown(Offset, 4); 1481 int64_t OffsetDiff = Offset - AlignDownOffset; 1482 1483 EVT IntVT = MemVT.changeTypeToInteger(); 1484 1485 // TODO: If we passed in the base kernel offset we could have a better 1486 // alignment than 4, but we don't really need it. 1487 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1488 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4, 1489 MachineMemOperand::MODereferenceable | 1490 MachineMemOperand::MOInvariant); 1491 1492 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1493 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1494 1495 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1496 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1497 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1498 1499 1500 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1501 } 1502 1503 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1504 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align, 1505 MachineMemOperand::MODereferenceable | 1506 MachineMemOperand::MOInvariant); 1507 1508 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1509 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1510 } 1511 1512 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1513 const SDLoc &SL, SDValue Chain, 1514 const ISD::InputArg &Arg) const { 1515 MachineFunction &MF = DAG.getMachineFunction(); 1516 MachineFrameInfo &MFI = MF.getFrameInfo(); 1517 1518 if (Arg.Flags.isByVal()) { 1519 unsigned Size = Arg.Flags.getByValSize(); 1520 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1521 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1522 } 1523 1524 unsigned ArgOffset = VA.getLocMemOffset(); 1525 unsigned ArgSize = VA.getValVT().getStoreSize(); 1526 1527 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1528 1529 // Create load nodes to retrieve arguments from the stack. 1530 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1531 SDValue ArgValue; 1532 1533 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1534 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1535 MVT MemVT = VA.getValVT(); 1536 1537 switch (VA.getLocInfo()) { 1538 default: 1539 break; 1540 case CCValAssign::BCvt: 1541 MemVT = VA.getLocVT(); 1542 break; 1543 case CCValAssign::SExt: 1544 ExtType = ISD::SEXTLOAD; 1545 break; 1546 case CCValAssign::ZExt: 1547 ExtType = ISD::ZEXTLOAD; 1548 break; 1549 case CCValAssign::AExt: 1550 ExtType = ISD::EXTLOAD; 1551 break; 1552 } 1553 1554 ArgValue = DAG.getExtLoad( 1555 ExtType, SL, VA.getLocVT(), Chain, FIN, 1556 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1557 MemVT); 1558 return ArgValue; 1559 } 1560 1561 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1562 const SIMachineFunctionInfo &MFI, 1563 EVT VT, 1564 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1565 const ArgDescriptor *Reg; 1566 const TargetRegisterClass *RC; 1567 1568 std::tie(Reg, RC) = MFI.getPreloadedValue(PVID); 1569 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1570 } 1571 1572 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1573 CallingConv::ID CallConv, 1574 ArrayRef<ISD::InputArg> Ins, 1575 BitVector &Skipped, 1576 FunctionType *FType, 1577 SIMachineFunctionInfo *Info) { 1578 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1579 const ISD::InputArg *Arg = &Ins[I]; 1580 1581 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1582 "vector type argument should have been split"); 1583 1584 // First check if it's a PS input addr. 1585 if (CallConv == CallingConv::AMDGPU_PS && 1586 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1587 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1588 1589 // Inconveniently only the first part of the split is marked as isSplit, 1590 // so skip to the end. We only want to increment PSInputNum once for the 1591 // entire split argument. 1592 if (Arg->Flags.isSplit()) { 1593 while (!Arg->Flags.isSplitEnd()) { 1594 assert((!Arg->VT.isVector() || 1595 Arg->VT.getScalarSizeInBits() == 16) && 1596 "unexpected vector split in ps argument type"); 1597 if (!SkipArg) 1598 Splits.push_back(*Arg); 1599 Arg = &Ins[++I]; 1600 } 1601 } 1602 1603 if (SkipArg) { 1604 // We can safely skip PS inputs. 1605 Skipped.set(Arg->getOrigArgIndex()); 1606 ++PSInputNum; 1607 continue; 1608 } 1609 1610 Info->markPSInputAllocated(PSInputNum); 1611 if (Arg->Used) 1612 Info->markPSInputEnabled(PSInputNum); 1613 1614 ++PSInputNum; 1615 } 1616 1617 Splits.push_back(*Arg); 1618 } 1619 } 1620 1621 // Allocate special inputs passed in VGPRs. 1622 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1623 MachineFunction &MF, 1624 const SIRegisterInfo &TRI, 1625 SIMachineFunctionInfo &Info) const { 1626 const LLT S32 = LLT::scalar(32); 1627 MachineRegisterInfo &MRI = MF.getRegInfo(); 1628 1629 if (Info.hasWorkItemIDX()) { 1630 Register Reg = AMDGPU::VGPR0; 1631 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1632 1633 CCInfo.AllocateReg(Reg); 1634 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg)); 1635 } 1636 1637 if (Info.hasWorkItemIDY()) { 1638 Register Reg = AMDGPU::VGPR1; 1639 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1640 1641 CCInfo.AllocateReg(Reg); 1642 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1643 } 1644 1645 if (Info.hasWorkItemIDZ()) { 1646 Register Reg = AMDGPU::VGPR2; 1647 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1648 1649 CCInfo.AllocateReg(Reg); 1650 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1651 } 1652 } 1653 1654 // Try to allocate a VGPR at the end of the argument list, or if no argument 1655 // VGPRs are left allocating a stack slot. 1656 // If \p Mask is is given it indicates bitfield position in the register. 1657 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1658 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1659 ArgDescriptor Arg = ArgDescriptor()) { 1660 if (Arg.isSet()) 1661 return ArgDescriptor::createArg(Arg, Mask); 1662 1663 ArrayRef<MCPhysReg> ArgVGPRs 1664 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1665 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1666 if (RegIdx == ArgVGPRs.size()) { 1667 // Spill to stack required. 1668 int64_t Offset = CCInfo.AllocateStack(4, 4); 1669 1670 return ArgDescriptor::createStack(Offset, Mask); 1671 } 1672 1673 unsigned Reg = ArgVGPRs[RegIdx]; 1674 Reg = CCInfo.AllocateReg(Reg); 1675 assert(Reg != AMDGPU::NoRegister); 1676 1677 MachineFunction &MF = CCInfo.getMachineFunction(); 1678 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1679 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1680 return ArgDescriptor::createRegister(Reg, Mask); 1681 } 1682 1683 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1684 const TargetRegisterClass *RC, 1685 unsigned NumArgRegs) { 1686 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1687 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1688 if (RegIdx == ArgSGPRs.size()) 1689 report_fatal_error("ran out of SGPRs for arguments"); 1690 1691 unsigned Reg = ArgSGPRs[RegIdx]; 1692 Reg = CCInfo.AllocateReg(Reg); 1693 assert(Reg != AMDGPU::NoRegister); 1694 1695 MachineFunction &MF = CCInfo.getMachineFunction(); 1696 MF.addLiveIn(Reg, RC); 1697 return ArgDescriptor::createRegister(Reg); 1698 } 1699 1700 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) { 1701 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1702 } 1703 1704 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) { 1705 return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1706 } 1707 1708 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo, 1709 MachineFunction &MF, 1710 const SIRegisterInfo &TRI, 1711 SIMachineFunctionInfo &Info) const { 1712 const unsigned Mask = 0x3ff; 1713 ArgDescriptor Arg; 1714 1715 if (Info.hasWorkItemIDX()) { 1716 Arg = allocateVGPR32Input(CCInfo, Mask); 1717 Info.setWorkItemIDX(Arg); 1718 } 1719 1720 if (Info.hasWorkItemIDY()) { 1721 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1722 Info.setWorkItemIDY(Arg); 1723 } 1724 1725 if (Info.hasWorkItemIDZ()) 1726 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1727 } 1728 1729 void SITargetLowering::allocateSpecialInputSGPRs( 1730 CCState &CCInfo, 1731 MachineFunction &MF, 1732 const SIRegisterInfo &TRI, 1733 SIMachineFunctionInfo &Info) const { 1734 auto &ArgInfo = Info.getArgInfo(); 1735 1736 // TODO: Unify handling with private memory pointers. 1737 1738 if (Info.hasDispatchPtr()) 1739 ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo); 1740 1741 if (Info.hasQueuePtr()) 1742 ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo); 1743 1744 if (Info.hasKernargSegmentPtr()) 1745 ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo); 1746 1747 if (Info.hasDispatchID()) 1748 ArgInfo.DispatchID = allocateSGPR64Input(CCInfo); 1749 1750 // flat_scratch_init is not applicable for non-kernel functions. 1751 1752 if (Info.hasWorkGroupIDX()) 1753 ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo); 1754 1755 if (Info.hasWorkGroupIDY()) 1756 ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo); 1757 1758 if (Info.hasWorkGroupIDZ()) 1759 ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo); 1760 1761 if (Info.hasImplicitArgPtr()) 1762 ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo); 1763 } 1764 1765 // Allocate special inputs passed in user SGPRs. 1766 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 1767 MachineFunction &MF, 1768 const SIRegisterInfo &TRI, 1769 SIMachineFunctionInfo &Info) const { 1770 if (Info.hasImplicitBufferPtr()) { 1771 unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 1772 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 1773 CCInfo.AllocateReg(ImplicitBufferPtrReg); 1774 } 1775 1776 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 1777 if (Info.hasPrivateSegmentBuffer()) { 1778 unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 1779 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 1780 CCInfo.AllocateReg(PrivateSegmentBufferReg); 1781 } 1782 1783 if (Info.hasDispatchPtr()) { 1784 unsigned DispatchPtrReg = Info.addDispatchPtr(TRI); 1785 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 1786 CCInfo.AllocateReg(DispatchPtrReg); 1787 } 1788 1789 if (Info.hasQueuePtr()) { 1790 unsigned QueuePtrReg = Info.addQueuePtr(TRI); 1791 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 1792 CCInfo.AllocateReg(QueuePtrReg); 1793 } 1794 1795 if (Info.hasKernargSegmentPtr()) { 1796 MachineRegisterInfo &MRI = MF.getRegInfo(); 1797 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 1798 CCInfo.AllocateReg(InputPtrReg); 1799 1800 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 1801 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 1802 } 1803 1804 if (Info.hasDispatchID()) { 1805 unsigned DispatchIDReg = Info.addDispatchID(TRI); 1806 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 1807 CCInfo.AllocateReg(DispatchIDReg); 1808 } 1809 1810 if (Info.hasFlatScratchInit()) { 1811 unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI); 1812 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 1813 CCInfo.AllocateReg(FlatScratchInitReg); 1814 } 1815 1816 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 1817 // these from the dispatch pointer. 1818 } 1819 1820 // Allocate special input registers that are initialized per-wave. 1821 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 1822 MachineFunction &MF, 1823 SIMachineFunctionInfo &Info, 1824 CallingConv::ID CallConv, 1825 bool IsShader) const { 1826 if (Info.hasWorkGroupIDX()) { 1827 unsigned Reg = Info.addWorkGroupIDX(); 1828 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1829 CCInfo.AllocateReg(Reg); 1830 } 1831 1832 if (Info.hasWorkGroupIDY()) { 1833 unsigned Reg = Info.addWorkGroupIDY(); 1834 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1835 CCInfo.AllocateReg(Reg); 1836 } 1837 1838 if (Info.hasWorkGroupIDZ()) { 1839 unsigned Reg = Info.addWorkGroupIDZ(); 1840 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1841 CCInfo.AllocateReg(Reg); 1842 } 1843 1844 if (Info.hasWorkGroupInfo()) { 1845 unsigned Reg = Info.addWorkGroupInfo(); 1846 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 1847 CCInfo.AllocateReg(Reg); 1848 } 1849 1850 if (Info.hasPrivateSegmentWaveByteOffset()) { 1851 // Scratch wave offset passed in system SGPR. 1852 unsigned PrivateSegmentWaveByteOffsetReg; 1853 1854 if (IsShader) { 1855 PrivateSegmentWaveByteOffsetReg = 1856 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 1857 1858 // This is true if the scratch wave byte offset doesn't have a fixed 1859 // location. 1860 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 1861 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 1862 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 1863 } 1864 } else 1865 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 1866 1867 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 1868 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 1869 } 1870 } 1871 1872 static void reservePrivateMemoryRegs(const TargetMachine &TM, 1873 MachineFunction &MF, 1874 const SIRegisterInfo &TRI, 1875 SIMachineFunctionInfo &Info) { 1876 // Now that we've figured out where the scratch register inputs are, see if 1877 // should reserve the arguments and use them directly. 1878 MachineFrameInfo &MFI = MF.getFrameInfo(); 1879 bool HasStackObjects = MFI.hasStackObjects(); 1880 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 1881 1882 // Record that we know we have non-spill stack objects so we don't need to 1883 // check all stack objects later. 1884 if (HasStackObjects) 1885 Info.setHasNonSpillStackObjects(true); 1886 1887 // Everything live out of a block is spilled with fast regalloc, so it's 1888 // almost certain that spilling will be required. 1889 if (TM.getOptLevel() == CodeGenOpt::None) 1890 HasStackObjects = true; 1891 1892 // For now assume stack access is needed in any callee functions, so we need 1893 // the scratch registers to pass in. 1894 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 1895 1896 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 1897 // If we have stack objects, we unquestionably need the private buffer 1898 // resource. For the Code Object V2 ABI, this will be the first 4 user 1899 // SGPR inputs. We can reserve those and use them directly. 1900 1901 Register PrivateSegmentBufferReg = 1902 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 1903 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 1904 } else { 1905 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 1906 // We tentatively reserve the last registers (skipping the last registers 1907 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 1908 // we'll replace these with the ones immediately after those which were 1909 // really allocated. In the prologue copies will be inserted from the 1910 // argument to these reserved registers. 1911 1912 // Without HSA, relocations are used for the scratch pointer and the 1913 // buffer resource setup is always inserted in the prologue. Scratch wave 1914 // offset is still in an input SGPR. 1915 Info.setScratchRSrcReg(ReservedBufferReg); 1916 } 1917 1918 // hasFP should be accurate for kernels even before the frame is finalized. 1919 if (ST.getFrameLowering()->hasFP(MF)) { 1920 MachineRegisterInfo &MRI = MF.getRegInfo(); 1921 1922 // Try to use s32 as the SP, but move it if it would interfere with input 1923 // arguments. This won't work with calls though. 1924 // 1925 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 1926 // registers. 1927 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 1928 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 1929 } else { 1930 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 1931 1932 if (MFI.hasCalls()) 1933 report_fatal_error("call in graphics shader with too many input SGPRs"); 1934 1935 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 1936 if (!MRI.isLiveIn(Reg)) { 1937 Info.setStackPtrOffsetReg(Reg); 1938 break; 1939 } 1940 } 1941 1942 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 1943 report_fatal_error("failed to find register for SP"); 1944 } 1945 1946 if (MFI.hasCalls()) { 1947 Info.setScratchWaveOffsetReg(AMDGPU::SGPR33); 1948 Info.setFrameOffsetReg(AMDGPU::SGPR33); 1949 } else { 1950 unsigned ReservedOffsetReg = 1951 TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1952 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1953 Info.setFrameOffsetReg(ReservedOffsetReg); 1954 } 1955 } else if (RequiresStackAccess) { 1956 assert(!MFI.hasCalls()); 1957 // We know there are accesses and they will be done relative to SP, so just 1958 // pin it to the input. 1959 // 1960 // FIXME: Should not do this if inline asm is reading/writing these 1961 // registers. 1962 Register PreloadedSP = Info.getPreloadedReg( 1963 AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET); 1964 1965 Info.setStackPtrOffsetReg(PreloadedSP); 1966 Info.setScratchWaveOffsetReg(PreloadedSP); 1967 Info.setFrameOffsetReg(PreloadedSP); 1968 } else { 1969 assert(!MFI.hasCalls()); 1970 1971 // There may not be stack access at all. There may still be spills, or 1972 // access of a constant pointer (in which cases an extra copy will be 1973 // emitted in the prolog). 1974 unsigned ReservedOffsetReg 1975 = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF); 1976 Info.setStackPtrOffsetReg(ReservedOffsetReg); 1977 Info.setScratchWaveOffsetReg(ReservedOffsetReg); 1978 Info.setFrameOffsetReg(ReservedOffsetReg); 1979 } 1980 } 1981 1982 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 1983 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 1984 return !Info->isEntryFunction(); 1985 } 1986 1987 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 1988 1989 } 1990 1991 void SITargetLowering::insertCopiesSplitCSR( 1992 MachineBasicBlock *Entry, 1993 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 1994 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 1995 1996 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 1997 if (!IStart) 1998 return; 1999 2000 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2001 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2002 MachineBasicBlock::iterator MBBI = Entry->begin(); 2003 for (const MCPhysReg *I = IStart; *I; ++I) { 2004 const TargetRegisterClass *RC = nullptr; 2005 if (AMDGPU::SReg_64RegClass.contains(*I)) 2006 RC = &AMDGPU::SGPR_64RegClass; 2007 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2008 RC = &AMDGPU::SGPR_32RegClass; 2009 else 2010 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2011 2012 Register NewVR = MRI->createVirtualRegister(RC); 2013 // Create copy from CSR to a virtual register. 2014 Entry->addLiveIn(*I); 2015 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2016 .addReg(*I); 2017 2018 // Insert the copy-back instructions right before the terminator. 2019 for (auto *Exit : Exits) 2020 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2021 TII->get(TargetOpcode::COPY), *I) 2022 .addReg(NewVR); 2023 } 2024 } 2025 2026 SDValue SITargetLowering::LowerFormalArguments( 2027 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2028 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2029 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2030 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2031 2032 MachineFunction &MF = DAG.getMachineFunction(); 2033 const Function &Fn = MF.getFunction(); 2034 FunctionType *FType = MF.getFunction().getFunctionType(); 2035 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2036 2037 if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) { 2038 DiagnosticInfoUnsupported NoGraphicsHSA( 2039 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2040 DAG.getContext()->diagnose(NoGraphicsHSA); 2041 return DAG.getEntryNode(); 2042 } 2043 2044 SmallVector<ISD::InputArg, 16> Splits; 2045 SmallVector<CCValAssign, 16> ArgLocs; 2046 BitVector Skipped(Ins.size()); 2047 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2048 *DAG.getContext()); 2049 2050 bool IsShader = AMDGPU::isShader(CallConv); 2051 bool IsKernel = AMDGPU::isKernel(CallConv); 2052 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2053 2054 if (IsShader) { 2055 processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2056 2057 // At least one interpolation mode must be enabled or else the GPU will 2058 // hang. 2059 // 2060 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2061 // set PSInputAddr, the user wants to enable some bits after the compilation 2062 // based on run-time states. Since we can't know what the final PSInputEna 2063 // will look like, so we shouldn't do anything here and the user should take 2064 // responsibility for the correct programming. 2065 // 2066 // Otherwise, the following restrictions apply: 2067 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2068 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2069 // enabled too. 2070 if (CallConv == CallingConv::AMDGPU_PS) { 2071 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2072 ((Info->getPSInputAddr() & 0xF) == 0 && 2073 Info->isPSInputAllocated(11))) { 2074 CCInfo.AllocateReg(AMDGPU::VGPR0); 2075 CCInfo.AllocateReg(AMDGPU::VGPR1); 2076 Info->markPSInputAllocated(0); 2077 Info->markPSInputEnabled(0); 2078 } 2079 if (Subtarget->isAmdPalOS()) { 2080 // For isAmdPalOS, the user does not enable some bits after compilation 2081 // based on run-time states; the register values being generated here are 2082 // the final ones set in hardware. Therefore we need to apply the 2083 // workaround to PSInputAddr and PSInputEnable together. (The case where 2084 // a bit is set in PSInputAddr but not PSInputEnable is where the 2085 // frontend set up an input arg for a particular interpolation mode, but 2086 // nothing uses that input arg. Really we should have an earlier pass 2087 // that removes such an arg.) 2088 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2089 if ((PsInputBits & 0x7F) == 0 || 2090 ((PsInputBits & 0xF) == 0 && 2091 (PsInputBits >> 11 & 1))) 2092 Info->markPSInputEnabled( 2093 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2094 } 2095 } 2096 2097 assert(!Info->hasDispatchPtr() && 2098 !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() && 2099 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2100 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2101 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2102 !Info->hasWorkItemIDZ()); 2103 } else if (IsKernel) { 2104 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2105 } else { 2106 Splits.append(Ins.begin(), Ins.end()); 2107 } 2108 2109 if (IsEntryFunc) { 2110 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2111 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2112 } 2113 2114 if (IsKernel) { 2115 analyzeFormalArgumentsCompute(CCInfo, Ins); 2116 } else { 2117 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2118 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2119 } 2120 2121 SmallVector<SDValue, 16> Chains; 2122 2123 // FIXME: This is the minimum kernel argument alignment. We should improve 2124 // this to the maximum alignment of the arguments. 2125 // 2126 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2127 // kern arg offset. 2128 const unsigned KernelArgBaseAlign = 16; 2129 2130 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2131 const ISD::InputArg &Arg = Ins[i]; 2132 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2133 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2134 continue; 2135 } 2136 2137 CCValAssign &VA = ArgLocs[ArgIdx++]; 2138 MVT VT = VA.getLocVT(); 2139 2140 if (IsEntryFunc && VA.isMemLoc()) { 2141 VT = Ins[i].VT; 2142 EVT MemVT = VA.getLocVT(); 2143 2144 const uint64_t Offset = VA.getLocMemOffset(); 2145 unsigned Align = MinAlign(KernelArgBaseAlign, Offset); 2146 2147 SDValue Arg = lowerKernargMemParameter( 2148 DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]); 2149 Chains.push_back(Arg.getValue(1)); 2150 2151 auto *ParamTy = 2152 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2153 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2154 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2155 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2156 // On SI local pointers are just offsets into LDS, so they are always 2157 // less than 16-bits. On CI and newer they could potentially be 2158 // real pointers, so we can't guarantee their size. 2159 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2160 DAG.getValueType(MVT::i16)); 2161 } 2162 2163 InVals.push_back(Arg); 2164 continue; 2165 } else if (!IsEntryFunc && VA.isMemLoc()) { 2166 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2167 InVals.push_back(Val); 2168 if (!Arg.Flags.isByVal()) 2169 Chains.push_back(Val.getValue(1)); 2170 continue; 2171 } 2172 2173 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2174 2175 Register Reg = VA.getLocReg(); 2176 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2177 EVT ValVT = VA.getValVT(); 2178 2179 Reg = MF.addLiveIn(Reg, RC); 2180 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2181 2182 if (Arg.Flags.isSRet()) { 2183 // The return object should be reasonably addressable. 2184 2185 // FIXME: This helps when the return is a real sret. If it is a 2186 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2187 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2188 unsigned NumBits 2189 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2190 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2191 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2192 } 2193 2194 // If this is an 8 or 16-bit value, it is really passed promoted 2195 // to 32 bits. Insert an assert[sz]ext to capture this, then 2196 // truncate to the right size. 2197 switch (VA.getLocInfo()) { 2198 case CCValAssign::Full: 2199 break; 2200 case CCValAssign::BCvt: 2201 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2202 break; 2203 case CCValAssign::SExt: 2204 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2205 DAG.getValueType(ValVT)); 2206 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2207 break; 2208 case CCValAssign::ZExt: 2209 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2210 DAG.getValueType(ValVT)); 2211 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2212 break; 2213 case CCValAssign::AExt: 2214 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2215 break; 2216 default: 2217 llvm_unreachable("Unknown loc info!"); 2218 } 2219 2220 InVals.push_back(Val); 2221 } 2222 2223 if (!IsEntryFunc) { 2224 // Special inputs come after user arguments. 2225 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2226 } 2227 2228 // Start adding system SGPRs. 2229 if (IsEntryFunc) { 2230 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader); 2231 } else { 2232 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2233 CCInfo.AllocateReg(Info->getScratchWaveOffsetReg()); 2234 CCInfo.AllocateReg(Info->getFrameOffsetReg()); 2235 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2236 } 2237 2238 auto &ArgUsageInfo = 2239 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2240 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2241 2242 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2243 Info->setBytesInStackArgArea(StackArgSize); 2244 2245 return Chains.empty() ? Chain : 2246 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2247 } 2248 2249 // TODO: If return values can't fit in registers, we should return as many as 2250 // possible in registers before passing on stack. 2251 bool SITargetLowering::CanLowerReturn( 2252 CallingConv::ID CallConv, 2253 MachineFunction &MF, bool IsVarArg, 2254 const SmallVectorImpl<ISD::OutputArg> &Outs, 2255 LLVMContext &Context) const { 2256 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2257 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2258 // for shaders. Vector types should be explicitly handled by CC. 2259 if (AMDGPU::isEntryFunctionCC(CallConv)) 2260 return true; 2261 2262 SmallVector<CCValAssign, 16> RVLocs; 2263 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2264 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2265 } 2266 2267 SDValue 2268 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2269 bool isVarArg, 2270 const SmallVectorImpl<ISD::OutputArg> &Outs, 2271 const SmallVectorImpl<SDValue> &OutVals, 2272 const SDLoc &DL, SelectionDAG &DAG) const { 2273 MachineFunction &MF = DAG.getMachineFunction(); 2274 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2275 2276 if (AMDGPU::isKernel(CallConv)) { 2277 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2278 OutVals, DL, DAG); 2279 } 2280 2281 bool IsShader = AMDGPU::isShader(CallConv); 2282 2283 Info->setIfReturnsVoid(Outs.empty()); 2284 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2285 2286 // CCValAssign - represent the assignment of the return value to a location. 2287 SmallVector<CCValAssign, 48> RVLocs; 2288 SmallVector<ISD::OutputArg, 48> Splits; 2289 2290 // CCState - Info about the registers and stack slots. 2291 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2292 *DAG.getContext()); 2293 2294 // Analyze outgoing return values. 2295 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2296 2297 SDValue Flag; 2298 SmallVector<SDValue, 48> RetOps; 2299 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2300 2301 // Add return address for callable functions. 2302 if (!Info->isEntryFunction()) { 2303 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2304 SDValue ReturnAddrReg = CreateLiveInRegister( 2305 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2306 2307 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2308 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2309 MVT::i64); 2310 Chain = 2311 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2312 Flag = Chain.getValue(1); 2313 RetOps.push_back(ReturnAddrVirtualReg); 2314 } 2315 2316 // Copy the result values into the output registers. 2317 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2318 ++I, ++RealRVLocIdx) { 2319 CCValAssign &VA = RVLocs[I]; 2320 assert(VA.isRegLoc() && "Can only return in registers!"); 2321 // TODO: Partially return in registers if return values don't fit. 2322 SDValue Arg = OutVals[RealRVLocIdx]; 2323 2324 // Copied from other backends. 2325 switch (VA.getLocInfo()) { 2326 case CCValAssign::Full: 2327 break; 2328 case CCValAssign::BCvt: 2329 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2330 break; 2331 case CCValAssign::SExt: 2332 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2333 break; 2334 case CCValAssign::ZExt: 2335 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2336 break; 2337 case CCValAssign::AExt: 2338 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2339 break; 2340 default: 2341 llvm_unreachable("Unknown loc info!"); 2342 } 2343 2344 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2345 Flag = Chain.getValue(1); 2346 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2347 } 2348 2349 // FIXME: Does sret work properly? 2350 if (!Info->isEntryFunction()) { 2351 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2352 const MCPhysReg *I = 2353 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2354 if (I) { 2355 for (; *I; ++I) { 2356 if (AMDGPU::SReg_64RegClass.contains(*I)) 2357 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2358 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2359 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2360 else 2361 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2362 } 2363 } 2364 } 2365 2366 // Update chain and glue. 2367 RetOps[0] = Chain; 2368 if (Flag.getNode()) 2369 RetOps.push_back(Flag); 2370 2371 unsigned Opc = AMDGPUISD::ENDPGM; 2372 if (!IsWaveEnd) 2373 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2374 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2375 } 2376 2377 SDValue SITargetLowering::LowerCallResult( 2378 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2379 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2380 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2381 SDValue ThisVal) const { 2382 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2383 2384 // Assign locations to each value returned by this call. 2385 SmallVector<CCValAssign, 16> RVLocs; 2386 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2387 *DAG.getContext()); 2388 CCInfo.AnalyzeCallResult(Ins, RetCC); 2389 2390 // Copy all of the result registers out of their specified physreg. 2391 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2392 CCValAssign VA = RVLocs[i]; 2393 SDValue Val; 2394 2395 if (VA.isRegLoc()) { 2396 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2397 Chain = Val.getValue(1); 2398 InFlag = Val.getValue(2); 2399 } else if (VA.isMemLoc()) { 2400 report_fatal_error("TODO: return values in memory"); 2401 } else 2402 llvm_unreachable("unknown argument location type"); 2403 2404 switch (VA.getLocInfo()) { 2405 case CCValAssign::Full: 2406 break; 2407 case CCValAssign::BCvt: 2408 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2409 break; 2410 case CCValAssign::ZExt: 2411 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2412 DAG.getValueType(VA.getValVT())); 2413 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2414 break; 2415 case CCValAssign::SExt: 2416 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2417 DAG.getValueType(VA.getValVT())); 2418 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2419 break; 2420 case CCValAssign::AExt: 2421 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2422 break; 2423 default: 2424 llvm_unreachable("Unknown loc info!"); 2425 } 2426 2427 InVals.push_back(Val); 2428 } 2429 2430 return Chain; 2431 } 2432 2433 // Add code to pass special inputs required depending on used features separate 2434 // from the explicit user arguments present in the IR. 2435 void SITargetLowering::passSpecialInputs( 2436 CallLoweringInfo &CLI, 2437 CCState &CCInfo, 2438 const SIMachineFunctionInfo &Info, 2439 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2440 SmallVectorImpl<SDValue> &MemOpChains, 2441 SDValue Chain) const { 2442 // If we don't have a call site, this was a call inserted by 2443 // legalization. These can never use special inputs. 2444 if (!CLI.CS) 2445 return; 2446 2447 const Function *CalleeFunc = CLI.CS.getCalledFunction(); 2448 assert(CalleeFunc); 2449 2450 SelectionDAG &DAG = CLI.DAG; 2451 const SDLoc &DL = CLI.DL; 2452 2453 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2454 2455 auto &ArgUsageInfo = 2456 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2457 const AMDGPUFunctionArgInfo &CalleeArgInfo 2458 = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2459 2460 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2461 2462 // TODO: Unify with private memory register handling. This is complicated by 2463 // the fact that at least in kernels, the input argument is not necessarily 2464 // in the same location as the input. 2465 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2466 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2467 AMDGPUFunctionArgInfo::QUEUE_PTR, 2468 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR, 2469 AMDGPUFunctionArgInfo::DISPATCH_ID, 2470 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2471 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2472 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z, 2473 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR 2474 }; 2475 2476 for (auto InputID : InputRegs) { 2477 const ArgDescriptor *OutgoingArg; 2478 const TargetRegisterClass *ArgRC; 2479 2480 std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID); 2481 if (!OutgoingArg) 2482 continue; 2483 2484 const ArgDescriptor *IncomingArg; 2485 const TargetRegisterClass *IncomingArgRC; 2486 std::tie(IncomingArg, IncomingArgRC) 2487 = CallerArgInfo.getPreloadedValue(InputID); 2488 assert(IncomingArgRC == ArgRC); 2489 2490 // All special arguments are ints for now. 2491 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2492 SDValue InputReg; 2493 2494 if (IncomingArg) { 2495 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2496 } else { 2497 // The implicit arg ptr is special because it doesn't have a corresponding 2498 // input for kernels, and is computed from the kernarg segment pointer. 2499 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2500 InputReg = getImplicitArgPtr(DAG, DL); 2501 } 2502 2503 if (OutgoingArg->isRegister()) { 2504 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2505 } else { 2506 unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4); 2507 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2508 SpecialArgOffset); 2509 MemOpChains.push_back(ArgStore); 2510 } 2511 } 2512 2513 // Pack workitem IDs into a single register or pass it as is if already 2514 // packed. 2515 const ArgDescriptor *OutgoingArg; 2516 const TargetRegisterClass *ArgRC; 2517 2518 std::tie(OutgoingArg, ArgRC) = 2519 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2520 if (!OutgoingArg) 2521 std::tie(OutgoingArg, ArgRC) = 2522 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2523 if (!OutgoingArg) 2524 std::tie(OutgoingArg, ArgRC) = 2525 CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2526 if (!OutgoingArg) 2527 return; 2528 2529 const ArgDescriptor *IncomingArgX 2530 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first; 2531 const ArgDescriptor *IncomingArgY 2532 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first; 2533 const ArgDescriptor *IncomingArgZ 2534 = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first; 2535 2536 SDValue InputReg; 2537 SDLoc SL; 2538 2539 // If incoming ids are not packed we need to pack them. 2540 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX) 2541 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2542 2543 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) { 2544 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2545 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2546 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2547 InputReg = InputReg.getNode() ? 2548 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2549 } 2550 2551 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) { 2552 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2553 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2554 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2555 InputReg = InputReg.getNode() ? 2556 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2557 } 2558 2559 if (!InputReg.getNode()) { 2560 // Workitem ids are already packed, any of present incoming arguments 2561 // will carry all required fields. 2562 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2563 IncomingArgX ? *IncomingArgX : 2564 IncomingArgY ? *IncomingArgY : 2565 *IncomingArgZ, ~0u); 2566 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2567 } 2568 2569 if (OutgoingArg->isRegister()) { 2570 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2571 } else { 2572 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4); 2573 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2574 SpecialArgOffset); 2575 MemOpChains.push_back(ArgStore); 2576 } 2577 } 2578 2579 static bool canGuaranteeTCO(CallingConv::ID CC) { 2580 return CC == CallingConv::Fast; 2581 } 2582 2583 /// Return true if we might ever do TCO for calls with this calling convention. 2584 static bool mayTailCallThisCC(CallingConv::ID CC) { 2585 switch (CC) { 2586 case CallingConv::C: 2587 return true; 2588 default: 2589 return canGuaranteeTCO(CC); 2590 } 2591 } 2592 2593 bool SITargetLowering::isEligibleForTailCallOptimization( 2594 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2595 const SmallVectorImpl<ISD::OutputArg> &Outs, 2596 const SmallVectorImpl<SDValue> &OutVals, 2597 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2598 if (!mayTailCallThisCC(CalleeCC)) 2599 return false; 2600 2601 MachineFunction &MF = DAG.getMachineFunction(); 2602 const Function &CallerF = MF.getFunction(); 2603 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2604 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2605 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2606 2607 // Kernels aren't callable, and don't have a live in return address so it 2608 // doesn't make sense to do a tail call with entry functions. 2609 if (!CallerPreserved) 2610 return false; 2611 2612 bool CCMatch = CallerCC == CalleeCC; 2613 2614 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2615 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2616 return true; 2617 return false; 2618 } 2619 2620 // TODO: Can we handle var args? 2621 if (IsVarArg) 2622 return false; 2623 2624 for (const Argument &Arg : CallerF.args()) { 2625 if (Arg.hasByValAttr()) 2626 return false; 2627 } 2628 2629 LLVMContext &Ctx = *DAG.getContext(); 2630 2631 // Check that the call results are passed in the same way. 2632 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2633 CCAssignFnForCall(CalleeCC, IsVarArg), 2634 CCAssignFnForCall(CallerCC, IsVarArg))) 2635 return false; 2636 2637 // The callee has to preserve all registers the caller needs to preserve. 2638 if (!CCMatch) { 2639 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2640 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2641 return false; 2642 } 2643 2644 // Nothing more to check if the callee is taking no arguments. 2645 if (Outs.empty()) 2646 return true; 2647 2648 SmallVector<CCValAssign, 16> ArgLocs; 2649 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2650 2651 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2652 2653 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2654 // If the stack arguments for this call do not fit into our own save area then 2655 // the call cannot be made tail. 2656 // TODO: Is this really necessary? 2657 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2658 return false; 2659 2660 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2661 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2662 } 2663 2664 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2665 if (!CI->isTailCall()) 2666 return false; 2667 2668 const Function *ParentFn = CI->getParent()->getParent(); 2669 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2670 return false; 2671 return true; 2672 } 2673 2674 // The wave scratch offset register is used as the global base pointer. 2675 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2676 SmallVectorImpl<SDValue> &InVals) const { 2677 SelectionDAG &DAG = CLI.DAG; 2678 const SDLoc &DL = CLI.DL; 2679 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2680 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2681 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2682 SDValue Chain = CLI.Chain; 2683 SDValue Callee = CLI.Callee; 2684 bool &IsTailCall = CLI.IsTailCall; 2685 CallingConv::ID CallConv = CLI.CallConv; 2686 bool IsVarArg = CLI.IsVarArg; 2687 bool IsSibCall = false; 2688 bool IsThisReturn = false; 2689 MachineFunction &MF = DAG.getMachineFunction(); 2690 2691 if (Callee.isUndef() || isNullConstant(Callee)) { 2692 if (!CLI.IsTailCall) { 2693 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2694 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2695 } 2696 2697 return Chain; 2698 } 2699 2700 if (IsVarArg) { 2701 return lowerUnhandledCall(CLI, InVals, 2702 "unsupported call to variadic function "); 2703 } 2704 2705 if (!CLI.CS.getInstruction()) 2706 report_fatal_error("unsupported libcall legalization"); 2707 2708 if (!CLI.CS.getCalledFunction()) { 2709 return lowerUnhandledCall(CLI, InVals, 2710 "unsupported indirect call to function "); 2711 } 2712 2713 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2714 return lowerUnhandledCall(CLI, InVals, 2715 "unsupported required tail call to function "); 2716 } 2717 2718 if (AMDGPU::isShader(MF.getFunction().getCallingConv())) { 2719 // Note the issue is with the CC of the calling function, not of the call 2720 // itself. 2721 return lowerUnhandledCall(CLI, InVals, 2722 "unsupported call from graphics shader of function "); 2723 } 2724 2725 if (IsTailCall) { 2726 IsTailCall = isEligibleForTailCallOptimization( 2727 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2728 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) { 2729 report_fatal_error("failed to perform tail call elimination on a call " 2730 "site marked musttail"); 2731 } 2732 2733 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2734 2735 // A sibling call is one where we're under the usual C ABI and not planning 2736 // to change that but can still do a tail call: 2737 if (!TailCallOpt && IsTailCall) 2738 IsSibCall = true; 2739 2740 if (IsTailCall) 2741 ++NumTailCalls; 2742 } 2743 2744 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2745 2746 // Analyze operands of the call, assigning locations to each operand. 2747 SmallVector<CCValAssign, 16> ArgLocs; 2748 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 2749 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 2750 2751 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 2752 2753 // Get a count of how many bytes are to be pushed on the stack. 2754 unsigned NumBytes = CCInfo.getNextStackOffset(); 2755 2756 if (IsSibCall) { 2757 // Since we're not changing the ABI to make this a tail call, the memory 2758 // operands are already available in the caller's incoming argument space. 2759 NumBytes = 0; 2760 } 2761 2762 // FPDiff is the byte offset of the call's argument area from the callee's. 2763 // Stores to callee stack arguments will be placed in FixedStackSlots offset 2764 // by this amount for a tail call. In a sibling call it must be 0 because the 2765 // caller will deallocate the entire stack and the callee still expects its 2766 // arguments to begin at SP+0. Completely unused for non-tail calls. 2767 int32_t FPDiff = 0; 2768 MachineFrameInfo &MFI = MF.getFrameInfo(); 2769 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 2770 2771 // Adjust the stack pointer for the new arguments... 2772 // These operations are automatically eliminated by the prolog/epilog pass 2773 if (!IsSibCall) { 2774 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 2775 2776 SmallVector<SDValue, 4> CopyFromChains; 2777 2778 // In the HSA case, this should be an identity copy. 2779 SDValue ScratchRSrcReg 2780 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 2781 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 2782 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 2783 Chain = DAG.getTokenFactor(DL, CopyFromChains); 2784 } 2785 2786 SmallVector<SDValue, 8> MemOpChains; 2787 MVT PtrVT = MVT::i32; 2788 2789 // Walk the register/memloc assignments, inserting copies/loads. 2790 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2791 CCValAssign &VA = ArgLocs[i]; 2792 SDValue Arg = OutVals[i]; 2793 2794 // Promote the value if needed. 2795 switch (VA.getLocInfo()) { 2796 case CCValAssign::Full: 2797 break; 2798 case CCValAssign::BCvt: 2799 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2800 break; 2801 case CCValAssign::ZExt: 2802 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2803 break; 2804 case CCValAssign::SExt: 2805 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2806 break; 2807 case CCValAssign::AExt: 2808 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2809 break; 2810 case CCValAssign::FPExt: 2811 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 2812 break; 2813 default: 2814 llvm_unreachable("Unknown loc info!"); 2815 } 2816 2817 if (VA.isRegLoc()) { 2818 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 2819 } else { 2820 assert(VA.isMemLoc()); 2821 2822 SDValue DstAddr; 2823 MachinePointerInfo DstInfo; 2824 2825 unsigned LocMemOffset = VA.getLocMemOffset(); 2826 int32_t Offset = LocMemOffset; 2827 2828 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 2829 MaybeAlign Alignment; 2830 2831 if (IsTailCall) { 2832 ISD::ArgFlagsTy Flags = Outs[i].Flags; 2833 unsigned OpSize = Flags.isByVal() ? 2834 Flags.getByValSize() : VA.getValVT().getStoreSize(); 2835 2836 // FIXME: We can have better than the minimum byval required alignment. 2837 Alignment = 2838 Flags.isByVal() 2839 ? Flags.getNonZeroByValAlign() 2840 : commonAlignment(Subtarget->getStackAlignment(), Offset); 2841 2842 Offset = Offset + FPDiff; 2843 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 2844 2845 DstAddr = DAG.getFrameIndex(FI, PtrVT); 2846 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 2847 2848 // Make sure any stack arguments overlapping with where we're storing 2849 // are loaded before this eventual operation. Otherwise they'll be 2850 // clobbered. 2851 2852 // FIXME: Why is this really necessary? This seems to just result in a 2853 // lot of code to copy the stack and write them back to the same 2854 // locations, which are supposed to be immutable? 2855 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 2856 } else { 2857 DstAddr = PtrOff; 2858 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 2859 Alignment = 2860 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 2861 } 2862 2863 if (Outs[i].Flags.isByVal()) { 2864 SDValue SizeNode = 2865 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 2866 SDValue Cpy = 2867 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 2868 Outs[i].Flags.getNonZeroByValAlign(), 2869 /*isVol = */ false, /*AlwaysInline = */ true, 2870 /*isTailCall = */ false, DstInfo, 2871 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 2872 2873 MemOpChains.push_back(Cpy); 2874 } else { 2875 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, 2876 Alignment ? Alignment->value() : 0); 2877 MemOpChains.push_back(Store); 2878 } 2879 } 2880 } 2881 2882 // Copy special input registers after user input arguments. 2883 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 2884 2885 if (!MemOpChains.empty()) 2886 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 2887 2888 // Build a sequence of copy-to-reg nodes chained together with token chain 2889 // and flag operands which copy the outgoing args into the appropriate regs. 2890 SDValue InFlag; 2891 for (auto &RegToPass : RegsToPass) { 2892 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 2893 RegToPass.second, InFlag); 2894 InFlag = Chain.getValue(1); 2895 } 2896 2897 2898 SDValue PhysReturnAddrReg; 2899 if (IsTailCall) { 2900 // Since the return is being combined with the call, we need to pass on the 2901 // return address. 2902 2903 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2904 SDValue ReturnAddrReg = CreateLiveInRegister( 2905 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2906 2907 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 2908 MVT::i64); 2909 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 2910 InFlag = Chain.getValue(1); 2911 } 2912 2913 // We don't usually want to end the call-sequence here because we would tidy 2914 // the frame up *after* the call, however in the ABI-changing tail-call case 2915 // we've carefully laid out the parameters so that when sp is reset they'll be 2916 // in the correct location. 2917 if (IsTailCall && !IsSibCall) { 2918 Chain = DAG.getCALLSEQ_END(Chain, 2919 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 2920 DAG.getTargetConstant(0, DL, MVT::i32), 2921 InFlag, DL); 2922 InFlag = Chain.getValue(1); 2923 } 2924 2925 std::vector<SDValue> Ops; 2926 Ops.push_back(Chain); 2927 Ops.push_back(Callee); 2928 // Add a redundant copy of the callee global which will not be legalized, as 2929 // we need direct access to the callee later. 2930 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee); 2931 const GlobalValue *GV = GSD->getGlobal(); 2932 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 2933 2934 if (IsTailCall) { 2935 // Each tail call may have to adjust the stack by a different amount, so 2936 // this information must travel along with the operation for eventual 2937 // consumption by emitEpilogue. 2938 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 2939 2940 Ops.push_back(PhysReturnAddrReg); 2941 } 2942 2943 // Add argument registers to the end of the list so that they are known live 2944 // into the call. 2945 for (auto &RegToPass : RegsToPass) { 2946 Ops.push_back(DAG.getRegister(RegToPass.first, 2947 RegToPass.second.getValueType())); 2948 } 2949 2950 // Add a register mask operand representing the call-preserved registers. 2951 2952 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 2953 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 2954 assert(Mask && "Missing call preserved mask for calling convention"); 2955 Ops.push_back(DAG.getRegisterMask(Mask)); 2956 2957 if (InFlag.getNode()) 2958 Ops.push_back(InFlag); 2959 2960 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 2961 2962 // If we're doing a tall call, use a TC_RETURN here rather than an 2963 // actual call instruction. 2964 if (IsTailCall) { 2965 MFI.setHasTailCall(); 2966 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 2967 } 2968 2969 // Returns a chain and a flag for retval copy to use. 2970 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 2971 Chain = Call.getValue(0); 2972 InFlag = Call.getValue(1); 2973 2974 uint64_t CalleePopBytes = NumBytes; 2975 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 2976 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 2977 InFlag, DL); 2978 if (!Ins.empty()) 2979 InFlag = Chain.getValue(1); 2980 2981 // Handle result values, copying them out of physregs into vregs that we 2982 // return. 2983 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 2984 InVals, IsThisReturn, 2985 IsThisReturn ? OutVals[0] : SDValue()); 2986 } 2987 2988 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 2989 const MachineFunction &MF) const { 2990 Register Reg = StringSwitch<Register>(RegName) 2991 .Case("m0", AMDGPU::M0) 2992 .Case("exec", AMDGPU::EXEC) 2993 .Case("exec_lo", AMDGPU::EXEC_LO) 2994 .Case("exec_hi", AMDGPU::EXEC_HI) 2995 .Case("flat_scratch", AMDGPU::FLAT_SCR) 2996 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 2997 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 2998 .Default(Register()); 2999 3000 if (Reg == AMDGPU::NoRegister) { 3001 report_fatal_error(Twine("invalid register name \"" 3002 + StringRef(RegName) + "\".")); 3003 3004 } 3005 3006 if (!Subtarget->hasFlatScrRegister() && 3007 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3008 report_fatal_error(Twine("invalid register \"" 3009 + StringRef(RegName) + "\" for subtarget.")); 3010 } 3011 3012 switch (Reg) { 3013 case AMDGPU::M0: 3014 case AMDGPU::EXEC_LO: 3015 case AMDGPU::EXEC_HI: 3016 case AMDGPU::FLAT_SCR_LO: 3017 case AMDGPU::FLAT_SCR_HI: 3018 if (VT.getSizeInBits() == 32) 3019 return Reg; 3020 break; 3021 case AMDGPU::EXEC: 3022 case AMDGPU::FLAT_SCR: 3023 if (VT.getSizeInBits() == 64) 3024 return Reg; 3025 break; 3026 default: 3027 llvm_unreachable("missing register type checking"); 3028 } 3029 3030 report_fatal_error(Twine("invalid type for register \"" 3031 + StringRef(RegName) + "\".")); 3032 } 3033 3034 // If kill is not the last instruction, split the block so kill is always a 3035 // proper terminator. 3036 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI, 3037 MachineBasicBlock *BB) const { 3038 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3039 3040 MachineBasicBlock::iterator SplitPoint(&MI); 3041 ++SplitPoint; 3042 3043 if (SplitPoint == BB->end()) { 3044 // Don't bother with a new block. 3045 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3046 return BB; 3047 } 3048 3049 MachineFunction *MF = BB->getParent(); 3050 MachineBasicBlock *SplitBB 3051 = MF->CreateMachineBasicBlock(BB->getBasicBlock()); 3052 3053 MF->insert(++MachineFunction::iterator(BB), SplitBB); 3054 SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end()); 3055 3056 SplitBB->transferSuccessorsAndUpdatePHIs(BB); 3057 BB->addSuccessor(SplitBB); 3058 3059 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3060 return SplitBB; 3061 } 3062 3063 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3064 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3065 // be the first instruction in the remainder block. 3066 // 3067 /// \returns { LoopBody, Remainder } 3068 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3069 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3070 MachineFunction *MF = MBB.getParent(); 3071 MachineBasicBlock::iterator I(&MI); 3072 3073 // To insert the loop we need to split the block. Move everything after this 3074 // point to a new block, and insert a new empty block between the two. 3075 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3076 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3077 MachineFunction::iterator MBBI(MBB); 3078 ++MBBI; 3079 3080 MF->insert(MBBI, LoopBB); 3081 MF->insert(MBBI, RemainderBB); 3082 3083 LoopBB->addSuccessor(LoopBB); 3084 LoopBB->addSuccessor(RemainderBB); 3085 3086 // Move the rest of the block into a new block. 3087 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3088 3089 if (InstInLoop) { 3090 auto Next = std::next(I); 3091 3092 // Move instruction to loop body. 3093 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3094 3095 // Move the rest of the block. 3096 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3097 } else { 3098 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3099 } 3100 3101 MBB.addSuccessor(LoopBB); 3102 3103 return std::make_pair(LoopBB, RemainderBB); 3104 } 3105 3106 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3107 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3108 MachineBasicBlock *MBB = MI.getParent(); 3109 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3110 auto I = MI.getIterator(); 3111 auto E = std::next(I); 3112 3113 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3114 .addImm(0); 3115 3116 MIBundleBuilder Bundler(*MBB, I, E); 3117 finalizeBundle(*MBB, Bundler.begin()); 3118 } 3119 3120 MachineBasicBlock * 3121 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3122 MachineBasicBlock *BB) const { 3123 const DebugLoc &DL = MI.getDebugLoc(); 3124 3125 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3126 3127 MachineBasicBlock *LoopBB; 3128 MachineBasicBlock *RemainderBB; 3129 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3130 3131 // Apparently kill flags are only valid if the def is in the same block? 3132 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3133 Src->setIsKill(false); 3134 3135 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3136 3137 MachineBasicBlock::iterator I = LoopBB->end(); 3138 3139 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3140 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3141 3142 // Clear TRAP_STS.MEM_VIOL 3143 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3144 .addImm(0) 3145 .addImm(EncodedReg); 3146 3147 bundleInstWithWaitcnt(MI); 3148 3149 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3150 3151 // Load and check TRAP_STS.MEM_VIOL 3152 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3153 .addImm(EncodedReg); 3154 3155 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3156 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3157 .addReg(Reg, RegState::Kill) 3158 .addImm(0); 3159 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3160 .addMBB(LoopBB); 3161 3162 return RemainderBB; 3163 } 3164 3165 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3166 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3167 // will only do one iteration. In the worst case, this will loop 64 times. 3168 // 3169 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3170 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop( 3171 const SIInstrInfo *TII, 3172 MachineRegisterInfo &MRI, 3173 MachineBasicBlock &OrigBB, 3174 MachineBasicBlock &LoopBB, 3175 const DebugLoc &DL, 3176 const MachineOperand &IdxReg, 3177 unsigned InitReg, 3178 unsigned ResultReg, 3179 unsigned PhiReg, 3180 unsigned InitSaveExecReg, 3181 int Offset, 3182 bool UseGPRIdxMode, 3183 bool IsIndirectSrc) { 3184 MachineFunction *MF = OrigBB.getParent(); 3185 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3186 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3187 MachineBasicBlock::iterator I = LoopBB.begin(); 3188 3189 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3190 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3191 Register NewExec = MRI.createVirtualRegister(BoolRC); 3192 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3193 Register CondReg = MRI.createVirtualRegister(BoolRC); 3194 3195 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3196 .addReg(InitReg) 3197 .addMBB(&OrigBB) 3198 .addReg(ResultReg) 3199 .addMBB(&LoopBB); 3200 3201 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3202 .addReg(InitSaveExecReg) 3203 .addMBB(&OrigBB) 3204 .addReg(NewExec) 3205 .addMBB(&LoopBB); 3206 3207 // Read the next variant <- also loop target. 3208 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3209 .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef())); 3210 3211 // Compare the just read M0 value to all possible Idx values. 3212 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3213 .addReg(CurrentIdxReg) 3214 .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg()); 3215 3216 // Update EXEC, save the original EXEC value to VCC. 3217 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3218 : AMDGPU::S_AND_SAVEEXEC_B64), 3219 NewExec) 3220 .addReg(CondReg, RegState::Kill); 3221 3222 MRI.setSimpleHint(NewExec, CondReg); 3223 3224 if (UseGPRIdxMode) { 3225 unsigned IdxReg; 3226 if (Offset == 0) { 3227 IdxReg = CurrentIdxReg; 3228 } else { 3229 IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3230 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg) 3231 .addReg(CurrentIdxReg, RegState::Kill) 3232 .addImm(Offset); 3233 } 3234 unsigned IdxMode = IsIndirectSrc ? 3235 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3236 MachineInstr *SetOn = 3237 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3238 .addReg(IdxReg, RegState::Kill) 3239 .addImm(IdxMode); 3240 SetOn->getOperand(3).setIsUndef(); 3241 } else { 3242 // Move index from VCC into M0 3243 if (Offset == 0) { 3244 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3245 .addReg(CurrentIdxReg, RegState::Kill); 3246 } else { 3247 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3248 .addReg(CurrentIdxReg, RegState::Kill) 3249 .addImm(Offset); 3250 } 3251 } 3252 3253 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3254 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3255 MachineInstr *InsertPt = 3256 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3257 : AMDGPU::S_XOR_B64_term), Exec) 3258 .addReg(Exec) 3259 .addReg(NewExec); 3260 3261 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3262 // s_cbranch_scc0? 3263 3264 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3265 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3266 .addMBB(&LoopBB); 3267 3268 return InsertPt->getIterator(); 3269 } 3270 3271 // This has slightly sub-optimal regalloc when the source vector is killed by 3272 // the read. The register allocator does not understand that the kill is 3273 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3274 // subregister from it, using 1 more VGPR than necessary. This was saved when 3275 // this was expanded after register allocation. 3276 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII, 3277 MachineBasicBlock &MBB, 3278 MachineInstr &MI, 3279 unsigned InitResultReg, 3280 unsigned PhiReg, 3281 int Offset, 3282 bool UseGPRIdxMode, 3283 bool IsIndirectSrc) { 3284 MachineFunction *MF = MBB.getParent(); 3285 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3286 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3287 MachineRegisterInfo &MRI = MF->getRegInfo(); 3288 const DebugLoc &DL = MI.getDebugLoc(); 3289 MachineBasicBlock::iterator I(&MI); 3290 3291 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3292 Register DstReg = MI.getOperand(0).getReg(); 3293 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3294 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3295 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3296 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3297 3298 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3299 3300 // Save the EXEC mask 3301 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3302 .addReg(Exec); 3303 3304 MachineBasicBlock *LoopBB; 3305 MachineBasicBlock *RemainderBB; 3306 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3307 3308 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3309 3310 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3311 InitResultReg, DstReg, PhiReg, TmpExec, 3312 Offset, UseGPRIdxMode, IsIndirectSrc); 3313 3314 MachineBasicBlock::iterator First = RemainderBB->begin(); 3315 BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec) 3316 .addReg(SaveExec); 3317 3318 return InsPt; 3319 } 3320 3321 // Returns subreg index, offset 3322 static std::pair<unsigned, int> 3323 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3324 const TargetRegisterClass *SuperRC, 3325 unsigned VecReg, 3326 int Offset) { 3327 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3328 3329 // Skip out of bounds offsets, or else we would end up using an undefined 3330 // register. 3331 if (Offset >= NumElts || Offset < 0) 3332 return std::make_pair(AMDGPU::sub0, Offset); 3333 3334 return std::make_pair(AMDGPU::sub0 + Offset, 0); 3335 } 3336 3337 // Return true if the index is an SGPR and was set. 3338 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3339 MachineRegisterInfo &MRI, 3340 MachineInstr &MI, 3341 int Offset, 3342 bool UseGPRIdxMode, 3343 bool IsIndirectSrc) { 3344 MachineBasicBlock *MBB = MI.getParent(); 3345 const DebugLoc &DL = MI.getDebugLoc(); 3346 MachineBasicBlock::iterator I(&MI); 3347 3348 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3349 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3350 3351 assert(Idx->getReg() != AMDGPU::NoRegister); 3352 3353 if (!TII->getRegisterInfo().isSGPRClass(IdxRC)) 3354 return false; 3355 3356 if (UseGPRIdxMode) { 3357 unsigned IdxMode = IsIndirectSrc ? 3358 AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE; 3359 if (Offset == 0) { 3360 MachineInstr *SetOn = 3361 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3362 .add(*Idx) 3363 .addImm(IdxMode); 3364 3365 SetOn->getOperand(3).setIsUndef(); 3366 } else { 3367 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3368 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3369 .add(*Idx) 3370 .addImm(Offset); 3371 MachineInstr *SetOn = 3372 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON)) 3373 .addReg(Tmp, RegState::Kill) 3374 .addImm(IdxMode); 3375 3376 SetOn->getOperand(3).setIsUndef(); 3377 } 3378 3379 return true; 3380 } 3381 3382 if (Offset == 0) { 3383 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3384 .add(*Idx); 3385 } else { 3386 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3387 .add(*Idx) 3388 .addImm(Offset); 3389 } 3390 3391 return true; 3392 } 3393 3394 // Control flow needs to be inserted if indexing with a VGPR. 3395 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3396 MachineBasicBlock &MBB, 3397 const GCNSubtarget &ST) { 3398 const SIInstrInfo *TII = ST.getInstrInfo(); 3399 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3400 MachineFunction *MF = MBB.getParent(); 3401 MachineRegisterInfo &MRI = MF->getRegInfo(); 3402 3403 Register Dst = MI.getOperand(0).getReg(); 3404 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3405 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3406 3407 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3408 3409 unsigned SubReg; 3410 std::tie(SubReg, Offset) 3411 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3412 3413 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3414 3415 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) { 3416 MachineBasicBlock::iterator I(&MI); 3417 const DebugLoc &DL = MI.getDebugLoc(); 3418 3419 if (UseGPRIdxMode) { 3420 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3421 // to avoid interfering with other uses, so probably requires a new 3422 // optimization pass. 3423 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3424 .addReg(SrcReg, RegState::Undef, SubReg) 3425 .addReg(SrcReg, RegState::Implicit) 3426 .addReg(AMDGPU::M0, RegState::Implicit); 3427 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3428 } else { 3429 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3430 .addReg(SrcReg, RegState::Undef, SubReg) 3431 .addReg(SrcReg, RegState::Implicit); 3432 } 3433 3434 MI.eraseFromParent(); 3435 3436 return &MBB; 3437 } 3438 3439 const DebugLoc &DL = MI.getDebugLoc(); 3440 MachineBasicBlock::iterator I(&MI); 3441 3442 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3443 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3444 3445 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3446 3447 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, 3448 Offset, UseGPRIdxMode, true); 3449 MachineBasicBlock *LoopBB = InsPt->getParent(); 3450 3451 if (UseGPRIdxMode) { 3452 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst) 3453 .addReg(SrcReg, RegState::Undef, SubReg) 3454 .addReg(SrcReg, RegState::Implicit) 3455 .addReg(AMDGPU::M0, RegState::Implicit); 3456 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3457 } else { 3458 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3459 .addReg(SrcReg, RegState::Undef, SubReg) 3460 .addReg(SrcReg, RegState::Implicit); 3461 } 3462 3463 MI.eraseFromParent(); 3464 3465 return LoopBB; 3466 } 3467 3468 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3469 MachineBasicBlock &MBB, 3470 const GCNSubtarget &ST) { 3471 const SIInstrInfo *TII = ST.getInstrInfo(); 3472 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3473 MachineFunction *MF = MBB.getParent(); 3474 MachineRegisterInfo &MRI = MF->getRegInfo(); 3475 3476 Register Dst = MI.getOperand(0).getReg(); 3477 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3478 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3479 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3480 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3481 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3482 3483 // This can be an immediate, but will be folded later. 3484 assert(Val->getReg()); 3485 3486 unsigned SubReg; 3487 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3488 SrcVec->getReg(), 3489 Offset); 3490 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3491 3492 if (Idx->getReg() == AMDGPU::NoRegister) { 3493 MachineBasicBlock::iterator I(&MI); 3494 const DebugLoc &DL = MI.getDebugLoc(); 3495 3496 assert(Offset == 0); 3497 3498 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3499 .add(*SrcVec) 3500 .add(*Val) 3501 .addImm(SubReg); 3502 3503 MI.eraseFromParent(); 3504 return &MBB; 3505 } 3506 3507 const MCInstrDesc &MovRelDesc 3508 = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false); 3509 3510 if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) { 3511 MachineBasicBlock::iterator I(&MI); 3512 const DebugLoc &DL = MI.getDebugLoc(); 3513 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3514 .addReg(SrcVec->getReg()) 3515 .add(*Val) 3516 .addImm(SubReg); 3517 if (UseGPRIdxMode) 3518 BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3519 3520 MI.eraseFromParent(); 3521 return &MBB; 3522 } 3523 3524 if (Val->isReg()) 3525 MRI.clearKillFlags(Val->getReg()); 3526 3527 const DebugLoc &DL = MI.getDebugLoc(); 3528 3529 Register PhiReg = MRI.createVirtualRegister(VecRC); 3530 3531 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, 3532 Offset, UseGPRIdxMode, false); 3533 MachineBasicBlock *LoopBB = InsPt->getParent(); 3534 3535 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3536 .addReg(PhiReg) 3537 .add(*Val) 3538 .addImm(AMDGPU::sub0); 3539 if (UseGPRIdxMode) 3540 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF)); 3541 3542 MI.eraseFromParent(); 3543 return LoopBB; 3544 } 3545 3546 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3547 MachineInstr &MI, MachineBasicBlock *BB) const { 3548 3549 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3550 MachineFunction *MF = BB->getParent(); 3551 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3552 3553 if (TII->isMIMG(MI)) { 3554 if (MI.memoperands_empty() && MI.mayLoadOrStore()) { 3555 report_fatal_error("missing mem operand from MIMG instruction"); 3556 } 3557 // Add a memoperand for mimg instructions so that they aren't assumed to 3558 // be ordered memory instuctions. 3559 3560 return BB; 3561 } 3562 3563 switch (MI.getOpcode()) { 3564 case AMDGPU::S_ADD_U64_PSEUDO: 3565 case AMDGPU::S_SUB_U64_PSEUDO: { 3566 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3567 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3568 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3569 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3570 const DebugLoc &DL = MI.getDebugLoc(); 3571 3572 MachineOperand &Dest = MI.getOperand(0); 3573 MachineOperand &Src0 = MI.getOperand(1); 3574 MachineOperand &Src1 = MI.getOperand(2); 3575 3576 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3577 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3578 3579 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3580 Src0, BoolRC, AMDGPU::sub0, 3581 &AMDGPU::SReg_32RegClass); 3582 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3583 Src0, BoolRC, AMDGPU::sub1, 3584 &AMDGPU::SReg_32RegClass); 3585 3586 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI, 3587 Src1, BoolRC, AMDGPU::sub0, 3588 &AMDGPU::SReg_32RegClass); 3589 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI, 3590 Src1, BoolRC, AMDGPU::sub1, 3591 &AMDGPU::SReg_32RegClass); 3592 3593 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3594 3595 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3596 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3597 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3598 .add(Src0Sub0) 3599 .add(Src1Sub0); 3600 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3601 .add(Src0Sub1) 3602 .add(Src1Sub1); 3603 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3604 .addReg(DestSub0) 3605 .addImm(AMDGPU::sub0) 3606 .addReg(DestSub1) 3607 .addImm(AMDGPU::sub1); 3608 MI.eraseFromParent(); 3609 return BB; 3610 } 3611 case AMDGPU::SI_INIT_M0: { 3612 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 3613 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3614 .add(MI.getOperand(0)); 3615 MI.eraseFromParent(); 3616 return BB; 3617 } 3618 case AMDGPU::SI_INIT_EXEC: 3619 // This should be before all vector instructions. 3620 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64), 3621 AMDGPU::EXEC) 3622 .addImm(MI.getOperand(0).getImm()); 3623 MI.eraseFromParent(); 3624 return BB; 3625 3626 case AMDGPU::SI_INIT_EXEC_LO: 3627 // This should be before all vector instructions. 3628 BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32), 3629 AMDGPU::EXEC_LO) 3630 .addImm(MI.getOperand(0).getImm()); 3631 MI.eraseFromParent(); 3632 return BB; 3633 3634 case AMDGPU::SI_INIT_EXEC_FROM_INPUT: { 3635 // Extract the thread count from an SGPR input and set EXEC accordingly. 3636 // Since BFM can't shift by 64, handle that case with CMP + CMOV. 3637 // 3638 // S_BFE_U32 count, input, {shift, 7} 3639 // S_BFM_B64 exec, count, 0 3640 // S_CMP_EQ_U32 count, 64 3641 // S_CMOV_B64 exec, -1 3642 MachineInstr *FirstMI = &*BB->begin(); 3643 MachineRegisterInfo &MRI = MF->getRegInfo(); 3644 Register InputReg = MI.getOperand(0).getReg(); 3645 Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3646 bool Found = false; 3647 3648 // Move the COPY of the input reg to the beginning, so that we can use it. 3649 for (auto I = BB->begin(); I != &MI; I++) { 3650 if (I->getOpcode() != TargetOpcode::COPY || 3651 I->getOperand(0).getReg() != InputReg) 3652 continue; 3653 3654 if (I == FirstMI) { 3655 FirstMI = &*++BB->begin(); 3656 } else { 3657 I->removeFromParent(); 3658 BB->insert(FirstMI, &*I); 3659 } 3660 Found = true; 3661 break; 3662 } 3663 assert(Found); 3664 (void)Found; 3665 3666 // This should be before all vector instructions. 3667 unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1; 3668 bool isWave32 = getSubtarget()->isWave32(); 3669 unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3670 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg) 3671 .addReg(InputReg) 3672 .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000); 3673 BuildMI(*BB, FirstMI, DebugLoc(), 3674 TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64), 3675 Exec) 3676 .addReg(CountReg) 3677 .addImm(0); 3678 BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32)) 3679 .addReg(CountReg, RegState::Kill) 3680 .addImm(getSubtarget()->getWavefrontSize()); 3681 BuildMI(*BB, FirstMI, DebugLoc(), 3682 TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64), 3683 Exec) 3684 .addImm(-1); 3685 MI.eraseFromParent(); 3686 return BB; 3687 } 3688 3689 case AMDGPU::GET_GROUPSTATICSIZE: { 3690 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 3691 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 3692 DebugLoc DL = MI.getDebugLoc(); 3693 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 3694 .add(MI.getOperand(0)) 3695 .addImm(MFI->getLDSSize()); 3696 MI.eraseFromParent(); 3697 return BB; 3698 } 3699 case AMDGPU::SI_INDIRECT_SRC_V1: 3700 case AMDGPU::SI_INDIRECT_SRC_V2: 3701 case AMDGPU::SI_INDIRECT_SRC_V4: 3702 case AMDGPU::SI_INDIRECT_SRC_V8: 3703 case AMDGPU::SI_INDIRECT_SRC_V16: 3704 return emitIndirectSrc(MI, *BB, *getSubtarget()); 3705 case AMDGPU::SI_INDIRECT_DST_V1: 3706 case AMDGPU::SI_INDIRECT_DST_V2: 3707 case AMDGPU::SI_INDIRECT_DST_V4: 3708 case AMDGPU::SI_INDIRECT_DST_V8: 3709 case AMDGPU::SI_INDIRECT_DST_V16: 3710 return emitIndirectDst(MI, *BB, *getSubtarget()); 3711 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 3712 case AMDGPU::SI_KILL_I1_PSEUDO: 3713 return splitKillBlock(MI, BB); 3714 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 3715 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3716 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3717 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3718 3719 Register Dst = MI.getOperand(0).getReg(); 3720 Register Src0 = MI.getOperand(1).getReg(); 3721 Register Src1 = MI.getOperand(2).getReg(); 3722 const DebugLoc &DL = MI.getDebugLoc(); 3723 Register SrcCond = MI.getOperand(3).getReg(); 3724 3725 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3726 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3727 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3728 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 3729 3730 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 3731 .addReg(SrcCond); 3732 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 3733 .addImm(0) 3734 .addReg(Src0, 0, AMDGPU::sub0) 3735 .addImm(0) 3736 .addReg(Src1, 0, AMDGPU::sub0) 3737 .addReg(SrcCondCopy); 3738 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 3739 .addImm(0) 3740 .addReg(Src0, 0, AMDGPU::sub1) 3741 .addImm(0) 3742 .addReg(Src1, 0, AMDGPU::sub1) 3743 .addReg(SrcCondCopy); 3744 3745 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 3746 .addReg(DstLo) 3747 .addImm(AMDGPU::sub0) 3748 .addReg(DstHi) 3749 .addImm(AMDGPU::sub1); 3750 MI.eraseFromParent(); 3751 return BB; 3752 } 3753 case AMDGPU::SI_BR_UNDEF: { 3754 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3755 const DebugLoc &DL = MI.getDebugLoc(); 3756 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3757 .add(MI.getOperand(0)); 3758 Br->getOperand(1).setIsUndef(true); // read undef SCC 3759 MI.eraseFromParent(); 3760 return BB; 3761 } 3762 case AMDGPU::ADJCALLSTACKUP: 3763 case AMDGPU::ADJCALLSTACKDOWN: { 3764 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 3765 MachineInstrBuilder MIB(*MF, &MI); 3766 3767 // Add an implicit use of the frame offset reg to prevent the restore copy 3768 // inserted after the call from being reorderd after stack operations in the 3769 // the caller's frame. 3770 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 3771 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit) 3772 .addReg(Info->getFrameOffsetReg(), RegState::Implicit); 3773 return BB; 3774 } 3775 case AMDGPU::SI_CALL_ISEL: { 3776 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3777 const DebugLoc &DL = MI.getDebugLoc(); 3778 3779 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 3780 3781 MachineInstrBuilder MIB; 3782 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 3783 3784 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 3785 MIB.add(MI.getOperand(I)); 3786 3787 MIB.cloneMemRefs(MI); 3788 MI.eraseFromParent(); 3789 return BB; 3790 } 3791 case AMDGPU::V_ADD_I32_e32: 3792 case AMDGPU::V_SUB_I32_e32: 3793 case AMDGPU::V_SUBREV_I32_e32: { 3794 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 3795 const DebugLoc &DL = MI.getDebugLoc(); 3796 unsigned Opc = MI.getOpcode(); 3797 3798 bool NeedClampOperand = false; 3799 if (TII->pseudoToMCOpcode(Opc) == -1) { 3800 Opc = AMDGPU::getVOPe64(Opc); 3801 NeedClampOperand = true; 3802 } 3803 3804 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 3805 if (TII->isVOP3(*I)) { 3806 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3807 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3808 I.addReg(TRI->getVCC(), RegState::Define); 3809 } 3810 I.add(MI.getOperand(1)) 3811 .add(MI.getOperand(2)); 3812 if (NeedClampOperand) 3813 I.addImm(0); // clamp bit for e64 encoding 3814 3815 TII->legalizeOperands(*I); 3816 3817 MI.eraseFromParent(); 3818 return BB; 3819 } 3820 case AMDGPU::DS_GWS_INIT: 3821 case AMDGPU::DS_GWS_SEMA_V: 3822 case AMDGPU::DS_GWS_SEMA_BR: 3823 case AMDGPU::DS_GWS_SEMA_P: 3824 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 3825 case AMDGPU::DS_GWS_BARRIER: 3826 // A s_waitcnt 0 is required to be the instruction immediately following. 3827 if (getSubtarget()->hasGWSAutoReplay()) { 3828 bundleInstWithWaitcnt(MI); 3829 return BB; 3830 } 3831 3832 return emitGWSMemViolTestLoop(MI, BB); 3833 default: 3834 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 3835 } 3836 } 3837 3838 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 3839 return isTypeLegal(VT.getScalarType()); 3840 } 3841 3842 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 3843 // This currently forces unfolding various combinations of fsub into fma with 3844 // free fneg'd operands. As long as we have fast FMA (controlled by 3845 // isFMAFasterThanFMulAndFAdd), we should perform these. 3846 3847 // When fma is quarter rate, for f64 where add / sub are at best half rate, 3848 // most of these combines appear to be cycle neutral but save on instruction 3849 // count / code size. 3850 return true; 3851 } 3852 3853 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 3854 EVT VT) const { 3855 if (!VT.isVector()) { 3856 return MVT::i1; 3857 } 3858 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 3859 } 3860 3861 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 3862 // TODO: Should i16 be used always if legal? For now it would force VALU 3863 // shifts. 3864 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 3865 } 3866 3867 // Answering this is somewhat tricky and depends on the specific device which 3868 // have different rates for fma or all f64 operations. 3869 // 3870 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 3871 // regardless of which device (although the number of cycles differs between 3872 // devices), so it is always profitable for f64. 3873 // 3874 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 3875 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 3876 // which we can always do even without fused FP ops since it returns the same 3877 // result as the separate operations and since it is always full 3878 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 3879 // however does not support denormals, so we do report fma as faster if we have 3880 // a fast fma device and require denormals. 3881 // 3882 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 3883 EVT VT) const { 3884 VT = VT.getScalarType(); 3885 3886 switch (VT.getSimpleVT().SimpleTy) { 3887 case MVT::f32: { 3888 // This is as fast on some subtargets. However, we always have full rate f32 3889 // mad available which returns the same result as the separate operations 3890 // which we should prefer over fma. We can't use this if we want to support 3891 // denormals, so only report this in these cases. 3892 if (hasFP32Denormals(MF)) 3893 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 3894 3895 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 3896 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 3897 } 3898 case MVT::f64: 3899 return true; 3900 case MVT::f16: 3901 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 3902 default: 3903 break; 3904 } 3905 3906 return false; 3907 } 3908 3909 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG, 3910 const SDNode *N) const { 3911 // TODO: Check future ftz flag 3912 // v_mad_f32/v_mac_f32 do not support denormals. 3913 EVT VT = N->getValueType(0); 3914 if (VT == MVT::f32) 3915 return !hasFP32Denormals(DAG.getMachineFunction()); 3916 if (VT == MVT::f16) { 3917 return Subtarget->hasMadF16() && 3918 !hasFP64FP16Denormals(DAG.getMachineFunction()); 3919 } 3920 3921 return false; 3922 } 3923 3924 //===----------------------------------------------------------------------===// 3925 // Custom DAG Lowering Operations 3926 //===----------------------------------------------------------------------===// 3927 3928 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3929 // wider vector type is legal. 3930 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 3931 SelectionDAG &DAG) const { 3932 unsigned Opc = Op.getOpcode(); 3933 EVT VT = Op.getValueType(); 3934 assert(VT == MVT::v4f16); 3935 3936 SDValue Lo, Hi; 3937 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 3938 3939 SDLoc SL(Op); 3940 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 3941 Op->getFlags()); 3942 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 3943 Op->getFlags()); 3944 3945 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3946 } 3947 3948 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 3949 // wider vector type is legal. 3950 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 3951 SelectionDAG &DAG) const { 3952 unsigned Opc = Op.getOpcode(); 3953 EVT VT = Op.getValueType(); 3954 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3955 3956 SDValue Lo0, Hi0; 3957 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3958 SDValue Lo1, Hi1; 3959 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3960 3961 SDLoc SL(Op); 3962 3963 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 3964 Op->getFlags()); 3965 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 3966 Op->getFlags()); 3967 3968 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3969 } 3970 3971 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 3972 SelectionDAG &DAG) const { 3973 unsigned Opc = Op.getOpcode(); 3974 EVT VT = Op.getValueType(); 3975 assert(VT == MVT::v4i16 || VT == MVT::v4f16); 3976 3977 SDValue Lo0, Hi0; 3978 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 3979 SDValue Lo1, Hi1; 3980 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 3981 SDValue Lo2, Hi2; 3982 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 3983 3984 SDLoc SL(Op); 3985 3986 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 3987 Op->getFlags()); 3988 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 3989 Op->getFlags()); 3990 3991 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 3992 } 3993 3994 3995 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 3996 switch (Op.getOpcode()) { 3997 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 3998 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 3999 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4000 case ISD::LOAD: { 4001 SDValue Result = LowerLOAD(Op, DAG); 4002 assert((!Result.getNode() || 4003 Result.getNode()->getNumValues() == 2) && 4004 "Load should return a value and a chain"); 4005 return Result; 4006 } 4007 4008 case ISD::FSIN: 4009 case ISD::FCOS: 4010 return LowerTrig(Op, DAG); 4011 case ISD::SELECT: return LowerSELECT(Op, DAG); 4012 case ISD::FDIV: return LowerFDIV(Op, DAG); 4013 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4014 case ISD::STORE: return LowerSTORE(Op, DAG); 4015 case ISD::GlobalAddress: { 4016 MachineFunction &MF = DAG.getMachineFunction(); 4017 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4018 return LowerGlobalAddress(MFI, Op, DAG); 4019 } 4020 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4021 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4022 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4023 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4024 case ISD::INSERT_SUBVECTOR: 4025 return lowerINSERT_SUBVECTOR(Op, DAG); 4026 case ISD::INSERT_VECTOR_ELT: 4027 return lowerINSERT_VECTOR_ELT(Op, DAG); 4028 case ISD::EXTRACT_VECTOR_ELT: 4029 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4030 case ISD::VECTOR_SHUFFLE: 4031 return lowerVECTOR_SHUFFLE(Op, DAG); 4032 case ISD::BUILD_VECTOR: 4033 return lowerBUILD_VECTOR(Op, DAG); 4034 case ISD::FP_ROUND: 4035 return lowerFP_ROUND(Op, DAG); 4036 case ISD::TRAP: 4037 return lowerTRAP(Op, DAG); 4038 case ISD::DEBUGTRAP: 4039 return lowerDEBUGTRAP(Op, DAG); 4040 case ISD::FABS: 4041 case ISD::FNEG: 4042 case ISD::FCANONICALIZE: 4043 return splitUnaryVectorOp(Op, DAG); 4044 case ISD::FMINNUM: 4045 case ISD::FMAXNUM: 4046 return lowerFMINNUM_FMAXNUM(Op, DAG); 4047 case ISD::FMA: 4048 return splitTernaryVectorOp(Op, DAG); 4049 case ISD::SHL: 4050 case ISD::SRA: 4051 case ISD::SRL: 4052 case ISD::ADD: 4053 case ISD::SUB: 4054 case ISD::MUL: 4055 case ISD::SMIN: 4056 case ISD::SMAX: 4057 case ISD::UMIN: 4058 case ISD::UMAX: 4059 case ISD::FADD: 4060 case ISD::FMUL: 4061 case ISD::FMINNUM_IEEE: 4062 case ISD::FMAXNUM_IEEE: 4063 return splitBinaryVectorOp(Op, DAG); 4064 } 4065 return SDValue(); 4066 } 4067 4068 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4069 const SDLoc &DL, 4070 SelectionDAG &DAG, bool Unpacked) { 4071 if (!LoadVT.isVector()) 4072 return Result; 4073 4074 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4075 // Truncate to v2i16/v4i16. 4076 EVT IntLoadVT = LoadVT.changeTypeToInteger(); 4077 4078 // Workaround legalizer not scalarizing truncate after vector op 4079 // legalization byt not creating intermediate vector trunc. 4080 SmallVector<SDValue, 4> Elts; 4081 DAG.ExtractVectorElements(Result, Elts); 4082 for (SDValue &Elt : Elts) 4083 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4084 4085 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4086 4087 // Bitcast to original type (v2f16/v4f16). 4088 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4089 } 4090 4091 // Cast back to the original packed type. 4092 return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result); 4093 } 4094 4095 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4096 MemSDNode *M, 4097 SelectionDAG &DAG, 4098 ArrayRef<SDValue> Ops, 4099 bool IsIntrinsic) const { 4100 SDLoc DL(M); 4101 4102 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4103 EVT LoadVT = M->getValueType(0); 4104 4105 EVT EquivLoadVT = LoadVT; 4106 if (Unpacked && LoadVT.isVector()) { 4107 EquivLoadVT = LoadVT.isVector() ? 4108 EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4109 LoadVT.getVectorNumElements()) : LoadVT; 4110 } 4111 4112 // Change from v4f16/v2f16 to EquivLoadVT. 4113 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4114 4115 SDValue Load 4116 = DAG.getMemIntrinsicNode( 4117 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4118 VTList, Ops, M->getMemoryVT(), 4119 M->getMemOperand()); 4120 if (!Unpacked) // Just adjusted the opcode. 4121 return Load; 4122 4123 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4124 4125 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4126 } 4127 4128 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4129 SelectionDAG &DAG, 4130 ArrayRef<SDValue> Ops) const { 4131 SDLoc DL(M); 4132 EVT LoadVT = M->getValueType(0); 4133 EVT EltType = LoadVT.getScalarType(); 4134 EVT IntVT = LoadVT.changeTypeToInteger(); 4135 4136 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4137 4138 unsigned Opc = 4139 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4140 4141 if (IsD16) { 4142 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4143 } 4144 4145 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4146 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4147 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4148 4149 if (isTypeLegal(LoadVT)) { 4150 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4151 M->getMemOperand(), DAG); 4152 } 4153 4154 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4155 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4156 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4157 M->getMemOperand(), DAG); 4158 return DAG.getMergeValues( 4159 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4160 DL); 4161 } 4162 4163 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4164 SDNode *N, SelectionDAG &DAG) { 4165 EVT VT = N->getValueType(0); 4166 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4167 int CondCode = CD->getSExtValue(); 4168 if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE || 4169 CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE) 4170 return DAG.getUNDEF(VT); 4171 4172 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4173 4174 SDValue LHS = N->getOperand(1); 4175 SDValue RHS = N->getOperand(2); 4176 4177 SDLoc DL(N); 4178 4179 EVT CmpVT = LHS.getValueType(); 4180 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4181 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4182 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4183 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4184 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4185 } 4186 4187 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4188 4189 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4190 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4191 4192 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4193 DAG.getCondCode(CCOpcode)); 4194 if (VT.bitsEq(CCVT)) 4195 return SetCC; 4196 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4197 } 4198 4199 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4200 SDNode *N, SelectionDAG &DAG) { 4201 EVT VT = N->getValueType(0); 4202 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4203 4204 int CondCode = CD->getSExtValue(); 4205 if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE || 4206 CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) { 4207 return DAG.getUNDEF(VT); 4208 } 4209 4210 SDValue Src0 = N->getOperand(1); 4211 SDValue Src1 = N->getOperand(2); 4212 EVT CmpVT = Src0.getValueType(); 4213 SDLoc SL(N); 4214 4215 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4216 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4217 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4218 } 4219 4220 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4221 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4222 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4223 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4224 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4225 Src1, DAG.getCondCode(CCOpcode)); 4226 if (VT.bitsEq(CCVT)) 4227 return SetCC; 4228 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4229 } 4230 4231 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4232 SmallVectorImpl<SDValue> &Results, 4233 SelectionDAG &DAG) const { 4234 switch (N->getOpcode()) { 4235 case ISD::INSERT_VECTOR_ELT: { 4236 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4237 Results.push_back(Res); 4238 return; 4239 } 4240 case ISD::EXTRACT_VECTOR_ELT: { 4241 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4242 Results.push_back(Res); 4243 return; 4244 } 4245 case ISD::INTRINSIC_WO_CHAIN: { 4246 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4247 switch (IID) { 4248 case Intrinsic::amdgcn_cvt_pkrtz: { 4249 SDValue Src0 = N->getOperand(1); 4250 SDValue Src1 = N->getOperand(2); 4251 SDLoc SL(N); 4252 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4253 Src0, Src1); 4254 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4255 return; 4256 } 4257 case Intrinsic::amdgcn_cvt_pknorm_i16: 4258 case Intrinsic::amdgcn_cvt_pknorm_u16: 4259 case Intrinsic::amdgcn_cvt_pk_i16: 4260 case Intrinsic::amdgcn_cvt_pk_u16: { 4261 SDValue Src0 = N->getOperand(1); 4262 SDValue Src1 = N->getOperand(2); 4263 SDLoc SL(N); 4264 unsigned Opcode; 4265 4266 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4267 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4268 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4269 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4270 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4271 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4272 else 4273 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4274 4275 EVT VT = N->getValueType(0); 4276 if (isTypeLegal(VT)) 4277 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4278 else { 4279 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4280 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4281 } 4282 return; 4283 } 4284 } 4285 break; 4286 } 4287 case ISD::INTRINSIC_W_CHAIN: { 4288 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4289 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4290 // FIXME: Hacky 4291 Results.push_back(Res.getOperand(0)); 4292 Results.push_back(Res.getOperand(1)); 4293 } else { 4294 Results.push_back(Res); 4295 Results.push_back(Res.getValue(1)); 4296 } 4297 return; 4298 } 4299 4300 break; 4301 } 4302 case ISD::SELECT: { 4303 SDLoc SL(N); 4304 EVT VT = N->getValueType(0); 4305 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4306 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4307 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4308 4309 EVT SelectVT = NewVT; 4310 if (NewVT.bitsLT(MVT::i32)) { 4311 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4312 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4313 SelectVT = MVT::i32; 4314 } 4315 4316 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4317 N->getOperand(0), LHS, RHS); 4318 4319 if (NewVT != SelectVT) 4320 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4321 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4322 return; 4323 } 4324 case ISD::FNEG: { 4325 if (N->getValueType(0) != MVT::v2f16) 4326 break; 4327 4328 SDLoc SL(N); 4329 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4330 4331 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4332 BC, 4333 DAG.getConstant(0x80008000, SL, MVT::i32)); 4334 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4335 return; 4336 } 4337 case ISD::FABS: { 4338 if (N->getValueType(0) != MVT::v2f16) 4339 break; 4340 4341 SDLoc SL(N); 4342 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4343 4344 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4345 BC, 4346 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4347 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4348 return; 4349 } 4350 default: 4351 break; 4352 } 4353 } 4354 4355 /// Helper function for LowerBRCOND 4356 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4357 4358 SDNode *Parent = Value.getNode(); 4359 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4360 I != E; ++I) { 4361 4362 if (I.getUse().get() != Value) 4363 continue; 4364 4365 if (I->getOpcode() == Opcode) 4366 return *I; 4367 } 4368 return nullptr; 4369 } 4370 4371 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4372 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4373 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4374 case Intrinsic::amdgcn_if: 4375 return AMDGPUISD::IF; 4376 case Intrinsic::amdgcn_else: 4377 return AMDGPUISD::ELSE; 4378 case Intrinsic::amdgcn_loop: 4379 return AMDGPUISD::LOOP; 4380 case Intrinsic::amdgcn_end_cf: 4381 llvm_unreachable("should not occur"); 4382 default: 4383 return 0; 4384 } 4385 } 4386 4387 // break, if_break, else_break are all only used as inputs to loop, not 4388 // directly as branch conditions. 4389 return 0; 4390 } 4391 4392 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4393 const Triple &TT = getTargetMachine().getTargetTriple(); 4394 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4395 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4396 AMDGPU::shouldEmitConstantsToTextSection(TT); 4397 } 4398 4399 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4400 // FIXME: Either avoid relying on address space here or change the default 4401 // address space for functions to avoid the explicit check. 4402 return (GV->getValueType()->isFunctionTy() || 4403 GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 4404 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4405 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4406 !shouldEmitFixup(GV) && 4407 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4408 } 4409 4410 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4411 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4412 } 4413 4414 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4415 if (!GV->hasExternalLinkage()) 4416 return true; 4417 4418 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4419 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4420 } 4421 4422 /// This transforms the control flow intrinsics to get the branch destination as 4423 /// last parameter, also switches branch target with BR if the need arise 4424 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4425 SelectionDAG &DAG) const { 4426 SDLoc DL(BRCOND); 4427 4428 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4429 SDValue Target = BRCOND.getOperand(2); 4430 SDNode *BR = nullptr; 4431 SDNode *SetCC = nullptr; 4432 4433 if (Intr->getOpcode() == ISD::SETCC) { 4434 // As long as we negate the condition everything is fine 4435 SetCC = Intr; 4436 Intr = SetCC->getOperand(0).getNode(); 4437 4438 } else { 4439 // Get the target from BR if we don't negate the condition 4440 BR = findUser(BRCOND, ISD::BR); 4441 Target = BR->getOperand(1); 4442 } 4443 4444 // FIXME: This changes the types of the intrinsics instead of introducing new 4445 // nodes with the correct types. 4446 // e.g. llvm.amdgcn.loop 4447 4448 // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3 4449 // => t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088> 4450 4451 unsigned CFNode = isCFIntrinsic(Intr); 4452 if (CFNode == 0) { 4453 // This is a uniform branch so we don't need to legalize. 4454 return BRCOND; 4455 } 4456 4457 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4458 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4459 4460 assert(!SetCC || 4461 (SetCC->getConstantOperandVal(1) == 1 && 4462 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4463 ISD::SETNE)); 4464 4465 // operands of the new intrinsic call 4466 SmallVector<SDValue, 4> Ops; 4467 if (HaveChain) 4468 Ops.push_back(BRCOND.getOperand(0)); 4469 4470 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 4471 Ops.push_back(Target); 4472 4473 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 4474 4475 // build the new intrinsic call 4476 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 4477 4478 if (!HaveChain) { 4479 SDValue Ops[] = { 4480 SDValue(Result, 0), 4481 BRCOND.getOperand(0) 4482 }; 4483 4484 Result = DAG.getMergeValues(Ops, DL).getNode(); 4485 } 4486 4487 if (BR) { 4488 // Give the branch instruction our target 4489 SDValue Ops[] = { 4490 BR->getOperand(0), 4491 BRCOND.getOperand(2) 4492 }; 4493 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 4494 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 4495 BR = NewBR.getNode(); 4496 } 4497 4498 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 4499 4500 // Copy the intrinsic results to registers 4501 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 4502 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 4503 if (!CopyToReg) 4504 continue; 4505 4506 Chain = DAG.getCopyToReg( 4507 Chain, DL, 4508 CopyToReg->getOperand(1), 4509 SDValue(Result, i - 1), 4510 SDValue()); 4511 4512 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 4513 } 4514 4515 // Remove the old intrinsic from the chain 4516 DAG.ReplaceAllUsesOfValueWith( 4517 SDValue(Intr, Intr->getNumValues() - 1), 4518 Intr->getOperand(0)); 4519 4520 return Chain; 4521 } 4522 4523 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 4524 SelectionDAG &DAG) const { 4525 MVT VT = Op.getSimpleValueType(); 4526 SDLoc DL(Op); 4527 // Checking the depth 4528 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 4529 return DAG.getConstant(0, DL, VT); 4530 4531 MachineFunction &MF = DAG.getMachineFunction(); 4532 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4533 // Check for kernel and shader functions 4534 if (Info->isEntryFunction()) 4535 return DAG.getConstant(0, DL, VT); 4536 4537 MachineFrameInfo &MFI = MF.getFrameInfo(); 4538 // There is a call to @llvm.returnaddress in this function 4539 MFI.setReturnAddressIsTaken(true); 4540 4541 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 4542 // Get the return address reg and mark it as an implicit live-in 4543 unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 4544 4545 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4546 } 4547 4548 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG, 4549 SDValue Op, 4550 const SDLoc &DL, 4551 EVT VT) const { 4552 return Op.getValueType().bitsLE(VT) ? 4553 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 4554 DAG.getNode(ISD::FTRUNC, DL, VT, Op); 4555 } 4556 4557 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 4558 assert(Op.getValueType() == MVT::f16 && 4559 "Do not know how to custom lower FP_ROUND for non-f16 type"); 4560 4561 SDValue Src = Op.getOperand(0); 4562 EVT SrcVT = Src.getValueType(); 4563 if (SrcVT != MVT::f64) 4564 return Op; 4565 4566 SDLoc DL(Op); 4567 4568 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 4569 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 4570 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 4571 } 4572 4573 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 4574 SelectionDAG &DAG) const { 4575 EVT VT = Op.getValueType(); 4576 const MachineFunction &MF = DAG.getMachineFunction(); 4577 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4578 bool IsIEEEMode = Info->getMode().IEEE; 4579 4580 // FIXME: Assert during eslection that this is only selected for 4581 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 4582 // mode functions, but this happens to be OK since it's only done in cases 4583 // where there is known no sNaN. 4584 if (IsIEEEMode) 4585 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 4586 4587 if (VT == MVT::v4f16) 4588 return splitBinaryVectorOp(Op, DAG); 4589 return Op; 4590 } 4591 4592 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 4593 SDLoc SL(Op); 4594 SDValue Chain = Op.getOperand(0); 4595 4596 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4597 !Subtarget->isTrapHandlerEnabled()) 4598 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 4599 4600 MachineFunction &MF = DAG.getMachineFunction(); 4601 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4602 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4603 assert(UserSGPR != AMDGPU::NoRegister); 4604 SDValue QueuePtr = CreateLiveInRegister( 4605 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4606 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 4607 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 4608 QueuePtr, SDValue()); 4609 SDValue Ops[] = { 4610 ToReg, 4611 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 4612 SGPR01, 4613 ToReg.getValue(1) 4614 }; 4615 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4616 } 4617 4618 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 4619 SDLoc SL(Op); 4620 SDValue Chain = Op.getOperand(0); 4621 MachineFunction &MF = DAG.getMachineFunction(); 4622 4623 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 4624 !Subtarget->isTrapHandlerEnabled()) { 4625 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 4626 "debugtrap handler not supported", 4627 Op.getDebugLoc(), 4628 DS_Warning); 4629 LLVMContext &Ctx = MF.getFunction().getContext(); 4630 Ctx.diagnose(NoTrap); 4631 return Chain; 4632 } 4633 4634 SDValue Ops[] = { 4635 Chain, 4636 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 4637 }; 4638 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 4639 } 4640 4641 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 4642 SelectionDAG &DAG) const { 4643 // FIXME: Use inline constants (src_{shared, private}_base) instead. 4644 if (Subtarget->hasApertureRegs()) { 4645 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 4646 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 4647 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 4648 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 4649 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 4650 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 4651 unsigned Encoding = 4652 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 4653 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 4654 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 4655 4656 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 4657 SDValue ApertureReg = SDValue( 4658 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 4659 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 4660 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 4661 } 4662 4663 MachineFunction &MF = DAG.getMachineFunction(); 4664 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 4665 unsigned UserSGPR = Info->getQueuePtrUserSGPR(); 4666 assert(UserSGPR != AMDGPU::NoRegister); 4667 4668 SDValue QueuePtr = CreateLiveInRegister( 4669 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 4670 4671 // Offset into amd_queue_t for group_segment_aperture_base_hi / 4672 // private_segment_aperture_base_hi. 4673 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 4674 4675 SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset); 4676 4677 // TODO: Use custom target PseudoSourceValue. 4678 // TODO: We should use the value from the IR intrinsic call, but it might not 4679 // be available and how do we get it? 4680 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 4681 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 4682 MinAlign(64, StructOffset), 4683 MachineMemOperand::MODereferenceable | 4684 MachineMemOperand::MOInvariant); 4685 } 4686 4687 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 4688 SelectionDAG &DAG) const { 4689 SDLoc SL(Op); 4690 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 4691 4692 SDValue Src = ASC->getOperand(0); 4693 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 4694 4695 const AMDGPUTargetMachine &TM = 4696 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 4697 4698 // flat -> local/private 4699 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4700 unsigned DestAS = ASC->getDestAddressSpace(); 4701 4702 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 4703 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 4704 unsigned NullVal = TM.getNullPointerValue(DestAS); 4705 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4706 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 4707 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 4708 4709 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 4710 NonNull, Ptr, SegmentNullPtr); 4711 } 4712 } 4713 4714 // local/private -> flat 4715 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 4716 unsigned SrcAS = ASC->getSrcAddressSpace(); 4717 4718 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 4719 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 4720 unsigned NullVal = TM.getNullPointerValue(SrcAS); 4721 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 4722 4723 SDValue NonNull 4724 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 4725 4726 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 4727 SDValue CvtPtr 4728 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 4729 4730 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 4731 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 4732 FlatNullPtr); 4733 } 4734 } 4735 4736 // global <-> flat are no-ops and never emitted. 4737 4738 const MachineFunction &MF = DAG.getMachineFunction(); 4739 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 4740 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 4741 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 4742 4743 return DAG.getUNDEF(ASC->getValueType(0)); 4744 } 4745 4746 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 4747 // the small vector and inserting them into the big vector. That is better than 4748 // the default expansion of doing it via a stack slot. Even though the use of 4749 // the stack slot would be optimized away afterwards, the stack slot itself 4750 // remains. 4751 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 4752 SelectionDAG &DAG) const { 4753 SDValue Vec = Op.getOperand(0); 4754 SDValue Ins = Op.getOperand(1); 4755 SDValue Idx = Op.getOperand(2); 4756 EVT VecVT = Vec.getValueType(); 4757 EVT InsVT = Ins.getValueType(); 4758 EVT EltVT = VecVT.getVectorElementType(); 4759 unsigned InsNumElts = InsVT.getVectorNumElements(); 4760 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 4761 SDLoc SL(Op); 4762 4763 for (unsigned I = 0; I != InsNumElts; ++I) { 4764 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 4765 DAG.getConstant(I, SL, MVT::i32)); 4766 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 4767 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 4768 } 4769 return Vec; 4770 } 4771 4772 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4773 SelectionDAG &DAG) const { 4774 SDValue Vec = Op.getOperand(0); 4775 SDValue InsVal = Op.getOperand(1); 4776 SDValue Idx = Op.getOperand(2); 4777 EVT VecVT = Vec.getValueType(); 4778 EVT EltVT = VecVT.getVectorElementType(); 4779 unsigned VecSize = VecVT.getSizeInBits(); 4780 unsigned EltSize = EltVT.getSizeInBits(); 4781 4782 4783 assert(VecSize <= 64); 4784 4785 unsigned NumElts = VecVT.getVectorNumElements(); 4786 SDLoc SL(Op); 4787 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 4788 4789 if (NumElts == 4 && EltSize == 16 && KIdx) { 4790 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 4791 4792 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4793 DAG.getConstant(0, SL, MVT::i32)); 4794 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 4795 DAG.getConstant(1, SL, MVT::i32)); 4796 4797 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 4798 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 4799 4800 unsigned Idx = KIdx->getZExtValue(); 4801 bool InsertLo = Idx < 2; 4802 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 4803 InsertLo ? LoVec : HiVec, 4804 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 4805 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 4806 4807 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 4808 4809 SDValue Concat = InsertLo ? 4810 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 4811 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 4812 4813 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 4814 } 4815 4816 if (isa<ConstantSDNode>(Idx)) 4817 return SDValue(); 4818 4819 MVT IntVT = MVT::getIntegerVT(VecSize); 4820 4821 // Avoid stack access for dynamic indexing. 4822 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 4823 4824 // Create a congruent vector with the target value in each element so that 4825 // the required element can be masked and ORed into the target vector. 4826 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 4827 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 4828 4829 assert(isPowerOf2_32(EltSize)); 4830 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4831 4832 // Convert vector index to bit-index. 4833 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4834 4835 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4836 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 4837 DAG.getConstant(0xffff, SL, IntVT), 4838 ScaledIdx); 4839 4840 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 4841 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 4842 DAG.getNOT(SL, BFM, IntVT), BCVec); 4843 4844 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 4845 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 4846 } 4847 4848 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4849 SelectionDAG &DAG) const { 4850 SDLoc SL(Op); 4851 4852 EVT ResultVT = Op.getValueType(); 4853 SDValue Vec = Op.getOperand(0); 4854 SDValue Idx = Op.getOperand(1); 4855 EVT VecVT = Vec.getValueType(); 4856 unsigned VecSize = VecVT.getSizeInBits(); 4857 EVT EltVT = VecVT.getVectorElementType(); 4858 assert(VecSize <= 64); 4859 4860 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 4861 4862 // Make sure we do any optimizations that will make it easier to fold 4863 // source modifiers before obscuring it with bit operations. 4864 4865 // XXX - Why doesn't this get called when vector_shuffle is expanded? 4866 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 4867 return Combined; 4868 4869 unsigned EltSize = EltVT.getSizeInBits(); 4870 assert(isPowerOf2_32(EltSize)); 4871 4872 MVT IntVT = MVT::getIntegerVT(VecSize); 4873 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 4874 4875 // Convert vector index to bit-index (* EltSize) 4876 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 4877 4878 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 4879 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 4880 4881 if (ResultVT == MVT::f16) { 4882 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 4883 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 4884 } 4885 4886 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 4887 } 4888 4889 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 4890 assert(Elt % 2 == 0); 4891 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 4892 } 4893 4894 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 4895 SelectionDAG &DAG) const { 4896 SDLoc SL(Op); 4897 EVT ResultVT = Op.getValueType(); 4898 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 4899 4900 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 4901 EVT EltVT = PackVT.getVectorElementType(); 4902 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 4903 4904 // vector_shuffle <0,1,6,7> lhs, rhs 4905 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 4906 // 4907 // vector_shuffle <6,7,2,3> lhs, rhs 4908 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 4909 // 4910 // vector_shuffle <6,7,0,1> lhs, rhs 4911 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 4912 4913 // Avoid scalarizing when both halves are reading from consecutive elements. 4914 SmallVector<SDValue, 4> Pieces; 4915 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 4916 if (elementPairIsContiguous(SVN->getMask(), I)) { 4917 const int Idx = SVN->getMaskElt(I); 4918 int VecIdx = Idx < SrcNumElts ? 0 : 1; 4919 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 4920 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 4921 PackVT, SVN->getOperand(VecIdx), 4922 DAG.getConstant(EltIdx, SL, MVT::i32)); 4923 Pieces.push_back(SubVec); 4924 } else { 4925 const int Idx0 = SVN->getMaskElt(I); 4926 const int Idx1 = SVN->getMaskElt(I + 1); 4927 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 4928 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 4929 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 4930 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 4931 4932 SDValue Vec0 = SVN->getOperand(VecIdx0); 4933 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4934 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 4935 4936 SDValue Vec1 = SVN->getOperand(VecIdx1); 4937 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 4938 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 4939 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 4940 } 4941 } 4942 4943 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 4944 } 4945 4946 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 4947 SelectionDAG &DAG) const { 4948 SDLoc SL(Op); 4949 EVT VT = Op.getValueType(); 4950 4951 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 4952 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 4953 4954 // Turn into pair of packed build_vectors. 4955 // TODO: Special case for constants that can be materialized with s_mov_b64. 4956 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 4957 { Op.getOperand(0), Op.getOperand(1) }); 4958 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 4959 { Op.getOperand(2), Op.getOperand(3) }); 4960 4961 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 4962 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 4963 4964 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 4965 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 4966 } 4967 4968 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 4969 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 4970 4971 SDValue Lo = Op.getOperand(0); 4972 SDValue Hi = Op.getOperand(1); 4973 4974 // Avoid adding defined bits with the zero_extend. 4975 if (Hi.isUndef()) { 4976 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4977 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 4978 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 4979 } 4980 4981 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 4982 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 4983 4984 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 4985 DAG.getConstant(16, SL, MVT::i32)); 4986 if (Lo.isUndef()) 4987 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 4988 4989 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 4990 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 4991 4992 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 4993 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 4994 } 4995 4996 bool 4997 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 4998 // We can fold offsets for anything that doesn't require a GOT relocation. 4999 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5000 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5001 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5002 !shouldEmitGOTReloc(GA->getGlobal()); 5003 } 5004 5005 static SDValue 5006 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5007 const SDLoc &DL, unsigned Offset, EVT PtrVT, 5008 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5009 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5010 // lowered to the following code sequence: 5011 // 5012 // For constant address space: 5013 // s_getpc_b64 s[0:1] 5014 // s_add_u32 s0, s0, $symbol 5015 // s_addc_u32 s1, s1, 0 5016 // 5017 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5018 // a fixup or relocation is emitted to replace $symbol with a literal 5019 // constant, which is a pc-relative offset from the encoding of the $symbol 5020 // operand to the global variable. 5021 // 5022 // For global address space: 5023 // s_getpc_b64 s[0:1] 5024 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5025 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5026 // 5027 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5028 // fixups or relocations are emitted to replace $symbol@*@lo and 5029 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5030 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5031 // operand to the global variable. 5032 // 5033 // What we want here is an offset from the value returned by s_getpc 5034 // (which is the address of the s_add_u32 instruction) to the global 5035 // variable, but since the encoding of $symbol starts 4 bytes after the start 5036 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5037 // small. This requires us to add 4 to the global variable offset in order to 5038 // compute the correct address. 5039 SDValue PtrLo = 5040 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5041 SDValue PtrHi; 5042 if (GAFlags == SIInstrInfo::MO_NONE) { 5043 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5044 } else { 5045 PtrHi = 5046 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1); 5047 } 5048 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5049 } 5050 5051 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5052 SDValue Op, 5053 SelectionDAG &DAG) const { 5054 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5055 const GlobalValue *GV = GSD->getGlobal(); 5056 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5057 shouldUseLDSConstAddress(GV)) || 5058 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5059 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) 5060 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5061 5062 SDLoc DL(GSD); 5063 EVT PtrVT = Op.getValueType(); 5064 5065 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5066 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5067 SIInstrInfo::MO_ABS32_LO); 5068 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5069 } 5070 5071 if (shouldEmitFixup(GV)) 5072 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5073 else if (shouldEmitPCReloc(GV)) 5074 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5075 SIInstrInfo::MO_REL32); 5076 5077 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5078 SIInstrInfo::MO_GOTPCREL32); 5079 5080 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5081 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5082 const DataLayout &DataLayout = DAG.getDataLayout(); 5083 unsigned Align = DataLayout.getABITypeAlignment(PtrTy); 5084 MachinePointerInfo PtrInfo 5085 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5086 5087 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align, 5088 MachineMemOperand::MODereferenceable | 5089 MachineMemOperand::MOInvariant); 5090 } 5091 5092 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5093 const SDLoc &DL, SDValue V) const { 5094 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5095 // the destination register. 5096 // 5097 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5098 // so we will end up with redundant moves to m0. 5099 // 5100 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5101 5102 // A Null SDValue creates a glue result. 5103 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5104 V, Chain); 5105 return SDValue(M0, 0); 5106 } 5107 5108 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5109 SDValue Op, 5110 MVT VT, 5111 unsigned Offset) const { 5112 SDLoc SL(Op); 5113 SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL, 5114 DAG.getEntryNode(), Offset, 4, false); 5115 // The local size values will have the hi 16-bits as zero. 5116 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5117 DAG.getValueType(VT)); 5118 } 5119 5120 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5121 EVT VT) { 5122 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5123 "non-hsa intrinsic with hsa target", 5124 DL.getDebugLoc()); 5125 DAG.getContext()->diagnose(BadIntrin); 5126 return DAG.getUNDEF(VT); 5127 } 5128 5129 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5130 EVT VT) { 5131 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5132 "intrinsic not supported on subtarget", 5133 DL.getDebugLoc()); 5134 DAG.getContext()->diagnose(BadIntrin); 5135 return DAG.getUNDEF(VT); 5136 } 5137 5138 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5139 ArrayRef<SDValue> Elts) { 5140 assert(!Elts.empty()); 5141 MVT Type; 5142 unsigned NumElts; 5143 5144 if (Elts.size() == 1) { 5145 Type = MVT::f32; 5146 NumElts = 1; 5147 } else if (Elts.size() == 2) { 5148 Type = MVT::v2f32; 5149 NumElts = 2; 5150 } else if (Elts.size() <= 4) { 5151 Type = MVT::v4f32; 5152 NumElts = 4; 5153 } else if (Elts.size() <= 8) { 5154 Type = MVT::v8f32; 5155 NumElts = 8; 5156 } else { 5157 assert(Elts.size() <= 16); 5158 Type = MVT::v16f32; 5159 NumElts = 16; 5160 } 5161 5162 SmallVector<SDValue, 16> VecElts(NumElts); 5163 for (unsigned i = 0; i < Elts.size(); ++i) { 5164 SDValue Elt = Elts[i]; 5165 if (Elt.getValueType() != MVT::f32) 5166 Elt = DAG.getBitcast(MVT::f32, Elt); 5167 VecElts[i] = Elt; 5168 } 5169 for (unsigned i = Elts.size(); i < NumElts; ++i) 5170 VecElts[i] = DAG.getUNDEF(MVT::f32); 5171 5172 if (NumElts == 1) 5173 return VecElts[0]; 5174 return DAG.getBuildVector(Type, DL, VecElts); 5175 } 5176 5177 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG, 5178 SDValue *GLC, SDValue *SLC, SDValue *DLC) { 5179 auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode()); 5180 5181 uint64_t Value = CachePolicyConst->getZExtValue(); 5182 SDLoc DL(CachePolicy); 5183 if (GLC) { 5184 *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5185 Value &= ~(uint64_t)0x1; 5186 } 5187 if (SLC) { 5188 *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5189 Value &= ~(uint64_t)0x2; 5190 } 5191 if (DLC) { 5192 *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32); 5193 Value &= ~(uint64_t)0x4; 5194 } 5195 5196 return Value == 0; 5197 } 5198 5199 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5200 SDValue Src, int ExtraElts) { 5201 EVT SrcVT = Src.getValueType(); 5202 5203 SmallVector<SDValue, 8> Elts; 5204 5205 if (SrcVT.isVector()) 5206 DAG.ExtractVectorElements(Src, Elts); 5207 else 5208 Elts.push_back(Src); 5209 5210 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5211 while (ExtraElts--) 5212 Elts.push_back(Undef); 5213 5214 return DAG.getBuildVector(CastVT, DL, Elts); 5215 } 5216 5217 // Re-construct the required return value for a image load intrinsic. 5218 // This is more complicated due to the optional use TexFailCtrl which means the required 5219 // return type is an aggregate 5220 static SDValue constructRetValue(SelectionDAG &DAG, 5221 MachineSDNode *Result, 5222 ArrayRef<EVT> ResultTypes, 5223 bool IsTexFail, bool Unpacked, bool IsD16, 5224 int DMaskPop, int NumVDataDwords, 5225 const SDLoc &DL, LLVMContext &Context) { 5226 // Determine the required return type. This is the same regardless of IsTexFail flag 5227 EVT ReqRetVT = ResultTypes[0]; 5228 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5229 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5230 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5231 5232 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5233 DMaskPop : (DMaskPop + 1) / 2; 5234 5235 MVT DataDwordVT = NumDataDwords == 1 ? 5236 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5237 5238 MVT MaskPopVT = MaskPopDwords == 1 ? 5239 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5240 5241 SDValue Data(Result, 0); 5242 SDValue TexFail; 5243 5244 if (IsTexFail) { 5245 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5246 if (MaskPopVT.isVector()) { 5247 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5248 SDValue(Result, 0), ZeroIdx); 5249 } else { 5250 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5251 SDValue(Result, 0), ZeroIdx); 5252 } 5253 5254 TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 5255 SDValue(Result, 0), 5256 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5257 } 5258 5259 if (DataDwordVT.isVector()) 5260 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5261 NumDataDwords - MaskPopDwords); 5262 5263 if (IsD16) 5264 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5265 5266 if (!ReqRetVT.isVector()) 5267 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5268 5269 Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data); 5270 5271 if (TexFail) 5272 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5273 5274 if (Result->getNumValues() == 1) 5275 return Data; 5276 5277 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5278 } 5279 5280 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5281 SDValue *LWE, bool &IsTexFail) { 5282 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5283 5284 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5285 if (Value) { 5286 IsTexFail = true; 5287 } 5288 5289 SDLoc DL(TexFailCtrlConst); 5290 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5291 Value &= ~(uint64_t)0x1; 5292 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5293 Value &= ~(uint64_t)0x2; 5294 5295 return Value == 0; 5296 } 5297 5298 SDValue SITargetLowering::lowerImage(SDValue Op, 5299 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5300 SelectionDAG &DAG) const { 5301 SDLoc DL(Op); 5302 MachineFunction &MF = DAG.getMachineFunction(); 5303 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5304 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5305 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5306 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5307 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5308 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5309 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5310 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5311 unsigned IntrOpcode = Intr->BaseOpcode; 5312 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5313 5314 SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end()); 5315 SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end()); 5316 bool IsD16 = false; 5317 bool IsA16 = false; 5318 SDValue VData; 5319 int NumVDataDwords; 5320 bool AdjustRetType = false; 5321 5322 unsigned AddrIdx; // Index of first address argument 5323 unsigned DMask; 5324 unsigned DMaskLanes = 0; 5325 5326 if (BaseOpcode->Atomic) { 5327 VData = Op.getOperand(2); 5328 5329 bool Is64Bit = VData.getValueType() == MVT::i64; 5330 if (BaseOpcode->AtomicX2) { 5331 SDValue VData2 = Op.getOperand(3); 5332 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5333 {VData, VData2}); 5334 if (Is64Bit) 5335 VData = DAG.getBitcast(MVT::v4i32, VData); 5336 5337 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5338 DMask = Is64Bit ? 0xf : 0x3; 5339 NumVDataDwords = Is64Bit ? 4 : 2; 5340 AddrIdx = 4; 5341 } else { 5342 DMask = Is64Bit ? 0x3 : 0x1; 5343 NumVDataDwords = Is64Bit ? 2 : 1; 5344 AddrIdx = 3; 5345 } 5346 } else { 5347 unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1; 5348 auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx)); 5349 DMask = DMaskConst->getZExtValue(); 5350 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5351 5352 if (BaseOpcode->Store) { 5353 VData = Op.getOperand(2); 5354 5355 MVT StoreVT = VData.getSimpleValueType(); 5356 if (StoreVT.getScalarType() == MVT::f16) { 5357 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5358 return Op; // D16 is unsupported for this instruction 5359 5360 IsD16 = true; 5361 VData = handleD16VData(VData, DAG); 5362 } 5363 5364 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5365 } else { 5366 // Work out the num dwords based on the dmask popcount and underlying type 5367 // and whether packing is supported. 5368 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5369 if (LoadVT.getScalarType() == MVT::f16) { 5370 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5371 return Op; // D16 is unsupported for this instruction 5372 5373 IsD16 = true; 5374 } 5375 5376 // Confirm that the return type is large enough for the dmask specified 5377 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5378 (!LoadVT.isVector() && DMaskLanes > 1)) 5379 return Op; 5380 5381 if (IsD16 && !Subtarget->hasUnpackedD16VMem()) 5382 NumVDataDwords = (DMaskLanes + 1) / 2; 5383 else 5384 NumVDataDwords = DMaskLanes; 5385 5386 AdjustRetType = true; 5387 } 5388 5389 AddrIdx = DMaskIdx + 1; 5390 } 5391 5392 unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0; 5393 unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0; 5394 unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0; 5395 unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients + 5396 NumCoords + NumLCM; 5397 unsigned NumMIVAddrs = NumVAddrs; 5398 5399 SmallVector<SDValue, 4> VAddrs; 5400 5401 // Optimize _L to _LZ when _L is zero 5402 if (LZMappingInfo) { 5403 if (auto ConstantLod = 5404 dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5405 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 5406 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 5407 NumMIVAddrs--; // remove 'lod' 5408 } 5409 } 5410 } 5411 5412 // Optimize _mip away, when 'lod' is zero 5413 if (MIPMappingInfo) { 5414 if (auto ConstantLod = 5415 dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) { 5416 if (ConstantLod->isNullValue()) { 5417 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 5418 NumMIVAddrs--; // remove 'lod' 5419 } 5420 } 5421 } 5422 5423 // Check for 16 bit addresses and pack if true. 5424 unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs; 5425 MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType(); 5426 const MVT VAddrScalarVT = VAddrVT.getScalarType(); 5427 if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) { 5428 // Illegal to use a16 images 5429 if (!ST->hasFeature(AMDGPU::FeatureR128A16)) 5430 return Op; 5431 5432 IsA16 = true; 5433 const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 5434 for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) { 5435 SDValue AddrLo, AddrHi; 5436 // Push back extra arguments. 5437 if (i < DimIdx) { 5438 AddrLo = Op.getOperand(i); 5439 } else { 5440 AddrLo = Op.getOperand(i); 5441 // Dz/dh, dz/dv and the last odd coord are packed with undef. Also, 5442 // in 1D, derivatives dx/dh and dx/dv are packed with undef. 5443 if (((i + 1) >= (AddrIdx + NumMIVAddrs)) || 5444 ((NumGradients / 2) % 2 == 1 && 5445 (i == DimIdx + (NumGradients / 2) - 1 || 5446 i == DimIdx + NumGradients - 1))) { 5447 AddrHi = DAG.getUNDEF(MVT::f16); 5448 } else { 5449 AddrHi = Op.getOperand(i + 1); 5450 i++; 5451 } 5452 AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT, 5453 {AddrLo, AddrHi}); 5454 AddrLo = DAG.getBitcast(MVT::i32, AddrLo); 5455 } 5456 VAddrs.push_back(AddrLo); 5457 } 5458 } else { 5459 for (unsigned i = 0; i < NumMIVAddrs; ++i) 5460 VAddrs.push_back(Op.getOperand(AddrIdx + i)); 5461 } 5462 5463 // If the register allocator cannot place the address registers contiguously 5464 // without introducing moves, then using the non-sequential address encoding 5465 // is always preferable, since it saves VALU instructions and is usually a 5466 // wash in terms of code size or even better. 5467 // 5468 // However, we currently have no way of hinting to the register allocator that 5469 // MIMG addresses should be placed contiguously when it is possible to do so, 5470 // so force non-NSA for the common 2-address case as a heuristic. 5471 // 5472 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 5473 // allocation when possible. 5474 bool UseNSA = 5475 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 5476 SDValue VAddr; 5477 if (!UseNSA) 5478 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 5479 5480 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 5481 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 5482 unsigned CtrlIdx; // Index of texfailctrl argument 5483 SDValue Unorm; 5484 if (!BaseOpcode->Sampler) { 5485 Unorm = True; 5486 CtrlIdx = AddrIdx + NumVAddrs + 1; 5487 } else { 5488 auto UnormConst = 5489 cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2)); 5490 5491 Unorm = UnormConst->getZExtValue() ? True : False; 5492 CtrlIdx = AddrIdx + NumVAddrs + 3; 5493 } 5494 5495 SDValue TFE; 5496 SDValue LWE; 5497 SDValue TexFail = Op.getOperand(CtrlIdx); 5498 bool IsTexFail = false; 5499 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 5500 return Op; 5501 5502 if (IsTexFail) { 5503 if (!DMaskLanes) { 5504 // Expecting to get an error flag since TFC is on - and dmask is 0 5505 // Force dmask to be at least 1 otherwise the instruction will fail 5506 DMask = 0x1; 5507 DMaskLanes = 1; 5508 NumVDataDwords = 1; 5509 } 5510 NumVDataDwords += 1; 5511 AdjustRetType = true; 5512 } 5513 5514 // Has something earlier tagged that the return type needs adjusting 5515 // This happens if the instruction is a load or has set TexFailCtrl flags 5516 if (AdjustRetType) { 5517 // NumVDataDwords reflects the true number of dwords required in the return type 5518 if (DMaskLanes == 0 && !BaseOpcode->Store) { 5519 // This is a no-op load. This can be eliminated 5520 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 5521 if (isa<MemSDNode>(Op)) 5522 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 5523 return Undef; 5524 } 5525 5526 EVT NewVT = NumVDataDwords > 1 ? 5527 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 5528 : MVT::i32; 5529 5530 ResultTypes[0] = NewVT; 5531 if (ResultTypes.size() == 3) { 5532 // Original result was aggregate type used for TexFailCtrl results 5533 // The actual instruction returns as a vector type which has now been 5534 // created. Remove the aggregate result. 5535 ResultTypes.erase(&ResultTypes[1]); 5536 } 5537 } 5538 5539 SDValue GLC; 5540 SDValue SLC; 5541 SDValue DLC; 5542 if (BaseOpcode->Atomic) { 5543 GLC = True; // TODO no-return optimization 5544 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC, 5545 IsGFX10 ? &DLC : nullptr)) 5546 return Op; 5547 } else { 5548 if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC, 5549 IsGFX10 ? &DLC : nullptr)) 5550 return Op; 5551 } 5552 5553 SmallVector<SDValue, 26> Ops; 5554 if (BaseOpcode->Store || BaseOpcode->Atomic) 5555 Ops.push_back(VData); // vdata 5556 if (UseNSA) { 5557 for (const SDValue &Addr : VAddrs) 5558 Ops.push_back(Addr); 5559 } else { 5560 Ops.push_back(VAddr); 5561 } 5562 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc 5563 if (BaseOpcode->Sampler) 5564 Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler 5565 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 5566 if (IsGFX10) 5567 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 5568 Ops.push_back(Unorm); 5569 if (IsGFX10) 5570 Ops.push_back(DLC); 5571 Ops.push_back(GLC); 5572 Ops.push_back(SLC); 5573 Ops.push_back(IsA16 && // a16 or r128 5574 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 5575 Ops.push_back(TFE); // tfe 5576 Ops.push_back(LWE); // lwe 5577 if (!IsGFX10) 5578 Ops.push_back(DimInfo->DA ? True : False); 5579 if (BaseOpcode->HasD16) 5580 Ops.push_back(IsD16 ? True : False); 5581 if (isa<MemSDNode>(Op)) 5582 Ops.push_back(Op.getOperand(0)); // chain 5583 5584 int NumVAddrDwords = 5585 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 5586 int Opcode = -1; 5587 5588 if (IsGFX10) { 5589 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 5590 UseNSA ? AMDGPU::MIMGEncGfx10NSA 5591 : AMDGPU::MIMGEncGfx10Default, 5592 NumVDataDwords, NumVAddrDwords); 5593 } else { 5594 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5595 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 5596 NumVDataDwords, NumVAddrDwords); 5597 if (Opcode == -1) 5598 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 5599 NumVDataDwords, NumVAddrDwords); 5600 } 5601 assert(Opcode != -1); 5602 5603 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 5604 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 5605 MachineMemOperand *MemRef = MemOp->getMemOperand(); 5606 DAG.setNodeMemRefs(NewNode, {MemRef}); 5607 } 5608 5609 if (BaseOpcode->AtomicX2) { 5610 SmallVector<SDValue, 1> Elt; 5611 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 5612 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 5613 } else if (!BaseOpcode->Store) { 5614 return constructRetValue(DAG, NewNode, 5615 OrigResultTypes, IsTexFail, 5616 Subtarget->hasUnpackedD16VMem(), IsD16, 5617 DMaskLanes, NumVDataDwords, DL, 5618 *DAG.getContext()); 5619 } 5620 5621 return SDValue(NewNode, 0); 5622 } 5623 5624 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 5625 SDValue Offset, SDValue CachePolicy, 5626 SelectionDAG &DAG) const { 5627 MachineFunction &MF = DAG.getMachineFunction(); 5628 5629 const DataLayout &DataLayout = DAG.getDataLayout(); 5630 unsigned Align = 5631 DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext())); 5632 5633 MachineMemOperand *MMO = MF.getMachineMemOperand( 5634 MachinePointerInfo(), 5635 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 5636 MachineMemOperand::MOInvariant, 5637 VT.getStoreSize(), Align); 5638 5639 if (!Offset->isDivergent()) { 5640 SDValue Ops[] = { 5641 Rsrc, 5642 Offset, // Offset 5643 CachePolicy 5644 }; 5645 5646 // Widen vec3 load to vec4. 5647 if (VT.isVector() && VT.getVectorNumElements() == 3) { 5648 EVT WidenedVT = 5649 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 5650 auto WidenedOp = DAG.getMemIntrinsicNode( 5651 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 5652 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 5653 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 5654 DAG.getVectorIdxConstant(0, DL)); 5655 return Subvector; 5656 } 5657 5658 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 5659 DAG.getVTList(VT), Ops, VT, MMO); 5660 } 5661 5662 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 5663 // assume that the buffer is unswizzled. 5664 SmallVector<SDValue, 4> Loads; 5665 unsigned NumLoads = 1; 5666 MVT LoadVT = VT.getSimpleVT(); 5667 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 5668 assert((LoadVT.getScalarType() == MVT::i32 || 5669 LoadVT.getScalarType() == MVT::f32)); 5670 5671 if (NumElts == 8 || NumElts == 16) { 5672 NumLoads = NumElts / 4; 5673 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 5674 } 5675 5676 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 5677 SDValue Ops[] = { 5678 DAG.getEntryNode(), // Chain 5679 Rsrc, // rsrc 5680 DAG.getConstant(0, DL, MVT::i32), // vindex 5681 {}, // voffset 5682 {}, // soffset 5683 {}, // offset 5684 CachePolicy, // cachepolicy 5685 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 5686 }; 5687 5688 // Use the alignment to ensure that the required offsets will fit into the 5689 // immediate offsets. 5690 setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4); 5691 5692 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 5693 for (unsigned i = 0; i < NumLoads; ++i) { 5694 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 5695 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 5696 LoadVT, MMO, DAG)); 5697 } 5698 5699 if (NumElts == 8 || NumElts == 16) 5700 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 5701 5702 return Loads[0]; 5703 } 5704 5705 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 5706 SelectionDAG &DAG) const { 5707 MachineFunction &MF = DAG.getMachineFunction(); 5708 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 5709 5710 EVT VT = Op.getValueType(); 5711 SDLoc DL(Op); 5712 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5713 5714 // TODO: Should this propagate fast-math-flags? 5715 5716 switch (IntrinsicID) { 5717 case Intrinsic::amdgcn_implicit_buffer_ptr: { 5718 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 5719 return emitNonHSAIntrinsicError(DAG, DL, VT); 5720 return getPreloadedValue(DAG, *MFI, VT, 5721 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 5722 } 5723 case Intrinsic::amdgcn_dispatch_ptr: 5724 case Intrinsic::amdgcn_queue_ptr: { 5725 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 5726 DiagnosticInfoUnsupported BadIntrin( 5727 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 5728 DL.getDebugLoc()); 5729 DAG.getContext()->diagnose(BadIntrin); 5730 return DAG.getUNDEF(VT); 5731 } 5732 5733 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 5734 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 5735 return getPreloadedValue(DAG, *MFI, VT, RegID); 5736 } 5737 case Intrinsic::amdgcn_implicitarg_ptr: { 5738 if (MFI->isEntryFunction()) 5739 return getImplicitArgPtr(DAG, DL); 5740 return getPreloadedValue(DAG, *MFI, VT, 5741 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 5742 } 5743 case Intrinsic::amdgcn_kernarg_segment_ptr: { 5744 return getPreloadedValue(DAG, *MFI, VT, 5745 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 5746 } 5747 case Intrinsic::amdgcn_dispatch_id: { 5748 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 5749 } 5750 case Intrinsic::amdgcn_rcp: 5751 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 5752 case Intrinsic::amdgcn_rsq: 5753 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5754 case Intrinsic::amdgcn_rsq_legacy: 5755 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5756 return emitRemovedIntrinsicError(DAG, DL, VT); 5757 5758 return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1)); 5759 case Intrinsic::amdgcn_rcp_legacy: 5760 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 5761 return emitRemovedIntrinsicError(DAG, DL, VT); 5762 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 5763 case Intrinsic::amdgcn_rsq_clamp: { 5764 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5765 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 5766 5767 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 5768 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 5769 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 5770 5771 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 5772 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 5773 DAG.getConstantFP(Max, DL, VT)); 5774 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 5775 DAG.getConstantFP(Min, DL, VT)); 5776 } 5777 case Intrinsic::r600_read_ngroups_x: 5778 if (Subtarget->isAmdHsaOS()) 5779 return emitNonHSAIntrinsicError(DAG, DL, VT); 5780 5781 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5782 SI::KernelInputOffsets::NGROUPS_X, 4, false); 5783 case Intrinsic::r600_read_ngroups_y: 5784 if (Subtarget->isAmdHsaOS()) 5785 return emitNonHSAIntrinsicError(DAG, DL, VT); 5786 5787 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5788 SI::KernelInputOffsets::NGROUPS_Y, 4, false); 5789 case Intrinsic::r600_read_ngroups_z: 5790 if (Subtarget->isAmdHsaOS()) 5791 return emitNonHSAIntrinsicError(DAG, DL, VT); 5792 5793 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5794 SI::KernelInputOffsets::NGROUPS_Z, 4, false); 5795 case Intrinsic::r600_read_global_size_x: 5796 if (Subtarget->isAmdHsaOS()) 5797 return emitNonHSAIntrinsicError(DAG, DL, VT); 5798 5799 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5800 SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false); 5801 case Intrinsic::r600_read_global_size_y: 5802 if (Subtarget->isAmdHsaOS()) 5803 return emitNonHSAIntrinsicError(DAG, DL, VT); 5804 5805 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5806 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false); 5807 case Intrinsic::r600_read_global_size_z: 5808 if (Subtarget->isAmdHsaOS()) 5809 return emitNonHSAIntrinsicError(DAG, DL, VT); 5810 5811 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 5812 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false); 5813 case Intrinsic::r600_read_local_size_x: 5814 if (Subtarget->isAmdHsaOS()) 5815 return emitNonHSAIntrinsicError(DAG, DL, VT); 5816 5817 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5818 SI::KernelInputOffsets::LOCAL_SIZE_X); 5819 case Intrinsic::r600_read_local_size_y: 5820 if (Subtarget->isAmdHsaOS()) 5821 return emitNonHSAIntrinsicError(DAG, DL, VT); 5822 5823 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5824 SI::KernelInputOffsets::LOCAL_SIZE_Y); 5825 case Intrinsic::r600_read_local_size_z: 5826 if (Subtarget->isAmdHsaOS()) 5827 return emitNonHSAIntrinsicError(DAG, DL, VT); 5828 5829 return lowerImplicitZextParam(DAG, Op, MVT::i16, 5830 SI::KernelInputOffsets::LOCAL_SIZE_Z); 5831 case Intrinsic::amdgcn_workgroup_id_x: 5832 case Intrinsic::r600_read_tgid_x: 5833 return getPreloadedValue(DAG, *MFI, VT, 5834 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 5835 case Intrinsic::amdgcn_workgroup_id_y: 5836 case Intrinsic::r600_read_tgid_y: 5837 return getPreloadedValue(DAG, *MFI, VT, 5838 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 5839 case Intrinsic::amdgcn_workgroup_id_z: 5840 case Intrinsic::r600_read_tgid_z: 5841 return getPreloadedValue(DAG, *MFI, VT, 5842 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 5843 case Intrinsic::amdgcn_workitem_id_x: 5844 case Intrinsic::r600_read_tidig_x: 5845 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5846 SDLoc(DAG.getEntryNode()), 5847 MFI->getArgInfo().WorkItemIDX); 5848 case Intrinsic::amdgcn_workitem_id_y: 5849 case Intrinsic::r600_read_tidig_y: 5850 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5851 SDLoc(DAG.getEntryNode()), 5852 MFI->getArgInfo().WorkItemIDY); 5853 case Intrinsic::amdgcn_workitem_id_z: 5854 case Intrinsic::r600_read_tidig_z: 5855 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 5856 SDLoc(DAG.getEntryNode()), 5857 MFI->getArgInfo().WorkItemIDZ); 5858 case Intrinsic::amdgcn_wavefrontsize: 5859 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 5860 SDLoc(Op), MVT::i32); 5861 case Intrinsic::amdgcn_s_buffer_load: { 5862 bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10; 5863 SDValue GLC; 5864 SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1); 5865 if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr, 5866 IsGFX10 ? &DLC : nullptr)) 5867 return Op; 5868 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5869 DAG); 5870 } 5871 case Intrinsic::amdgcn_fdiv_fast: 5872 return lowerFDIV_FAST(Op, DAG); 5873 case Intrinsic::amdgcn_sin: 5874 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 5875 5876 case Intrinsic::amdgcn_cos: 5877 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 5878 5879 case Intrinsic::amdgcn_mul_u24: 5880 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5881 case Intrinsic::amdgcn_mul_i24: 5882 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5883 5884 case Intrinsic::amdgcn_log_clamp: { 5885 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 5886 return SDValue(); 5887 5888 DiagnosticInfoUnsupported BadIntrin( 5889 MF.getFunction(), "intrinsic not supported on subtarget", 5890 DL.getDebugLoc()); 5891 DAG.getContext()->diagnose(BadIntrin); 5892 return DAG.getUNDEF(VT); 5893 } 5894 case Intrinsic::amdgcn_ldexp: 5895 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 5896 Op.getOperand(1), Op.getOperand(2)); 5897 5898 case Intrinsic::amdgcn_fract: 5899 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 5900 5901 case Intrinsic::amdgcn_class: 5902 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 5903 Op.getOperand(1), Op.getOperand(2)); 5904 case Intrinsic::amdgcn_div_fmas: 5905 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 5906 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5907 Op.getOperand(4)); 5908 5909 case Intrinsic::amdgcn_div_fixup: 5910 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 5911 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5912 5913 case Intrinsic::amdgcn_trig_preop: 5914 return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT, 5915 Op.getOperand(1), Op.getOperand(2)); 5916 case Intrinsic::amdgcn_div_scale: { 5917 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 5918 5919 // Translate to the operands expected by the machine instruction. The 5920 // first parameter must be the same as the first instruction. 5921 SDValue Numerator = Op.getOperand(1); 5922 SDValue Denominator = Op.getOperand(2); 5923 5924 // Note this order is opposite of the machine instruction's operations, 5925 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 5926 // intrinsic has the numerator as the first operand to match a normal 5927 // division operation. 5928 5929 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 5930 5931 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 5932 Denominator, Numerator); 5933 } 5934 case Intrinsic::amdgcn_icmp: { 5935 // There is a Pat that handles this variant, so return it as-is. 5936 if (Op.getOperand(1).getValueType() == MVT::i1 && 5937 Op.getConstantOperandVal(2) == 0 && 5938 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 5939 return Op; 5940 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 5941 } 5942 case Intrinsic::amdgcn_fcmp: { 5943 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 5944 } 5945 case Intrinsic::amdgcn_fmed3: 5946 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 5947 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5948 case Intrinsic::amdgcn_fdot2: 5949 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 5950 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 5951 Op.getOperand(4)); 5952 case Intrinsic::amdgcn_fmul_legacy: 5953 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 5954 Op.getOperand(1), Op.getOperand(2)); 5955 case Intrinsic::amdgcn_sffbh: 5956 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 5957 case Intrinsic::amdgcn_sbfe: 5958 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 5959 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5960 case Intrinsic::amdgcn_ubfe: 5961 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 5962 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 5963 case Intrinsic::amdgcn_cvt_pkrtz: 5964 case Intrinsic::amdgcn_cvt_pknorm_i16: 5965 case Intrinsic::amdgcn_cvt_pknorm_u16: 5966 case Intrinsic::amdgcn_cvt_pk_i16: 5967 case Intrinsic::amdgcn_cvt_pk_u16: { 5968 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 5969 EVT VT = Op.getValueType(); 5970 unsigned Opcode; 5971 5972 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 5973 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 5974 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 5975 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 5976 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 5977 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 5978 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 5979 Opcode = AMDGPUISD::CVT_PK_I16_I32; 5980 else 5981 Opcode = AMDGPUISD::CVT_PK_U16_U32; 5982 5983 if (isTypeLegal(VT)) 5984 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 5985 5986 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 5987 Op.getOperand(1), Op.getOperand(2)); 5988 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 5989 } 5990 case Intrinsic::amdgcn_fmad_ftz: 5991 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 5992 Op.getOperand(2), Op.getOperand(3)); 5993 5994 case Intrinsic::amdgcn_if_break: 5995 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 5996 Op->getOperand(1), Op->getOperand(2)), 0); 5997 5998 case Intrinsic::amdgcn_groupstaticsize: { 5999 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6000 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6001 return Op; 6002 6003 const Module *M = MF.getFunction().getParent(); 6004 const GlobalValue *GV = 6005 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6006 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6007 SIInstrInfo::MO_ABS32_LO); 6008 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6009 } 6010 case Intrinsic::amdgcn_is_shared: 6011 case Intrinsic::amdgcn_is_private: { 6012 SDLoc SL(Op); 6013 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6014 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6015 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6016 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6017 Op.getOperand(1)); 6018 6019 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6020 DAG.getConstant(1, SL, MVT::i32)); 6021 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6022 } 6023 default: 6024 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6025 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6026 return lowerImage(Op, ImageDimIntr, DAG); 6027 6028 return Op; 6029 } 6030 } 6031 6032 // This function computes an appropriate offset to pass to 6033 // MachineMemOperand::setOffset() based on the offset inputs to 6034 // an intrinsic. If any of the offsets are non-contstant or 6035 // if VIndex is non-zero then this function returns 0. Otherwise, 6036 // it returns the sum of VOffset, SOffset, and Offset. 6037 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6038 SDValue SOffset, 6039 SDValue Offset, 6040 SDValue VIndex = SDValue()) { 6041 6042 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6043 !isa<ConstantSDNode>(Offset)) 6044 return 0; 6045 6046 if (VIndex) { 6047 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6048 return 0; 6049 } 6050 6051 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6052 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6053 cast<ConstantSDNode>(Offset)->getSExtValue(); 6054 } 6055 6056 static unsigned getDSShaderTypeValue(const MachineFunction &MF) { 6057 switch (MF.getFunction().getCallingConv()) { 6058 case CallingConv::AMDGPU_PS: 6059 return 1; 6060 case CallingConv::AMDGPU_VS: 6061 return 2; 6062 case CallingConv::AMDGPU_GS: 6063 return 3; 6064 case CallingConv::AMDGPU_HS: 6065 case CallingConv::AMDGPU_LS: 6066 case CallingConv::AMDGPU_ES: 6067 report_fatal_error("ds_ordered_count unsupported for this calling conv"); 6068 case CallingConv::AMDGPU_CS: 6069 case CallingConv::AMDGPU_KERNEL: 6070 case CallingConv::C: 6071 case CallingConv::Fast: 6072 default: 6073 // Assume other calling conventions are various compute callable functions 6074 return 0; 6075 } 6076 } 6077 6078 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6079 SelectionDAG &DAG) const { 6080 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6081 SDLoc DL(Op); 6082 6083 switch (IntrID) { 6084 case Intrinsic::amdgcn_ds_ordered_add: 6085 case Intrinsic::amdgcn_ds_ordered_swap: { 6086 MemSDNode *M = cast<MemSDNode>(Op); 6087 SDValue Chain = M->getOperand(0); 6088 SDValue M0 = M->getOperand(2); 6089 SDValue Value = M->getOperand(3); 6090 unsigned IndexOperand = M->getConstantOperandVal(7); 6091 unsigned WaveRelease = M->getConstantOperandVal(8); 6092 unsigned WaveDone = M->getConstantOperandVal(9); 6093 6094 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6095 IndexOperand &= ~0x3f; 6096 unsigned CountDw = 0; 6097 6098 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6099 CountDw = (IndexOperand >> 24) & 0xf; 6100 IndexOperand &= ~(0xf << 24); 6101 6102 if (CountDw < 1 || CountDw > 4) { 6103 report_fatal_error( 6104 "ds_ordered_count: dword count must be between 1 and 4"); 6105 } 6106 } 6107 6108 if (IndexOperand) 6109 report_fatal_error("ds_ordered_count: bad index operand"); 6110 6111 if (WaveDone && !WaveRelease) 6112 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6113 6114 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6115 unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction()); 6116 unsigned Offset0 = OrderedCountIndex << 2; 6117 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6118 (Instruction << 4); 6119 6120 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6121 Offset1 |= (CountDw - 1) << 6; 6122 6123 unsigned Offset = Offset0 | (Offset1 << 8); 6124 6125 SDValue Ops[] = { 6126 Chain, 6127 Value, 6128 DAG.getTargetConstant(Offset, DL, MVT::i16), 6129 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6130 }; 6131 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6132 M->getVTList(), Ops, M->getMemoryVT(), 6133 M->getMemOperand()); 6134 } 6135 case Intrinsic::amdgcn_ds_fadd: { 6136 MemSDNode *M = cast<MemSDNode>(Op); 6137 unsigned Opc; 6138 switch (IntrID) { 6139 case Intrinsic::amdgcn_ds_fadd: 6140 Opc = ISD::ATOMIC_LOAD_FADD; 6141 break; 6142 } 6143 6144 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6145 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6146 M->getMemOperand()); 6147 } 6148 case Intrinsic::amdgcn_atomic_inc: 6149 case Intrinsic::amdgcn_atomic_dec: 6150 case Intrinsic::amdgcn_ds_fmin: 6151 case Intrinsic::amdgcn_ds_fmax: { 6152 MemSDNode *M = cast<MemSDNode>(Op); 6153 unsigned Opc; 6154 switch (IntrID) { 6155 case Intrinsic::amdgcn_atomic_inc: 6156 Opc = AMDGPUISD::ATOMIC_INC; 6157 break; 6158 case Intrinsic::amdgcn_atomic_dec: 6159 Opc = AMDGPUISD::ATOMIC_DEC; 6160 break; 6161 case Intrinsic::amdgcn_ds_fmin: 6162 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6163 break; 6164 case Intrinsic::amdgcn_ds_fmax: 6165 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6166 break; 6167 default: 6168 llvm_unreachable("Unknown intrinsic!"); 6169 } 6170 SDValue Ops[] = { 6171 M->getOperand(0), // Chain 6172 M->getOperand(2), // Ptr 6173 M->getOperand(3) // Value 6174 }; 6175 6176 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6177 M->getMemoryVT(), M->getMemOperand()); 6178 } 6179 case Intrinsic::amdgcn_buffer_load: 6180 case Intrinsic::amdgcn_buffer_load_format: { 6181 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6182 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6183 unsigned IdxEn = 1; 6184 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6185 IdxEn = Idx->getZExtValue() != 0; 6186 SDValue Ops[] = { 6187 Op.getOperand(0), // Chain 6188 Op.getOperand(2), // rsrc 6189 Op.getOperand(3), // vindex 6190 SDValue(), // voffset -- will be set by setBufferOffsets 6191 SDValue(), // soffset -- will be set by setBufferOffsets 6192 SDValue(), // offset -- will be set by setBufferOffsets 6193 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6194 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6195 }; 6196 6197 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6198 // We don't know the offset if vindex is non-zero, so clear it. 6199 if (IdxEn) 6200 Offset = 0; 6201 6202 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6203 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6204 6205 EVT VT = Op.getValueType(); 6206 EVT IntVT = VT.changeTypeToInteger(); 6207 auto *M = cast<MemSDNode>(Op); 6208 M->getMemOperand()->setOffset(Offset); 6209 EVT LoadVT = Op.getValueType(); 6210 6211 if (LoadVT.getScalarType() == MVT::f16) 6212 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6213 M, DAG, Ops); 6214 6215 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6216 if (LoadVT.getScalarType() == MVT::i8 || 6217 LoadVT.getScalarType() == MVT::i16) 6218 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6219 6220 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6221 M->getMemOperand(), DAG); 6222 } 6223 case Intrinsic::amdgcn_raw_buffer_load: 6224 case Intrinsic::amdgcn_raw_buffer_load_format: { 6225 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6226 6227 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6228 SDValue Ops[] = { 6229 Op.getOperand(0), // Chain 6230 Op.getOperand(2), // rsrc 6231 DAG.getConstant(0, DL, MVT::i32), // vindex 6232 Offsets.first, // voffset 6233 Op.getOperand(4), // soffset 6234 Offsets.second, // offset 6235 Op.getOperand(5), // cachepolicy, swizzled buffer 6236 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6237 }; 6238 6239 auto *M = cast<MemSDNode>(Op); 6240 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6241 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6242 } 6243 case Intrinsic::amdgcn_struct_buffer_load: 6244 case Intrinsic::amdgcn_struct_buffer_load_format: { 6245 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6246 6247 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6248 SDValue Ops[] = { 6249 Op.getOperand(0), // Chain 6250 Op.getOperand(2), // rsrc 6251 Op.getOperand(3), // vindex 6252 Offsets.first, // voffset 6253 Op.getOperand(5), // soffset 6254 Offsets.second, // offset 6255 Op.getOperand(6), // cachepolicy, swizzled buffer 6256 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6257 }; 6258 6259 auto *M = cast<MemSDNode>(Op); 6260 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6261 Ops[2])); 6262 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6263 } 6264 case Intrinsic::amdgcn_tbuffer_load: { 6265 MemSDNode *M = cast<MemSDNode>(Op); 6266 EVT LoadVT = Op.getValueType(); 6267 6268 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6269 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6270 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6271 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6272 unsigned IdxEn = 1; 6273 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6274 IdxEn = Idx->getZExtValue() != 0; 6275 SDValue Ops[] = { 6276 Op.getOperand(0), // Chain 6277 Op.getOperand(2), // rsrc 6278 Op.getOperand(3), // vindex 6279 Op.getOperand(4), // voffset 6280 Op.getOperand(5), // soffset 6281 Op.getOperand(6), // offset 6282 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6283 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6284 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6285 }; 6286 6287 if (LoadVT.getScalarType() == MVT::f16) 6288 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6289 M, DAG, Ops); 6290 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6291 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6292 DAG); 6293 } 6294 case Intrinsic::amdgcn_raw_tbuffer_load: { 6295 MemSDNode *M = cast<MemSDNode>(Op); 6296 EVT LoadVT = Op.getValueType(); 6297 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6298 6299 SDValue Ops[] = { 6300 Op.getOperand(0), // Chain 6301 Op.getOperand(2), // rsrc 6302 DAG.getConstant(0, DL, MVT::i32), // vindex 6303 Offsets.first, // voffset 6304 Op.getOperand(4), // soffset 6305 Offsets.second, // offset 6306 Op.getOperand(5), // format 6307 Op.getOperand(6), // cachepolicy, swizzled buffer 6308 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6309 }; 6310 6311 if (LoadVT.getScalarType() == MVT::f16) 6312 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6313 M, DAG, Ops); 6314 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6315 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6316 DAG); 6317 } 6318 case Intrinsic::amdgcn_struct_tbuffer_load: { 6319 MemSDNode *M = cast<MemSDNode>(Op); 6320 EVT LoadVT = Op.getValueType(); 6321 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6322 6323 SDValue Ops[] = { 6324 Op.getOperand(0), // Chain 6325 Op.getOperand(2), // rsrc 6326 Op.getOperand(3), // vindex 6327 Offsets.first, // voffset 6328 Op.getOperand(5), // soffset 6329 Offsets.second, // offset 6330 Op.getOperand(6), // format 6331 Op.getOperand(7), // cachepolicy, swizzled buffer 6332 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6333 }; 6334 6335 if (LoadVT.getScalarType() == MVT::f16) 6336 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6337 M, DAG, Ops); 6338 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6339 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6340 DAG); 6341 } 6342 case Intrinsic::amdgcn_buffer_atomic_swap: 6343 case Intrinsic::amdgcn_buffer_atomic_add: 6344 case Intrinsic::amdgcn_buffer_atomic_sub: 6345 case Intrinsic::amdgcn_buffer_atomic_smin: 6346 case Intrinsic::amdgcn_buffer_atomic_umin: 6347 case Intrinsic::amdgcn_buffer_atomic_smax: 6348 case Intrinsic::amdgcn_buffer_atomic_umax: 6349 case Intrinsic::amdgcn_buffer_atomic_and: 6350 case Intrinsic::amdgcn_buffer_atomic_or: 6351 case Intrinsic::amdgcn_buffer_atomic_xor: { 6352 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6353 unsigned IdxEn = 1; 6354 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6355 IdxEn = Idx->getZExtValue() != 0; 6356 SDValue Ops[] = { 6357 Op.getOperand(0), // Chain 6358 Op.getOperand(2), // vdata 6359 Op.getOperand(3), // rsrc 6360 Op.getOperand(4), // vindex 6361 SDValue(), // voffset -- will be set by setBufferOffsets 6362 SDValue(), // soffset -- will be set by setBufferOffsets 6363 SDValue(), // offset -- will be set by setBufferOffsets 6364 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6365 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6366 }; 6367 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6368 // We don't know the offset if vindex is non-zero, so clear it. 6369 if (IdxEn) 6370 Offset = 0; 6371 EVT VT = Op.getValueType(); 6372 6373 auto *M = cast<MemSDNode>(Op); 6374 M->getMemOperand()->setOffset(Offset); 6375 unsigned Opcode = 0; 6376 6377 switch (IntrID) { 6378 case Intrinsic::amdgcn_buffer_atomic_swap: 6379 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6380 break; 6381 case Intrinsic::amdgcn_buffer_atomic_add: 6382 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6383 break; 6384 case Intrinsic::amdgcn_buffer_atomic_sub: 6385 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6386 break; 6387 case Intrinsic::amdgcn_buffer_atomic_smin: 6388 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6389 break; 6390 case Intrinsic::amdgcn_buffer_atomic_umin: 6391 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6392 break; 6393 case Intrinsic::amdgcn_buffer_atomic_smax: 6394 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6395 break; 6396 case Intrinsic::amdgcn_buffer_atomic_umax: 6397 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6398 break; 6399 case Intrinsic::amdgcn_buffer_atomic_and: 6400 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6401 break; 6402 case Intrinsic::amdgcn_buffer_atomic_or: 6403 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6404 break; 6405 case Intrinsic::amdgcn_buffer_atomic_xor: 6406 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6407 break; 6408 default: 6409 llvm_unreachable("unhandled atomic opcode"); 6410 } 6411 6412 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6413 M->getMemOperand()); 6414 } 6415 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6416 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6417 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6418 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6419 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6420 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6421 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6422 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6423 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6424 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6425 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6426 case Intrinsic::amdgcn_raw_buffer_atomic_dec: { 6427 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6428 SDValue Ops[] = { 6429 Op.getOperand(0), // Chain 6430 Op.getOperand(2), // vdata 6431 Op.getOperand(3), // rsrc 6432 DAG.getConstant(0, DL, MVT::i32), // vindex 6433 Offsets.first, // voffset 6434 Op.getOperand(5), // soffset 6435 Offsets.second, // offset 6436 Op.getOperand(6), // cachepolicy 6437 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6438 }; 6439 EVT VT = Op.getValueType(); 6440 6441 auto *M = cast<MemSDNode>(Op); 6442 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6443 unsigned Opcode = 0; 6444 6445 switch (IntrID) { 6446 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 6447 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6448 break; 6449 case Intrinsic::amdgcn_raw_buffer_atomic_add: 6450 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6451 break; 6452 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 6453 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6454 break; 6455 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 6456 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6457 break; 6458 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 6459 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6460 break; 6461 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 6462 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6463 break; 6464 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 6465 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6466 break; 6467 case Intrinsic::amdgcn_raw_buffer_atomic_and: 6468 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6469 break; 6470 case Intrinsic::amdgcn_raw_buffer_atomic_or: 6471 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6472 break; 6473 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 6474 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6475 break; 6476 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 6477 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6478 break; 6479 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 6480 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6481 break; 6482 default: 6483 llvm_unreachable("unhandled atomic opcode"); 6484 } 6485 6486 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6487 M->getMemOperand()); 6488 } 6489 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6490 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6491 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6492 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6493 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6494 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6495 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6496 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6497 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6498 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6499 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6500 case Intrinsic::amdgcn_struct_buffer_atomic_dec: { 6501 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6502 SDValue Ops[] = { 6503 Op.getOperand(0), // Chain 6504 Op.getOperand(2), // vdata 6505 Op.getOperand(3), // rsrc 6506 Op.getOperand(4), // vindex 6507 Offsets.first, // voffset 6508 Op.getOperand(6), // soffset 6509 Offsets.second, // offset 6510 Op.getOperand(7), // cachepolicy 6511 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6512 }; 6513 EVT VT = Op.getValueType(); 6514 6515 auto *M = cast<MemSDNode>(Op); 6516 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6517 Ops[3])); 6518 unsigned Opcode = 0; 6519 6520 switch (IntrID) { 6521 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 6522 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 6523 break; 6524 case Intrinsic::amdgcn_struct_buffer_atomic_add: 6525 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 6526 break; 6527 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 6528 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 6529 break; 6530 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 6531 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 6532 break; 6533 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 6534 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 6535 break; 6536 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 6537 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 6538 break; 6539 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 6540 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 6541 break; 6542 case Intrinsic::amdgcn_struct_buffer_atomic_and: 6543 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 6544 break; 6545 case Intrinsic::amdgcn_struct_buffer_atomic_or: 6546 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 6547 break; 6548 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 6549 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 6550 break; 6551 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 6552 Opcode = AMDGPUISD::BUFFER_ATOMIC_INC; 6553 break; 6554 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 6555 Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC; 6556 break; 6557 default: 6558 llvm_unreachable("unhandled atomic opcode"); 6559 } 6560 6561 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6562 M->getMemOperand()); 6563 } 6564 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 6565 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6566 unsigned IdxEn = 1; 6567 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 6568 IdxEn = Idx->getZExtValue() != 0; 6569 SDValue Ops[] = { 6570 Op.getOperand(0), // Chain 6571 Op.getOperand(2), // src 6572 Op.getOperand(3), // cmp 6573 Op.getOperand(4), // rsrc 6574 Op.getOperand(5), // vindex 6575 SDValue(), // voffset -- will be set by setBufferOffsets 6576 SDValue(), // soffset -- will be set by setBufferOffsets 6577 SDValue(), // offset -- will be set by setBufferOffsets 6578 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6579 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6580 }; 6581 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 6582 // We don't know the offset if vindex is non-zero, so clear it. 6583 if (IdxEn) 6584 Offset = 0; 6585 EVT VT = Op.getValueType(); 6586 auto *M = cast<MemSDNode>(Op); 6587 M->getMemOperand()->setOffset(Offset); 6588 6589 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6590 Op->getVTList(), Ops, VT, M->getMemOperand()); 6591 } 6592 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 6593 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6594 SDValue Ops[] = { 6595 Op.getOperand(0), // Chain 6596 Op.getOperand(2), // src 6597 Op.getOperand(3), // cmp 6598 Op.getOperand(4), // rsrc 6599 DAG.getConstant(0, DL, MVT::i32), // vindex 6600 Offsets.first, // voffset 6601 Op.getOperand(6), // soffset 6602 Offsets.second, // offset 6603 Op.getOperand(7), // cachepolicy 6604 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6605 }; 6606 EVT VT = Op.getValueType(); 6607 auto *M = cast<MemSDNode>(Op); 6608 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 6609 6610 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6611 Op->getVTList(), Ops, VT, M->getMemOperand()); 6612 } 6613 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 6614 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 6615 SDValue Ops[] = { 6616 Op.getOperand(0), // Chain 6617 Op.getOperand(2), // src 6618 Op.getOperand(3), // cmp 6619 Op.getOperand(4), // rsrc 6620 Op.getOperand(5), // vindex 6621 Offsets.first, // voffset 6622 Op.getOperand(7), // soffset 6623 Offsets.second, // offset 6624 Op.getOperand(8), // cachepolicy 6625 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6626 }; 6627 EVT VT = Op.getValueType(); 6628 auto *M = cast<MemSDNode>(Op); 6629 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 6630 Ops[4])); 6631 6632 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 6633 Op->getVTList(), Ops, VT, M->getMemOperand()); 6634 } 6635 6636 default: 6637 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6638 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 6639 return lowerImage(Op, ImageDimIntr, DAG); 6640 6641 return SDValue(); 6642 } 6643 } 6644 6645 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 6646 // dwordx4 if on SI. 6647 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 6648 SDVTList VTList, 6649 ArrayRef<SDValue> Ops, EVT MemVT, 6650 MachineMemOperand *MMO, 6651 SelectionDAG &DAG) const { 6652 EVT VT = VTList.VTs[0]; 6653 EVT WidenedVT = VT; 6654 EVT WidenedMemVT = MemVT; 6655 if (!Subtarget->hasDwordx3LoadStores() && 6656 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 6657 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 6658 WidenedVT.getVectorElementType(), 4); 6659 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 6660 WidenedMemVT.getVectorElementType(), 4); 6661 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 6662 } 6663 6664 assert(VTList.NumVTs == 2); 6665 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 6666 6667 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 6668 WidenedMemVT, MMO); 6669 if (WidenedVT != VT) { 6670 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 6671 DAG.getVectorIdxConstant(0, DL)); 6672 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 6673 } 6674 return NewOp; 6675 } 6676 6677 SDValue SITargetLowering::handleD16VData(SDValue VData, 6678 SelectionDAG &DAG) const { 6679 EVT StoreVT = VData.getValueType(); 6680 6681 // No change for f16 and legal vector D16 types. 6682 if (!StoreVT.isVector()) 6683 return VData; 6684 6685 SDLoc DL(VData); 6686 assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16"); 6687 6688 if (Subtarget->hasUnpackedD16VMem()) { 6689 // We need to unpack the packed data to store. 6690 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 6691 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 6692 6693 EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 6694 StoreVT.getVectorNumElements()); 6695 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 6696 return DAG.UnrollVectorOp(ZExt.getNode()); 6697 } 6698 6699 assert(isTypeLegal(StoreVT)); 6700 return VData; 6701 } 6702 6703 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 6704 SelectionDAG &DAG) const { 6705 SDLoc DL(Op); 6706 SDValue Chain = Op.getOperand(0); 6707 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6708 MachineFunction &MF = DAG.getMachineFunction(); 6709 6710 switch (IntrinsicID) { 6711 case Intrinsic::amdgcn_exp_compr: { 6712 SDValue Src0 = Op.getOperand(4); 6713 SDValue Src1 = Op.getOperand(5); 6714 // Hack around illegal type on SI by directly selecting it. 6715 if (isTypeLegal(Src0.getValueType())) 6716 return SDValue(); 6717 6718 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 6719 SDValue Undef = DAG.getUNDEF(MVT::f32); 6720 const SDValue Ops[] = { 6721 Op.getOperand(2), // tgt 6722 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 6723 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 6724 Undef, // src2 6725 Undef, // src3 6726 Op.getOperand(7), // vm 6727 DAG.getTargetConstant(1, DL, MVT::i1), // compr 6728 Op.getOperand(3), // en 6729 Op.getOperand(0) // Chain 6730 }; 6731 6732 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 6733 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 6734 } 6735 case Intrinsic::amdgcn_s_barrier: { 6736 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 6737 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 6738 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 6739 if (WGSize <= ST.getWavefrontSize()) 6740 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 6741 Op.getOperand(0)), 0); 6742 } 6743 return SDValue(); 6744 }; 6745 case Intrinsic::amdgcn_tbuffer_store: { 6746 SDValue VData = Op.getOperand(2); 6747 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6748 if (IsD16) 6749 VData = handleD16VData(VData, DAG); 6750 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6751 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6752 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6753 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 6754 unsigned IdxEn = 1; 6755 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6756 IdxEn = Idx->getZExtValue() != 0; 6757 SDValue Ops[] = { 6758 Chain, 6759 VData, // vdata 6760 Op.getOperand(3), // rsrc 6761 Op.getOperand(4), // vindex 6762 Op.getOperand(5), // voffset 6763 Op.getOperand(6), // soffset 6764 Op.getOperand(7), // offset 6765 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6766 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6767 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 6768 }; 6769 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6770 AMDGPUISD::TBUFFER_STORE_FORMAT; 6771 MemSDNode *M = cast<MemSDNode>(Op); 6772 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6773 M->getMemoryVT(), M->getMemOperand()); 6774 } 6775 6776 case Intrinsic::amdgcn_struct_tbuffer_store: { 6777 SDValue VData = Op.getOperand(2); 6778 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6779 if (IsD16) 6780 VData = handleD16VData(VData, DAG); 6781 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6782 SDValue Ops[] = { 6783 Chain, 6784 VData, // vdata 6785 Op.getOperand(3), // rsrc 6786 Op.getOperand(4), // vindex 6787 Offsets.first, // voffset 6788 Op.getOperand(6), // soffset 6789 Offsets.second, // offset 6790 Op.getOperand(7), // format 6791 Op.getOperand(8), // cachepolicy, swizzled buffer 6792 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 6793 }; 6794 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6795 AMDGPUISD::TBUFFER_STORE_FORMAT; 6796 MemSDNode *M = cast<MemSDNode>(Op); 6797 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6798 M->getMemoryVT(), M->getMemOperand()); 6799 } 6800 6801 case Intrinsic::amdgcn_raw_tbuffer_store: { 6802 SDValue VData = Op.getOperand(2); 6803 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6804 if (IsD16) 6805 VData = handleD16VData(VData, DAG); 6806 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6807 SDValue Ops[] = { 6808 Chain, 6809 VData, // vdata 6810 Op.getOperand(3), // rsrc 6811 DAG.getConstant(0, DL, MVT::i32), // vindex 6812 Offsets.first, // voffset 6813 Op.getOperand(5), // soffset 6814 Offsets.second, // offset 6815 Op.getOperand(6), // format 6816 Op.getOperand(7), // cachepolicy, swizzled buffer 6817 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 6818 }; 6819 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 6820 AMDGPUISD::TBUFFER_STORE_FORMAT; 6821 MemSDNode *M = cast<MemSDNode>(Op); 6822 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6823 M->getMemoryVT(), M->getMemOperand()); 6824 } 6825 6826 case Intrinsic::amdgcn_buffer_store: 6827 case Intrinsic::amdgcn_buffer_store_format: { 6828 SDValue VData = Op.getOperand(2); 6829 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 6830 if (IsD16) 6831 VData = handleD16VData(VData, DAG); 6832 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6833 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6834 unsigned IdxEn = 1; 6835 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6836 IdxEn = Idx->getZExtValue() != 0; 6837 SDValue Ops[] = { 6838 Chain, 6839 VData, 6840 Op.getOperand(3), // rsrc 6841 Op.getOperand(4), // vindex 6842 SDValue(), // voffset -- will be set by setBufferOffsets 6843 SDValue(), // soffset -- will be set by setBufferOffsets 6844 SDValue(), // offset -- will be set by setBufferOffsets 6845 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6846 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6847 }; 6848 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6849 // We don't know the offset if vindex is non-zero, so clear it. 6850 if (IdxEn) 6851 Offset = 0; 6852 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 6853 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6854 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6855 MemSDNode *M = cast<MemSDNode>(Op); 6856 M->getMemOperand()->setOffset(Offset); 6857 6858 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6859 EVT VDataType = VData.getValueType().getScalarType(); 6860 if (VDataType == MVT::i8 || VDataType == MVT::i16) 6861 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6862 6863 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6864 M->getMemoryVT(), M->getMemOperand()); 6865 } 6866 6867 case Intrinsic::amdgcn_raw_buffer_store: 6868 case Intrinsic::amdgcn_raw_buffer_store_format: { 6869 const bool IsFormat = 6870 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 6871 6872 SDValue VData = Op.getOperand(2); 6873 EVT VDataVT = VData.getValueType(); 6874 EVT EltType = VDataVT.getScalarType(); 6875 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6876 if (IsD16) 6877 VData = handleD16VData(VData, DAG); 6878 6879 if (!isTypeLegal(VDataVT)) { 6880 VData = 6881 DAG.getNode(ISD::BITCAST, DL, 6882 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6883 } 6884 6885 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6886 SDValue Ops[] = { 6887 Chain, 6888 VData, 6889 Op.getOperand(3), // rsrc 6890 DAG.getConstant(0, DL, MVT::i32), // vindex 6891 Offsets.first, // voffset 6892 Op.getOperand(5), // soffset 6893 Offsets.second, // offset 6894 Op.getOperand(6), // cachepolicy, swizzled buffer 6895 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6896 }; 6897 unsigned Opc = 6898 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 6899 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6900 MemSDNode *M = cast<MemSDNode>(Op); 6901 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6902 6903 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6904 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6905 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 6906 6907 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6908 M->getMemoryVT(), M->getMemOperand()); 6909 } 6910 6911 case Intrinsic::amdgcn_struct_buffer_store: 6912 case Intrinsic::amdgcn_struct_buffer_store_format: { 6913 const bool IsFormat = 6914 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 6915 6916 SDValue VData = Op.getOperand(2); 6917 EVT VDataVT = VData.getValueType(); 6918 EVT EltType = VDataVT.getScalarType(); 6919 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 6920 6921 if (IsD16) 6922 VData = handleD16VData(VData, DAG); 6923 6924 if (!isTypeLegal(VDataVT)) { 6925 VData = 6926 DAG.getNode(ISD::BITCAST, DL, 6927 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 6928 } 6929 6930 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6931 SDValue Ops[] = { 6932 Chain, 6933 VData, 6934 Op.getOperand(3), // rsrc 6935 Op.getOperand(4), // vindex 6936 Offsets.first, // voffset 6937 Op.getOperand(6), // soffset 6938 Offsets.second, // offset 6939 Op.getOperand(7), // cachepolicy, swizzled buffer 6940 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6941 }; 6942 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 6943 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 6944 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 6945 MemSDNode *M = cast<MemSDNode>(Op); 6946 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6947 Ops[3])); 6948 6949 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 6950 EVT VDataType = VData.getValueType().getScalarType(); 6951 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 6952 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 6953 6954 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 6955 M->getMemoryVT(), M->getMemOperand()); 6956 } 6957 6958 case Intrinsic::amdgcn_buffer_atomic_fadd: { 6959 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6960 unsigned IdxEn = 1; 6961 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 6962 IdxEn = Idx->getZExtValue() != 0; 6963 SDValue Ops[] = { 6964 Chain, 6965 Op.getOperand(2), // vdata 6966 Op.getOperand(3), // rsrc 6967 Op.getOperand(4), // vindex 6968 SDValue(), // voffset -- will be set by setBufferOffsets 6969 SDValue(), // soffset -- will be set by setBufferOffsets 6970 SDValue(), // offset -- will be set by setBufferOffsets 6971 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 6972 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6973 }; 6974 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 6975 // We don't know the offset if vindex is non-zero, so clear it. 6976 if (IdxEn) 6977 Offset = 0; 6978 EVT VT = Op.getOperand(2).getValueType(); 6979 6980 auto *M = cast<MemSDNode>(Op); 6981 M->getMemOperand()->setOffset(Offset); 6982 unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD 6983 : AMDGPUISD::BUFFER_ATOMIC_FADD; 6984 6985 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 6986 M->getMemOperand()); 6987 } 6988 6989 case Intrinsic::amdgcn_global_atomic_fadd: { 6990 SDValue Ops[] = { 6991 Chain, 6992 Op.getOperand(2), // ptr 6993 Op.getOperand(3) // vdata 6994 }; 6995 EVT VT = Op.getOperand(3).getValueType(); 6996 6997 auto *M = cast<MemSDNode>(Op); 6998 if (VT.isVector()) { 6999 return DAG.getMemIntrinsicNode( 7000 AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT, 7001 M->getMemOperand()); 7002 } 7003 7004 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7005 DAG.getVTList(VT, MVT::Other), Ops, 7006 M->getMemOperand()).getValue(1); 7007 } 7008 case Intrinsic::amdgcn_end_cf: 7009 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7010 Op->getOperand(2), Chain), 0); 7011 7012 default: { 7013 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7014 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7015 return lowerImage(Op, ImageDimIntr, DAG); 7016 7017 return Op; 7018 } 7019 } 7020 } 7021 7022 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7023 // offset (the offset that is included in bounds checking and swizzling, to be 7024 // split between the instruction's voffset and immoffset fields) and soffset 7025 // (the offset that is excluded from bounds checking and swizzling, to go in 7026 // the instruction's soffset field). This function takes the first kind of 7027 // offset and figures out how to split it between voffset and immoffset. 7028 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7029 SDValue Offset, SelectionDAG &DAG) const { 7030 SDLoc DL(Offset); 7031 const unsigned MaxImm = 4095; 7032 SDValue N0 = Offset; 7033 ConstantSDNode *C1 = nullptr; 7034 7035 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7036 N0 = SDValue(); 7037 else if (DAG.isBaseWithConstantOffset(N0)) { 7038 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7039 N0 = N0.getOperand(0); 7040 } 7041 7042 if (C1) { 7043 unsigned ImmOffset = C1->getZExtValue(); 7044 // If the immediate value is too big for the immoffset field, put the value 7045 // and -4096 into the immoffset field so that the value that is copied/added 7046 // for the voffset field is a multiple of 4096, and it stands more chance 7047 // of being CSEd with the copy/add for another similar load/store. 7048 // However, do not do that rounding down to a multiple of 4096 if that is a 7049 // negative number, as it appears to be illegal to have a negative offset 7050 // in the vgpr, even if adding the immediate offset makes it positive. 7051 unsigned Overflow = ImmOffset & ~MaxImm; 7052 ImmOffset -= Overflow; 7053 if ((int32_t)Overflow < 0) { 7054 Overflow += ImmOffset; 7055 ImmOffset = 0; 7056 } 7057 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7058 if (Overflow) { 7059 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7060 if (!N0) 7061 N0 = OverflowVal; 7062 else { 7063 SDValue Ops[] = { N0, OverflowVal }; 7064 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7065 } 7066 } 7067 } 7068 if (!N0) 7069 N0 = DAG.getConstant(0, DL, MVT::i32); 7070 if (!C1) 7071 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7072 return {N0, SDValue(C1, 0)}; 7073 } 7074 7075 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7076 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7077 // pointed to by Offsets. 7078 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7079 SelectionDAG &DAG, SDValue *Offsets, 7080 unsigned Align) const { 7081 SDLoc DL(CombinedOffset); 7082 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7083 uint32_t Imm = C->getZExtValue(); 7084 uint32_t SOffset, ImmOffset; 7085 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) { 7086 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7087 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7088 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7089 return SOffset + ImmOffset; 7090 } 7091 } 7092 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7093 SDValue N0 = CombinedOffset.getOperand(0); 7094 SDValue N1 = CombinedOffset.getOperand(1); 7095 uint32_t SOffset, ImmOffset; 7096 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7097 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7098 Subtarget, Align)) { 7099 Offsets[0] = N0; 7100 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7101 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7102 return 0; 7103 } 7104 } 7105 Offsets[0] = CombinedOffset; 7106 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7107 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7108 return 0; 7109 } 7110 7111 // Handle 8 bit and 16 bit buffer loads 7112 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7113 EVT LoadVT, SDLoc DL, 7114 ArrayRef<SDValue> Ops, 7115 MemSDNode *M) const { 7116 EVT IntVT = LoadVT.changeTypeToInteger(); 7117 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7118 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7119 7120 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7121 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7122 Ops, IntVT, 7123 M->getMemOperand()); 7124 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7125 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7126 7127 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7128 } 7129 7130 // Handle 8 bit and 16 bit buffer stores 7131 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7132 EVT VDataType, SDLoc DL, 7133 SDValue Ops[], 7134 MemSDNode *M) const { 7135 if (VDataType == MVT::f16) 7136 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7137 7138 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7139 Ops[1] = BufferStoreExt; 7140 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7141 AMDGPUISD::BUFFER_STORE_SHORT; 7142 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7143 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7144 M->getMemOperand()); 7145 } 7146 7147 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7148 ISD::LoadExtType ExtType, SDValue Op, 7149 const SDLoc &SL, EVT VT) { 7150 if (VT.bitsLT(Op.getValueType())) 7151 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7152 7153 switch (ExtType) { 7154 case ISD::SEXTLOAD: 7155 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7156 case ISD::ZEXTLOAD: 7157 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7158 case ISD::EXTLOAD: 7159 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7160 case ISD::NON_EXTLOAD: 7161 return Op; 7162 } 7163 7164 llvm_unreachable("invalid ext type"); 7165 } 7166 7167 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7168 SelectionDAG &DAG = DCI.DAG; 7169 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7170 return SDValue(); 7171 7172 // FIXME: Constant loads should all be marked invariant. 7173 unsigned AS = Ld->getAddressSpace(); 7174 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7175 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7176 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7177 return SDValue(); 7178 7179 // Don't do this early, since it may interfere with adjacent load merging for 7180 // illegal types. We can avoid losing alignment information for exotic types 7181 // pre-legalize. 7182 EVT MemVT = Ld->getMemoryVT(); 7183 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7184 MemVT.getSizeInBits() >= 32) 7185 return SDValue(); 7186 7187 SDLoc SL(Ld); 7188 7189 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7190 "unexpected vector extload"); 7191 7192 // TODO: Drop only high part of range. 7193 SDValue Ptr = Ld->getBasePtr(); 7194 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7195 MVT::i32, SL, Ld->getChain(), Ptr, 7196 Ld->getOffset(), 7197 Ld->getPointerInfo(), MVT::i32, 7198 Ld->getAlignment(), 7199 Ld->getMemOperand()->getFlags(), 7200 Ld->getAAInfo(), 7201 nullptr); // Drop ranges 7202 7203 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7204 if (MemVT.isFloatingPoint()) { 7205 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7206 "unexpected fp extload"); 7207 TruncVT = MemVT.changeTypeToInteger(); 7208 } 7209 7210 SDValue Cvt = NewLoad; 7211 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7212 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7213 DAG.getValueType(TruncVT)); 7214 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7215 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7216 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7217 } else { 7218 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7219 } 7220 7221 EVT VT = Ld->getValueType(0); 7222 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7223 7224 DCI.AddToWorklist(Cvt.getNode()); 7225 7226 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7227 // the appropriate extension from the 32-bit load. 7228 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7229 DCI.AddToWorklist(Cvt.getNode()); 7230 7231 // Handle conversion back to floating point if necessary. 7232 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7233 7234 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7235 } 7236 7237 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7238 SDLoc DL(Op); 7239 LoadSDNode *Load = cast<LoadSDNode>(Op); 7240 ISD::LoadExtType ExtType = Load->getExtensionType(); 7241 EVT MemVT = Load->getMemoryVT(); 7242 7243 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7244 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7245 return SDValue(); 7246 7247 // FIXME: Copied from PPC 7248 // First, load into 32 bits, then truncate to 1 bit. 7249 7250 SDValue Chain = Load->getChain(); 7251 SDValue BasePtr = Load->getBasePtr(); 7252 MachineMemOperand *MMO = Load->getMemOperand(); 7253 7254 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7255 7256 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7257 BasePtr, RealMemVT, MMO); 7258 7259 if (!MemVT.isVector()) { 7260 SDValue Ops[] = { 7261 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7262 NewLD.getValue(1) 7263 }; 7264 7265 return DAG.getMergeValues(Ops, DL); 7266 } 7267 7268 SmallVector<SDValue, 3> Elts; 7269 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7270 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7271 DAG.getConstant(I, DL, MVT::i32)); 7272 7273 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 7274 } 7275 7276 SDValue Ops[] = { 7277 DAG.getBuildVector(MemVT, DL, Elts), 7278 NewLD.getValue(1) 7279 }; 7280 7281 return DAG.getMergeValues(Ops, DL); 7282 } 7283 7284 if (!MemVT.isVector()) 7285 return SDValue(); 7286 7287 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 7288 "Custom lowering for non-i32 vectors hasn't been implemented."); 7289 7290 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7291 MemVT, *Load->getMemOperand())) { 7292 SDValue Ops[2]; 7293 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 7294 return DAG.getMergeValues(Ops, DL); 7295 } 7296 7297 unsigned Alignment = Load->getAlignment(); 7298 unsigned AS = Load->getAddressSpace(); 7299 if (Subtarget->hasLDSMisalignedBug() && 7300 AS == AMDGPUAS::FLAT_ADDRESS && 7301 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 7302 return SplitVectorLoad(Op, DAG); 7303 } 7304 7305 MachineFunction &MF = DAG.getMachineFunction(); 7306 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7307 // If there is a possibilty that flat instruction access scratch memory 7308 // then we need to use the same legalization rules we use for private. 7309 if (AS == AMDGPUAS::FLAT_ADDRESS && 7310 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7311 AS = MFI->hasFlatScratchInit() ? 7312 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7313 7314 unsigned NumElements = MemVT.getVectorNumElements(); 7315 7316 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7317 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 7318 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 7319 if (MemVT.isPow2VectorType()) 7320 return SDValue(); 7321 if (NumElements == 3) 7322 return WidenVectorLoad(Op, DAG); 7323 return SplitVectorLoad(Op, DAG); 7324 } 7325 // Non-uniform loads will be selected to MUBUF instructions, so they 7326 // have the same legalization requirements as global and private 7327 // loads. 7328 // 7329 } 7330 7331 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7332 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7333 AS == AMDGPUAS::GLOBAL_ADDRESS) { 7334 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 7335 !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) && 7336 Alignment >= 4 && NumElements < 32) { 7337 if (MemVT.isPow2VectorType()) 7338 return SDValue(); 7339 if (NumElements == 3) 7340 return WidenVectorLoad(Op, DAG); 7341 return SplitVectorLoad(Op, DAG); 7342 } 7343 // Non-uniform loads will be selected to MUBUF instructions, so they 7344 // have the same legalization requirements as global and private 7345 // loads. 7346 // 7347 } 7348 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 7349 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 7350 AS == AMDGPUAS::GLOBAL_ADDRESS || 7351 AS == AMDGPUAS::FLAT_ADDRESS) { 7352 if (NumElements > 4) 7353 return SplitVectorLoad(Op, DAG); 7354 // v3 loads not supported on SI. 7355 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7356 return WidenVectorLoad(Op, DAG); 7357 // v3 and v4 loads are supported for private and global memory. 7358 return SDValue(); 7359 } 7360 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7361 // Depending on the setting of the private_element_size field in the 7362 // resource descriptor, we can only make private accesses up to a certain 7363 // size. 7364 switch (Subtarget->getMaxPrivateElementSize()) { 7365 case 4: { 7366 SDValue Ops[2]; 7367 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 7368 return DAG.getMergeValues(Ops, DL); 7369 } 7370 case 8: 7371 if (NumElements > 2) 7372 return SplitVectorLoad(Op, DAG); 7373 return SDValue(); 7374 case 16: 7375 // Same as global/flat 7376 if (NumElements > 4) 7377 return SplitVectorLoad(Op, DAG); 7378 // v3 loads not supported on SI. 7379 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7380 return WidenVectorLoad(Op, DAG); 7381 return SDValue(); 7382 default: 7383 llvm_unreachable("unsupported private_element_size"); 7384 } 7385 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7386 // Use ds_read_b128 if possible. 7387 if (Subtarget->useDS128() && Load->getAlignment() >= 16 && 7388 MemVT.getStoreSize() == 16) 7389 return SDValue(); 7390 7391 if (NumElements > 2) 7392 return SplitVectorLoad(Op, DAG); 7393 7394 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7395 // address is negative, then the instruction is incorrectly treated as 7396 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7397 // loads here to avoid emitting ds_read2_b32. We may re-combine the 7398 // load later in the SILoadStoreOptimizer. 7399 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 7400 NumElements == 2 && MemVT.getStoreSize() == 8 && 7401 Load->getAlignment() < 8) { 7402 return SplitVectorLoad(Op, DAG); 7403 } 7404 } 7405 return SDValue(); 7406 } 7407 7408 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 7409 EVT VT = Op.getValueType(); 7410 assert(VT.getSizeInBits() == 64); 7411 7412 SDLoc DL(Op); 7413 SDValue Cond = Op.getOperand(0); 7414 7415 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 7416 SDValue One = DAG.getConstant(1, DL, MVT::i32); 7417 7418 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 7419 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 7420 7421 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 7422 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 7423 7424 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 7425 7426 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 7427 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 7428 7429 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 7430 7431 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 7432 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 7433 } 7434 7435 // Catch division cases where we can use shortcuts with rcp and rsq 7436 // instructions. 7437 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 7438 SelectionDAG &DAG) const { 7439 SDLoc SL(Op); 7440 SDValue LHS = Op.getOperand(0); 7441 SDValue RHS = Op.getOperand(1); 7442 EVT VT = Op.getValueType(); 7443 const SDNodeFlags Flags = Op->getFlags(); 7444 7445 bool FastUnsafeRcpLegal = DAG.getTarget().Options.UnsafeFPMath || 7446 (Flags.hasAllowReciprocal() && 7447 ((VT == MVT::f32 && hasFP32Denormals(DAG.getMachineFunction())) || 7448 VT == MVT::f16 || 7449 Flags.hasApproximateFuncs())); 7450 7451 // Do rcp optimization only when fast unsafe rcp is legal here. 7452 // NOTE: We already performed RCP optimization to insert intrinsics in 7453 // AMDGPUCodeGenPrepare. Ideally there should have no opportunity here to 7454 // rcp optimization. 7455 // However, there are cases like FREM, which is expended into a sequence 7456 // of instructions including FDIV, which may expose new opportunities. 7457 if (!FastUnsafeRcpLegal) 7458 return SDValue(); 7459 7460 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 7461 if (CLHS->isExactlyValue(1.0)) { 7462 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 7463 // the CI documentation has a worst case error of 1 ulp. 7464 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 7465 // use it as long as we aren't trying to use denormals. 7466 // 7467 // v_rcp_f16 and v_rsq_f16 DO support denormals. 7468 7469 // 1.0 / sqrt(x) -> rsq(x) 7470 7471 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 7472 // error seems really high at 2^29 ULP. 7473 if (RHS.getOpcode() == ISD::FSQRT) 7474 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 7475 7476 // 1.0 / x -> rcp(x) 7477 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7478 } 7479 7480 // Same as for 1.0, but expand the sign out of the constant. 7481 if (CLHS->isExactlyValue(-1.0)) { 7482 // -1.0 / x -> rcp (fneg x) 7483 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 7484 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 7485 } 7486 } 7487 7488 // Turn into multiply by the reciprocal. 7489 // x / y -> x * (1.0 / y) 7490 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 7491 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 7492 } 7493 7494 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7495 EVT VT, SDValue A, SDValue B, SDValue GlueChain) { 7496 if (GlueChain->getNumValues() <= 1) { 7497 return DAG.getNode(Opcode, SL, VT, A, B); 7498 } 7499 7500 assert(GlueChain->getNumValues() == 3); 7501 7502 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7503 switch (Opcode) { 7504 default: llvm_unreachable("no chain equivalent for opcode"); 7505 case ISD::FMUL: 7506 Opcode = AMDGPUISD::FMUL_W_CHAIN; 7507 break; 7508 } 7509 7510 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, 7511 GlueChain.getValue(2)); 7512 } 7513 7514 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 7515 EVT VT, SDValue A, SDValue B, SDValue C, 7516 SDValue GlueChain) { 7517 if (GlueChain->getNumValues() <= 1) { 7518 return DAG.getNode(Opcode, SL, VT, A, B, C); 7519 } 7520 7521 assert(GlueChain->getNumValues() == 3); 7522 7523 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 7524 switch (Opcode) { 7525 default: llvm_unreachable("no chain equivalent for opcode"); 7526 case ISD::FMA: 7527 Opcode = AMDGPUISD::FMA_W_CHAIN; 7528 break; 7529 } 7530 7531 return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C, 7532 GlueChain.getValue(2)); 7533 } 7534 7535 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 7536 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7537 return FastLowered; 7538 7539 SDLoc SL(Op); 7540 SDValue Src0 = Op.getOperand(0); 7541 SDValue Src1 = Op.getOperand(1); 7542 7543 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 7544 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 7545 7546 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 7547 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 7548 7549 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 7550 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 7551 7552 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 7553 } 7554 7555 // Faster 2.5 ULP division that does not support denormals. 7556 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 7557 SDLoc SL(Op); 7558 SDValue LHS = Op.getOperand(1); 7559 SDValue RHS = Op.getOperand(2); 7560 7561 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 7562 7563 const APFloat K0Val(BitsToFloat(0x6f800000)); 7564 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 7565 7566 const APFloat K1Val(BitsToFloat(0x2f800000)); 7567 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 7568 7569 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7570 7571 EVT SetCCVT = 7572 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 7573 7574 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 7575 7576 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 7577 7578 // TODO: Should this propagate fast-math-flags? 7579 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 7580 7581 // rcp does not support denormals. 7582 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 7583 7584 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 7585 7586 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 7587 } 7588 7589 // Returns immediate value for setting the F32 denorm mode when using the 7590 // S_DENORM_MODE instruction. 7591 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 7592 const SDLoc &SL, const GCNSubtarget *ST) { 7593 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 7594 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 7595 ? FP_DENORM_FLUSH_NONE 7596 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 7597 7598 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 7599 return DAG.getTargetConstant(Mode, SL, MVT::i32); 7600 } 7601 7602 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 7603 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 7604 return FastLowered; 7605 7606 SDLoc SL(Op); 7607 SDValue LHS = Op.getOperand(0); 7608 SDValue RHS = Op.getOperand(1); 7609 7610 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 7611 7612 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 7613 7614 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7615 RHS, RHS, LHS); 7616 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 7617 LHS, RHS, LHS); 7618 7619 // Denominator is scaled to not be denormal, so using rcp is ok. 7620 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 7621 DenominatorScaled); 7622 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 7623 DenominatorScaled); 7624 7625 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 7626 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 7627 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 7628 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16); 7629 7630 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 7631 7632 if (!HasFP32Denormals) { 7633 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 7634 7635 SDValue EnableDenorm; 7636 if (Subtarget->hasDenormModeInst()) { 7637 const SDValue EnableDenormValue = 7638 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 7639 7640 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 7641 DAG.getEntryNode(), EnableDenormValue); 7642 } else { 7643 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 7644 SL, MVT::i32); 7645 EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs, 7646 DAG.getEntryNode(), EnableDenormValue, 7647 BitField); 7648 } 7649 7650 SDValue Ops[3] = { 7651 NegDivScale0, 7652 EnableDenorm.getValue(0), 7653 EnableDenorm.getValue(1) 7654 }; 7655 7656 NegDivScale0 = DAG.getMergeValues(Ops, SL); 7657 } 7658 7659 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 7660 ApproxRcp, One, NegDivScale0); 7661 7662 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 7663 ApproxRcp, Fma0); 7664 7665 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 7666 Fma1, Fma1); 7667 7668 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 7669 NumeratorScaled, Mul); 7670 7671 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2); 7672 7673 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 7674 NumeratorScaled, Fma3); 7675 7676 if (!HasFP32Denormals) { 7677 SDValue DisableDenorm; 7678 if (Subtarget->hasDenormModeInst()) { 7679 const SDValue DisableDenormValue = 7680 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 7681 7682 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 7683 Fma4.getValue(1), DisableDenormValue, 7684 Fma4.getValue(2)); 7685 } else { 7686 const SDValue DisableDenormValue = 7687 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 7688 7689 DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other, 7690 Fma4.getValue(1), DisableDenormValue, 7691 BitField, Fma4.getValue(2)); 7692 } 7693 7694 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 7695 DisableDenorm, DAG.getRoot()); 7696 DAG.setRoot(OutputChain); 7697 } 7698 7699 SDValue Scale = NumeratorScaled.getValue(1); 7700 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 7701 Fma4, Fma1, Fma3, Scale); 7702 7703 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS); 7704 } 7705 7706 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 7707 if (DAG.getTarget().Options.UnsafeFPMath) 7708 return lowerFastUnsafeFDIV(Op, DAG); 7709 7710 SDLoc SL(Op); 7711 SDValue X = Op.getOperand(0); 7712 SDValue Y = Op.getOperand(1); 7713 7714 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 7715 7716 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 7717 7718 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 7719 7720 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 7721 7722 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 7723 7724 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 7725 7726 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 7727 7728 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 7729 7730 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 7731 7732 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 7733 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 7734 7735 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 7736 NegDivScale0, Mul, DivScale1); 7737 7738 SDValue Scale; 7739 7740 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 7741 // Workaround a hardware bug on SI where the condition output from div_scale 7742 // is not usable. 7743 7744 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 7745 7746 // Figure out if the scale to use for div_fmas. 7747 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 7748 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 7749 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 7750 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 7751 7752 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 7753 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 7754 7755 SDValue Scale0Hi 7756 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 7757 SDValue Scale1Hi 7758 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 7759 7760 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 7761 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 7762 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 7763 } else { 7764 Scale = DivScale1.getValue(1); 7765 } 7766 7767 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 7768 Fma4, Fma3, Mul, Scale); 7769 7770 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 7771 } 7772 7773 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 7774 EVT VT = Op.getValueType(); 7775 7776 if (VT == MVT::f32) 7777 return LowerFDIV32(Op, DAG); 7778 7779 if (VT == MVT::f64) 7780 return LowerFDIV64(Op, DAG); 7781 7782 if (VT == MVT::f16) 7783 return LowerFDIV16(Op, DAG); 7784 7785 llvm_unreachable("Unexpected type for fdiv"); 7786 } 7787 7788 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 7789 SDLoc DL(Op); 7790 StoreSDNode *Store = cast<StoreSDNode>(Op); 7791 EVT VT = Store->getMemoryVT(); 7792 7793 if (VT == MVT::i1) { 7794 return DAG.getTruncStore(Store->getChain(), DL, 7795 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 7796 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 7797 } 7798 7799 assert(VT.isVector() && 7800 Store->getValue().getValueType().getScalarType() == MVT::i32); 7801 7802 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 7803 VT, *Store->getMemOperand())) { 7804 return expandUnalignedStore(Store, DAG); 7805 } 7806 7807 unsigned AS = Store->getAddressSpace(); 7808 if (Subtarget->hasLDSMisalignedBug() && 7809 AS == AMDGPUAS::FLAT_ADDRESS && 7810 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 7811 return SplitVectorStore(Op, DAG); 7812 } 7813 7814 MachineFunction &MF = DAG.getMachineFunction(); 7815 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 7816 // If there is a possibilty that flat instruction access scratch memory 7817 // then we need to use the same legalization rules we use for private. 7818 if (AS == AMDGPUAS::FLAT_ADDRESS && 7819 !Subtarget->hasMultiDwordFlatScratchAddressing()) 7820 AS = MFI->hasFlatScratchInit() ? 7821 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 7822 7823 unsigned NumElements = VT.getVectorNumElements(); 7824 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 7825 AS == AMDGPUAS::FLAT_ADDRESS) { 7826 if (NumElements > 4) 7827 return SplitVectorStore(Op, DAG); 7828 // v3 stores not supported on SI. 7829 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 7830 return SplitVectorStore(Op, DAG); 7831 return SDValue(); 7832 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 7833 switch (Subtarget->getMaxPrivateElementSize()) { 7834 case 4: 7835 return scalarizeVectorStore(Store, DAG); 7836 case 8: 7837 if (NumElements > 2) 7838 return SplitVectorStore(Op, DAG); 7839 return SDValue(); 7840 case 16: 7841 if (NumElements > 4 || NumElements == 3) 7842 return SplitVectorStore(Op, DAG); 7843 return SDValue(); 7844 default: 7845 llvm_unreachable("unsupported private_element_size"); 7846 } 7847 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 7848 // Use ds_write_b128 if possible. 7849 if (Subtarget->useDS128() && Store->getAlignment() >= 16 && 7850 VT.getStoreSize() == 16 && NumElements != 3) 7851 return SDValue(); 7852 7853 if (NumElements > 2) 7854 return SplitVectorStore(Op, DAG); 7855 7856 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 7857 // address is negative, then the instruction is incorrectly treated as 7858 // out-of-bounds even if base + offsets is in bounds. Split vectorized 7859 // stores here to avoid emitting ds_write2_b32. We may re-combine the 7860 // store later in the SILoadStoreOptimizer. 7861 if (!Subtarget->hasUsableDSOffset() && 7862 NumElements == 2 && VT.getStoreSize() == 8 && 7863 Store->getAlignment() < 8) { 7864 return SplitVectorStore(Op, DAG); 7865 } 7866 7867 return SDValue(); 7868 } else { 7869 llvm_unreachable("unhandled address space"); 7870 } 7871 } 7872 7873 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 7874 SDLoc DL(Op); 7875 EVT VT = Op.getValueType(); 7876 SDValue Arg = Op.getOperand(0); 7877 SDValue TrigVal; 7878 7879 // TODO: Should this propagate fast-math-flags? 7880 7881 SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT); 7882 7883 if (Subtarget->hasTrigReducedRange()) { 7884 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7885 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal); 7886 } else { 7887 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi); 7888 } 7889 7890 switch (Op.getOpcode()) { 7891 case ISD::FCOS: 7892 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal); 7893 case ISD::FSIN: 7894 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal); 7895 default: 7896 llvm_unreachable("Wrong trig opcode"); 7897 } 7898 } 7899 7900 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 7901 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 7902 assert(AtomicNode->isCompareAndSwap()); 7903 unsigned AS = AtomicNode->getAddressSpace(); 7904 7905 // No custom lowering required for local address space 7906 if (!isFlatGlobalAddrSpace(AS)) 7907 return Op; 7908 7909 // Non-local address space requires custom lowering for atomic compare 7910 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 7911 SDLoc DL(Op); 7912 SDValue ChainIn = Op.getOperand(0); 7913 SDValue Addr = Op.getOperand(1); 7914 SDValue Old = Op.getOperand(2); 7915 SDValue New = Op.getOperand(3); 7916 EVT VT = Op.getValueType(); 7917 MVT SimpleVT = VT.getSimpleVT(); 7918 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 7919 7920 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 7921 SDValue Ops[] = { ChainIn, Addr, NewOld }; 7922 7923 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 7924 Ops, VT, AtomicNode->getMemOperand()); 7925 } 7926 7927 //===----------------------------------------------------------------------===// 7928 // Custom DAG optimizations 7929 //===----------------------------------------------------------------------===// 7930 7931 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 7932 DAGCombinerInfo &DCI) const { 7933 EVT VT = N->getValueType(0); 7934 EVT ScalarVT = VT.getScalarType(); 7935 if (ScalarVT != MVT::f32) 7936 return SDValue(); 7937 7938 SelectionDAG &DAG = DCI.DAG; 7939 SDLoc DL(N); 7940 7941 SDValue Src = N->getOperand(0); 7942 EVT SrcVT = Src.getValueType(); 7943 7944 // TODO: We could try to match extracting the higher bytes, which would be 7945 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 7946 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 7947 // about in practice. 7948 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 7949 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 7950 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src); 7951 DCI.AddToWorklist(Cvt.getNode()); 7952 return Cvt; 7953 } 7954 } 7955 7956 return SDValue(); 7957 } 7958 7959 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 7960 7961 // This is a variant of 7962 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 7963 // 7964 // The normal DAG combiner will do this, but only if the add has one use since 7965 // that would increase the number of instructions. 7966 // 7967 // This prevents us from seeing a constant offset that can be folded into a 7968 // memory instruction's addressing mode. If we know the resulting add offset of 7969 // a pointer can be folded into an addressing offset, we can replace the pointer 7970 // operand with the add of new constant offset. This eliminates one of the uses, 7971 // and may allow the remaining use to also be simplified. 7972 // 7973 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 7974 unsigned AddrSpace, 7975 EVT MemVT, 7976 DAGCombinerInfo &DCI) const { 7977 SDValue N0 = N->getOperand(0); 7978 SDValue N1 = N->getOperand(1); 7979 7980 // We only do this to handle cases where it's profitable when there are 7981 // multiple uses of the add, so defer to the standard combine. 7982 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 7983 N0->hasOneUse()) 7984 return SDValue(); 7985 7986 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 7987 if (!CN1) 7988 return SDValue(); 7989 7990 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 7991 if (!CAdd) 7992 return SDValue(); 7993 7994 // If the resulting offset is too large, we can't fold it into the addressing 7995 // mode offset. 7996 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 7997 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 7998 7999 AddrMode AM; 8000 AM.HasBaseReg = true; 8001 AM.BaseOffs = Offset.getSExtValue(); 8002 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8003 return SDValue(); 8004 8005 SelectionDAG &DAG = DCI.DAG; 8006 SDLoc SL(N); 8007 EVT VT = N->getValueType(0); 8008 8009 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8010 SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32); 8011 8012 SDNodeFlags Flags; 8013 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8014 (N0.getOpcode() == ISD::OR || 8015 N0->getFlags().hasNoUnsignedWrap())); 8016 8017 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8018 } 8019 8020 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8021 DAGCombinerInfo &DCI) const { 8022 SDValue Ptr = N->getBasePtr(); 8023 SelectionDAG &DAG = DCI.DAG; 8024 SDLoc SL(N); 8025 8026 // TODO: We could also do this for multiplies. 8027 if (Ptr.getOpcode() == ISD::SHL) { 8028 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8029 N->getMemoryVT(), DCI); 8030 if (NewPtr) { 8031 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8032 8033 NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr; 8034 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8035 } 8036 } 8037 8038 return SDValue(); 8039 } 8040 8041 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8042 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8043 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8044 (Opc == ISD::XOR && Val == 0); 8045 } 8046 8047 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8048 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8049 // integer combine opportunities since most 64-bit operations are decomposed 8050 // this way. TODO: We won't want this for SALU especially if it is an inline 8051 // immediate. 8052 SDValue SITargetLowering::splitBinaryBitConstantOp( 8053 DAGCombinerInfo &DCI, 8054 const SDLoc &SL, 8055 unsigned Opc, SDValue LHS, 8056 const ConstantSDNode *CRHS) const { 8057 uint64_t Val = CRHS->getZExtValue(); 8058 uint32_t ValLo = Lo_32(Val); 8059 uint32_t ValHi = Hi_32(Val); 8060 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8061 8062 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8063 bitOpWithConstantIsReducible(Opc, ValHi)) || 8064 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8065 // If we need to materialize a 64-bit immediate, it will be split up later 8066 // anyway. Avoid creating the harder to understand 64-bit immediate 8067 // materialization. 8068 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8069 } 8070 8071 return SDValue(); 8072 } 8073 8074 // Returns true if argument is a boolean value which is not serialized into 8075 // memory or argument and does not require v_cmdmask_b32 to be deserialized. 8076 static bool isBoolSGPR(SDValue V) { 8077 if (V.getValueType() != MVT::i1) 8078 return false; 8079 switch (V.getOpcode()) { 8080 default: break; 8081 case ISD::SETCC: 8082 case ISD::AND: 8083 case ISD::OR: 8084 case ISD::XOR: 8085 case AMDGPUISD::FP_CLASS: 8086 return true; 8087 } 8088 return false; 8089 } 8090 8091 // If a constant has all zeroes or all ones within each byte return it. 8092 // Otherwise return 0. 8093 static uint32_t getConstantPermuteMask(uint32_t C) { 8094 // 0xff for any zero byte in the mask 8095 uint32_t ZeroByteMask = 0; 8096 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8097 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8098 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8099 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8100 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8101 if ((NonZeroByteMask & C) != NonZeroByteMask) 8102 return 0; // Partial bytes selected. 8103 return C; 8104 } 8105 8106 // Check if a node selects whole bytes from its operand 0 starting at a byte 8107 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8108 // or -1 if not succeeded. 8109 // Note byte select encoding: 8110 // value 0-3 selects corresponding source byte; 8111 // value 0xc selects zero; 8112 // value 0xff selects 0xff. 8113 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8114 assert(V.getValueSizeInBits() == 32); 8115 8116 if (V.getNumOperands() != 2) 8117 return ~0; 8118 8119 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8120 if (!N1) 8121 return ~0; 8122 8123 uint32_t C = N1->getZExtValue(); 8124 8125 switch (V.getOpcode()) { 8126 default: 8127 break; 8128 case ISD::AND: 8129 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8130 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8131 } 8132 break; 8133 8134 case ISD::OR: 8135 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8136 return (0x03020100 & ~ConstMask) | ConstMask; 8137 } 8138 break; 8139 8140 case ISD::SHL: 8141 if (C % 8) 8142 return ~0; 8143 8144 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8145 8146 case ISD::SRL: 8147 if (C % 8) 8148 return ~0; 8149 8150 return uint32_t(0x0c0c0c0c03020100ull >> C); 8151 } 8152 8153 return ~0; 8154 } 8155 8156 SDValue SITargetLowering::performAndCombine(SDNode *N, 8157 DAGCombinerInfo &DCI) const { 8158 if (DCI.isBeforeLegalize()) 8159 return SDValue(); 8160 8161 SelectionDAG &DAG = DCI.DAG; 8162 EVT VT = N->getValueType(0); 8163 SDValue LHS = N->getOperand(0); 8164 SDValue RHS = N->getOperand(1); 8165 8166 8167 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8168 if (VT == MVT::i64 && CRHS) { 8169 if (SDValue Split 8170 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8171 return Split; 8172 } 8173 8174 if (CRHS && VT == MVT::i32) { 8175 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8176 // nb = number of trailing zeroes in mask 8177 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8178 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8179 uint64_t Mask = CRHS->getZExtValue(); 8180 unsigned Bits = countPopulation(Mask); 8181 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8182 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8183 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8184 unsigned Shift = CShift->getZExtValue(); 8185 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8186 unsigned Offset = NB + Shift; 8187 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8188 SDLoc SL(N); 8189 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8190 LHS->getOperand(0), 8191 DAG.getConstant(Offset, SL, MVT::i32), 8192 DAG.getConstant(Bits, SL, MVT::i32)); 8193 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8194 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8195 DAG.getValueType(NarrowVT)); 8196 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8197 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8198 return Shl; 8199 } 8200 } 8201 } 8202 8203 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8204 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 8205 isa<ConstantSDNode>(LHS.getOperand(2))) { 8206 uint32_t Sel = getConstantPermuteMask(Mask); 8207 if (!Sel) 8208 return SDValue(); 8209 8210 // Select 0xc for all zero bytes 8211 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 8212 SDLoc DL(N); 8213 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8214 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8215 } 8216 } 8217 8218 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 8219 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 8220 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 8221 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8222 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 8223 8224 SDValue X = LHS.getOperand(0); 8225 SDValue Y = RHS.getOperand(0); 8226 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 8227 return SDValue(); 8228 8229 if (LCC == ISD::SETO) { 8230 if (X != LHS.getOperand(1)) 8231 return SDValue(); 8232 8233 if (RCC == ISD::SETUNE) { 8234 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 8235 if (!C1 || !C1->isInfinity() || C1->isNegative()) 8236 return SDValue(); 8237 8238 const uint32_t Mask = SIInstrFlags::N_NORMAL | 8239 SIInstrFlags::N_SUBNORMAL | 8240 SIInstrFlags::N_ZERO | 8241 SIInstrFlags::P_ZERO | 8242 SIInstrFlags::P_SUBNORMAL | 8243 SIInstrFlags::P_NORMAL; 8244 8245 static_assert(((~(SIInstrFlags::S_NAN | 8246 SIInstrFlags::Q_NAN | 8247 SIInstrFlags::N_INFINITY | 8248 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 8249 "mask not equal"); 8250 8251 SDLoc DL(N); 8252 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8253 X, DAG.getConstant(Mask, DL, MVT::i32)); 8254 } 8255 } 8256 } 8257 8258 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 8259 std::swap(LHS, RHS); 8260 8261 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 8262 RHS.hasOneUse()) { 8263 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8264 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 8265 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 8266 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8267 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 8268 (RHS.getOperand(0) == LHS.getOperand(0) && 8269 LHS.getOperand(0) == LHS.getOperand(1))) { 8270 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 8271 unsigned NewMask = LCC == ISD::SETO ? 8272 Mask->getZExtValue() & ~OrdMask : 8273 Mask->getZExtValue() & OrdMask; 8274 8275 SDLoc DL(N); 8276 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 8277 DAG.getConstant(NewMask, DL, MVT::i32)); 8278 } 8279 } 8280 8281 if (VT == MVT::i32 && 8282 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 8283 // and x, (sext cc from i1) => select cc, x, 0 8284 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 8285 std::swap(LHS, RHS); 8286 if (isBoolSGPR(RHS.getOperand(0))) 8287 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 8288 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 8289 } 8290 8291 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8292 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8293 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8294 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8295 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8296 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8297 if (LHSMask != ~0u && RHSMask != ~0u) { 8298 // Canonicalize the expression in an attempt to have fewer unique masks 8299 // and therefore fewer registers used to hold the masks. 8300 if (LHSMask > RHSMask) { 8301 std::swap(LHSMask, RHSMask); 8302 std::swap(LHS, RHS); 8303 } 8304 8305 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8306 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8307 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8308 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8309 8310 // Check of we need to combine values from two sources within a byte. 8311 if (!(LHSUsedLanes & RHSUsedLanes) && 8312 // If we select high and lower word keep it for SDWA. 8313 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8314 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8315 // Each byte in each mask is either selector mask 0-3, or has higher 8316 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 8317 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 8318 // mask which is not 0xff wins. By anding both masks we have a correct 8319 // result except that 0x0c shall be corrected to give 0x0c only. 8320 uint32_t Mask = LHSMask & RHSMask; 8321 for (unsigned I = 0; I < 32; I += 8) { 8322 uint32_t ByteSel = 0xff << I; 8323 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 8324 Mask &= (0x0c << I) & 0xffffffff; 8325 } 8326 8327 // Add 4 to each active LHS lane. It will not affect any existing 0xff 8328 // or 0x0c. 8329 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 8330 SDLoc DL(N); 8331 8332 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8333 LHS.getOperand(0), RHS.getOperand(0), 8334 DAG.getConstant(Sel, DL, MVT::i32)); 8335 } 8336 } 8337 } 8338 8339 return SDValue(); 8340 } 8341 8342 SDValue SITargetLowering::performOrCombine(SDNode *N, 8343 DAGCombinerInfo &DCI) const { 8344 SelectionDAG &DAG = DCI.DAG; 8345 SDValue LHS = N->getOperand(0); 8346 SDValue RHS = N->getOperand(1); 8347 8348 EVT VT = N->getValueType(0); 8349 if (VT == MVT::i1) { 8350 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 8351 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 8352 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 8353 SDValue Src = LHS.getOperand(0); 8354 if (Src != RHS.getOperand(0)) 8355 return SDValue(); 8356 8357 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 8358 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 8359 if (!CLHS || !CRHS) 8360 return SDValue(); 8361 8362 // Only 10 bits are used. 8363 static const uint32_t MaxMask = 0x3ff; 8364 8365 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 8366 SDLoc DL(N); 8367 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 8368 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 8369 } 8370 8371 return SDValue(); 8372 } 8373 8374 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 8375 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 8376 LHS.getOpcode() == AMDGPUISD::PERM && 8377 isa<ConstantSDNode>(LHS.getOperand(2))) { 8378 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 8379 if (!Sel) 8380 return SDValue(); 8381 8382 Sel |= LHS.getConstantOperandVal(2); 8383 SDLoc DL(N); 8384 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 8385 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 8386 } 8387 8388 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 8389 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8390 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 8391 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) { 8392 uint32_t LHSMask = getPermuteMask(DAG, LHS); 8393 uint32_t RHSMask = getPermuteMask(DAG, RHS); 8394 if (LHSMask != ~0u && RHSMask != ~0u) { 8395 // Canonicalize the expression in an attempt to have fewer unique masks 8396 // and therefore fewer registers used to hold the masks. 8397 if (LHSMask > RHSMask) { 8398 std::swap(LHSMask, RHSMask); 8399 std::swap(LHS, RHS); 8400 } 8401 8402 // Select 0xc for each lane used from source operand. Zero has 0xc mask 8403 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 8404 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8405 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 8406 8407 // Check of we need to combine values from two sources within a byte. 8408 if (!(LHSUsedLanes & RHSUsedLanes) && 8409 // If we select high and lower word keep it for SDWA. 8410 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 8411 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 8412 // Kill zero bytes selected by other mask. Zero value is 0xc. 8413 LHSMask &= ~RHSUsedLanes; 8414 RHSMask &= ~LHSUsedLanes; 8415 // Add 4 to each active LHS lane 8416 LHSMask |= LHSUsedLanes & 0x04040404; 8417 // Combine masks 8418 uint32_t Sel = LHSMask | RHSMask; 8419 SDLoc DL(N); 8420 8421 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 8422 LHS.getOperand(0), RHS.getOperand(0), 8423 DAG.getConstant(Sel, DL, MVT::i32)); 8424 } 8425 } 8426 } 8427 8428 if (VT != MVT::i64) 8429 return SDValue(); 8430 8431 // TODO: This could be a generic combine with a predicate for extracting the 8432 // high half of an integer being free. 8433 8434 // (or i64:x, (zero_extend i32:y)) -> 8435 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 8436 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 8437 RHS.getOpcode() != ISD::ZERO_EXTEND) 8438 std::swap(LHS, RHS); 8439 8440 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 8441 SDValue ExtSrc = RHS.getOperand(0); 8442 EVT SrcVT = ExtSrc.getValueType(); 8443 if (SrcVT == MVT::i32) { 8444 SDLoc SL(N); 8445 SDValue LowLHS, HiBits; 8446 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 8447 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 8448 8449 DCI.AddToWorklist(LowOr.getNode()); 8450 DCI.AddToWorklist(HiBits.getNode()); 8451 8452 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 8453 LowOr, HiBits); 8454 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 8455 } 8456 } 8457 8458 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8459 if (CRHS) { 8460 if (SDValue Split 8461 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 8462 return Split; 8463 } 8464 8465 return SDValue(); 8466 } 8467 8468 SDValue SITargetLowering::performXorCombine(SDNode *N, 8469 DAGCombinerInfo &DCI) const { 8470 EVT VT = N->getValueType(0); 8471 if (VT != MVT::i64) 8472 return SDValue(); 8473 8474 SDValue LHS = N->getOperand(0); 8475 SDValue RHS = N->getOperand(1); 8476 8477 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8478 if (CRHS) { 8479 if (SDValue Split 8480 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 8481 return Split; 8482 } 8483 8484 return SDValue(); 8485 } 8486 8487 // Instructions that will be lowered with a final instruction that zeros the 8488 // high result bits. 8489 // XXX - probably only need to list legal operations. 8490 static bool fp16SrcZerosHighBits(unsigned Opc) { 8491 switch (Opc) { 8492 case ISD::FADD: 8493 case ISD::FSUB: 8494 case ISD::FMUL: 8495 case ISD::FDIV: 8496 case ISD::FREM: 8497 case ISD::FMA: 8498 case ISD::FMAD: 8499 case ISD::FCANONICALIZE: 8500 case ISD::FP_ROUND: 8501 case ISD::UINT_TO_FP: 8502 case ISD::SINT_TO_FP: 8503 case ISD::FABS: 8504 // Fabs is lowered to a bit operation, but it's an and which will clear the 8505 // high bits anyway. 8506 case ISD::FSQRT: 8507 case ISD::FSIN: 8508 case ISD::FCOS: 8509 case ISD::FPOWI: 8510 case ISD::FPOW: 8511 case ISD::FLOG: 8512 case ISD::FLOG2: 8513 case ISD::FLOG10: 8514 case ISD::FEXP: 8515 case ISD::FEXP2: 8516 case ISD::FCEIL: 8517 case ISD::FTRUNC: 8518 case ISD::FRINT: 8519 case ISD::FNEARBYINT: 8520 case ISD::FROUND: 8521 case ISD::FFLOOR: 8522 case ISD::FMINNUM: 8523 case ISD::FMAXNUM: 8524 case AMDGPUISD::FRACT: 8525 case AMDGPUISD::CLAMP: 8526 case AMDGPUISD::COS_HW: 8527 case AMDGPUISD::SIN_HW: 8528 case AMDGPUISD::FMIN3: 8529 case AMDGPUISD::FMAX3: 8530 case AMDGPUISD::FMED3: 8531 case AMDGPUISD::FMAD_FTZ: 8532 case AMDGPUISD::RCP: 8533 case AMDGPUISD::RSQ: 8534 case AMDGPUISD::RCP_IFLAG: 8535 case AMDGPUISD::LDEXP: 8536 return true; 8537 default: 8538 // fcopysign, select and others may be lowered to 32-bit bit operations 8539 // which don't zero the high bits. 8540 return false; 8541 } 8542 } 8543 8544 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 8545 DAGCombinerInfo &DCI) const { 8546 if (!Subtarget->has16BitInsts() || 8547 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 8548 return SDValue(); 8549 8550 EVT VT = N->getValueType(0); 8551 if (VT != MVT::i32) 8552 return SDValue(); 8553 8554 SDValue Src = N->getOperand(0); 8555 if (Src.getValueType() != MVT::i16) 8556 return SDValue(); 8557 8558 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 8559 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 8560 if (Src.getOpcode() == ISD::BITCAST) { 8561 SDValue BCSrc = Src.getOperand(0); 8562 if (BCSrc.getValueType() == MVT::f16 && 8563 fp16SrcZerosHighBits(BCSrc.getOpcode())) 8564 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 8565 } 8566 8567 return SDValue(); 8568 } 8569 8570 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 8571 DAGCombinerInfo &DCI) 8572 const { 8573 SDValue Src = N->getOperand(0); 8574 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 8575 8576 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 8577 VTSign->getVT() == MVT::i8) || 8578 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 8579 VTSign->getVT() == MVT::i16)) && 8580 Src.hasOneUse()) { 8581 auto *M = cast<MemSDNode>(Src); 8582 SDValue Ops[] = { 8583 Src.getOperand(0), // Chain 8584 Src.getOperand(1), // rsrc 8585 Src.getOperand(2), // vindex 8586 Src.getOperand(3), // voffset 8587 Src.getOperand(4), // soffset 8588 Src.getOperand(5), // offset 8589 Src.getOperand(6), 8590 Src.getOperand(7) 8591 }; 8592 // replace with BUFFER_LOAD_BYTE/SHORT 8593 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 8594 Src.getOperand(0).getValueType()); 8595 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 8596 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 8597 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 8598 ResList, 8599 Ops, M->getMemoryVT(), 8600 M->getMemOperand()); 8601 return DCI.DAG.getMergeValues({BufferLoadSignExt, 8602 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 8603 } 8604 return SDValue(); 8605 } 8606 8607 SDValue SITargetLowering::performClassCombine(SDNode *N, 8608 DAGCombinerInfo &DCI) const { 8609 SelectionDAG &DAG = DCI.DAG; 8610 SDValue Mask = N->getOperand(1); 8611 8612 // fp_class x, 0 -> false 8613 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 8614 if (CMask->isNullValue()) 8615 return DAG.getConstant(0, SDLoc(N), MVT::i1); 8616 } 8617 8618 if (N->getOperand(0).isUndef()) 8619 return DAG.getUNDEF(MVT::i1); 8620 8621 return SDValue(); 8622 } 8623 8624 SDValue SITargetLowering::performRcpCombine(SDNode *N, 8625 DAGCombinerInfo &DCI) const { 8626 EVT VT = N->getValueType(0); 8627 SDValue N0 = N->getOperand(0); 8628 8629 if (N0.isUndef()) 8630 return N0; 8631 8632 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 8633 N0.getOpcode() == ISD::SINT_TO_FP)) { 8634 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 8635 N->getFlags()); 8636 } 8637 8638 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 8639 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 8640 N0.getOperand(0), N->getFlags()); 8641 } 8642 8643 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 8644 } 8645 8646 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 8647 unsigned MaxDepth) const { 8648 unsigned Opcode = Op.getOpcode(); 8649 if (Opcode == ISD::FCANONICALIZE) 8650 return true; 8651 8652 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8653 auto F = CFP->getValueAPF(); 8654 if (F.isNaN() && F.isSignaling()) 8655 return false; 8656 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 8657 } 8658 8659 // If source is a result of another standard FP operation it is already in 8660 // canonical form. 8661 if (MaxDepth == 0) 8662 return false; 8663 8664 switch (Opcode) { 8665 // These will flush denorms if required. 8666 case ISD::FADD: 8667 case ISD::FSUB: 8668 case ISD::FMUL: 8669 case ISD::FCEIL: 8670 case ISD::FFLOOR: 8671 case ISD::FMA: 8672 case ISD::FMAD: 8673 case ISD::FSQRT: 8674 case ISD::FDIV: 8675 case ISD::FREM: 8676 case ISD::FP_ROUND: 8677 case ISD::FP_EXTEND: 8678 case AMDGPUISD::FMUL_LEGACY: 8679 case AMDGPUISD::FMAD_FTZ: 8680 case AMDGPUISD::RCP: 8681 case AMDGPUISD::RSQ: 8682 case AMDGPUISD::RSQ_CLAMP: 8683 case AMDGPUISD::RCP_LEGACY: 8684 case AMDGPUISD::RSQ_LEGACY: 8685 case AMDGPUISD::RCP_IFLAG: 8686 case AMDGPUISD::TRIG_PREOP: 8687 case AMDGPUISD::DIV_SCALE: 8688 case AMDGPUISD::DIV_FMAS: 8689 case AMDGPUISD::DIV_FIXUP: 8690 case AMDGPUISD::FRACT: 8691 case AMDGPUISD::LDEXP: 8692 case AMDGPUISD::CVT_PKRTZ_F16_F32: 8693 case AMDGPUISD::CVT_F32_UBYTE0: 8694 case AMDGPUISD::CVT_F32_UBYTE1: 8695 case AMDGPUISD::CVT_F32_UBYTE2: 8696 case AMDGPUISD::CVT_F32_UBYTE3: 8697 return true; 8698 8699 // It can/will be lowered or combined as a bit operation. 8700 // Need to check their input recursively to handle. 8701 case ISD::FNEG: 8702 case ISD::FABS: 8703 case ISD::FCOPYSIGN: 8704 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8705 8706 case ISD::FSIN: 8707 case ISD::FCOS: 8708 case ISD::FSINCOS: 8709 return Op.getValueType().getScalarType() != MVT::f16; 8710 8711 case ISD::FMINNUM: 8712 case ISD::FMAXNUM: 8713 case ISD::FMINNUM_IEEE: 8714 case ISD::FMAXNUM_IEEE: 8715 case AMDGPUISD::CLAMP: 8716 case AMDGPUISD::FMED3: 8717 case AMDGPUISD::FMAX3: 8718 case AMDGPUISD::FMIN3: { 8719 // FIXME: Shouldn't treat the generic operations different based these. 8720 // However, we aren't really required to flush the result from 8721 // minnum/maxnum.. 8722 8723 // snans will be quieted, so we only need to worry about denormals. 8724 if (Subtarget->supportsMinMaxDenormModes() || 8725 denormalsEnabledForType(DAG, Op.getValueType())) 8726 return true; 8727 8728 // Flushing may be required. 8729 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 8730 // targets need to check their input recursively. 8731 8732 // FIXME: Does this apply with clamp? It's implemented with max. 8733 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 8734 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 8735 return false; 8736 } 8737 8738 return true; 8739 } 8740 case ISD::SELECT: { 8741 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 8742 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 8743 } 8744 case ISD::BUILD_VECTOR: { 8745 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 8746 SDValue SrcOp = Op.getOperand(i); 8747 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 8748 return false; 8749 } 8750 8751 return true; 8752 } 8753 case ISD::EXTRACT_VECTOR_ELT: 8754 case ISD::EXTRACT_SUBVECTOR: { 8755 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 8756 } 8757 case ISD::INSERT_VECTOR_ELT: { 8758 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 8759 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 8760 } 8761 case ISD::UNDEF: 8762 // Could be anything. 8763 return false; 8764 8765 case ISD::BITCAST: { 8766 // Hack round the mess we make when legalizing extract_vector_elt 8767 SDValue Src = Op.getOperand(0); 8768 if (Src.getValueType() == MVT::i16 && 8769 Src.getOpcode() == ISD::TRUNCATE) { 8770 SDValue TruncSrc = Src.getOperand(0); 8771 if (TruncSrc.getValueType() == MVT::i32 && 8772 TruncSrc.getOpcode() == ISD::BITCAST && 8773 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 8774 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 8775 } 8776 } 8777 8778 return false; 8779 } 8780 case ISD::INTRINSIC_WO_CHAIN: { 8781 unsigned IntrinsicID 8782 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 8783 // TODO: Handle more intrinsics 8784 switch (IntrinsicID) { 8785 case Intrinsic::amdgcn_cvt_pkrtz: 8786 case Intrinsic::amdgcn_cubeid: 8787 case Intrinsic::amdgcn_frexp_mant: 8788 case Intrinsic::amdgcn_fdot2: 8789 return true; 8790 default: 8791 break; 8792 } 8793 8794 LLVM_FALLTHROUGH; 8795 } 8796 default: 8797 return denormalsEnabledForType(DAG, Op.getValueType()) && 8798 DAG.isKnownNeverSNaN(Op); 8799 } 8800 8801 llvm_unreachable("invalid operation"); 8802 } 8803 8804 // Constant fold canonicalize. 8805 SDValue SITargetLowering::getCanonicalConstantFP( 8806 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 8807 // Flush denormals to 0 if not enabled. 8808 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 8809 return DAG.getConstantFP(0.0, SL, VT); 8810 8811 if (C.isNaN()) { 8812 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 8813 if (C.isSignaling()) { 8814 // Quiet a signaling NaN. 8815 // FIXME: Is this supposed to preserve payload bits? 8816 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8817 } 8818 8819 // Make sure it is the canonical NaN bitpattern. 8820 // 8821 // TODO: Can we use -1 as the canonical NaN value since it's an inline 8822 // immediate? 8823 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 8824 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 8825 } 8826 8827 // Already canonical. 8828 return DAG.getConstantFP(C, SL, VT); 8829 } 8830 8831 static bool vectorEltWillFoldAway(SDValue Op) { 8832 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 8833 } 8834 8835 SDValue SITargetLowering::performFCanonicalizeCombine( 8836 SDNode *N, 8837 DAGCombinerInfo &DCI) const { 8838 SelectionDAG &DAG = DCI.DAG; 8839 SDValue N0 = N->getOperand(0); 8840 EVT VT = N->getValueType(0); 8841 8842 // fcanonicalize undef -> qnan 8843 if (N0.isUndef()) { 8844 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 8845 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 8846 } 8847 8848 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 8849 EVT VT = N->getValueType(0); 8850 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 8851 } 8852 8853 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 8854 // (fcanonicalize k) 8855 // 8856 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 8857 8858 // TODO: This could be better with wider vectors that will be split to v2f16, 8859 // and to consider uses since there aren't that many packed operations. 8860 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 8861 isTypeLegal(MVT::v2f16)) { 8862 SDLoc SL(N); 8863 SDValue NewElts[2]; 8864 SDValue Lo = N0.getOperand(0); 8865 SDValue Hi = N0.getOperand(1); 8866 EVT EltVT = Lo.getValueType(); 8867 8868 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 8869 for (unsigned I = 0; I != 2; ++I) { 8870 SDValue Op = N0.getOperand(I); 8871 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 8872 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 8873 CFP->getValueAPF()); 8874 } else if (Op.isUndef()) { 8875 // Handled below based on what the other operand is. 8876 NewElts[I] = Op; 8877 } else { 8878 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 8879 } 8880 } 8881 8882 // If one half is undef, and one is constant, perfer a splat vector rather 8883 // than the normal qNaN. If it's a register, prefer 0.0 since that's 8884 // cheaper to use and may be free with a packed operation. 8885 if (NewElts[0].isUndef()) { 8886 if (isa<ConstantFPSDNode>(NewElts[1])) 8887 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 8888 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 8889 } 8890 8891 if (NewElts[1].isUndef()) { 8892 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 8893 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 8894 } 8895 8896 return DAG.getBuildVector(VT, SL, NewElts); 8897 } 8898 } 8899 8900 unsigned SrcOpc = N0.getOpcode(); 8901 8902 // If it's free to do so, push canonicalizes further up the source, which may 8903 // find a canonical source. 8904 // 8905 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 8906 // sNaNs. 8907 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 8908 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 8909 if (CRHS && N0.hasOneUse()) { 8910 SDLoc SL(N); 8911 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 8912 N0.getOperand(0)); 8913 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 8914 DCI.AddToWorklist(Canon0.getNode()); 8915 8916 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 8917 } 8918 } 8919 8920 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 8921 } 8922 8923 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 8924 switch (Opc) { 8925 case ISD::FMAXNUM: 8926 case ISD::FMAXNUM_IEEE: 8927 return AMDGPUISD::FMAX3; 8928 case ISD::SMAX: 8929 return AMDGPUISD::SMAX3; 8930 case ISD::UMAX: 8931 return AMDGPUISD::UMAX3; 8932 case ISD::FMINNUM: 8933 case ISD::FMINNUM_IEEE: 8934 return AMDGPUISD::FMIN3; 8935 case ISD::SMIN: 8936 return AMDGPUISD::SMIN3; 8937 case ISD::UMIN: 8938 return AMDGPUISD::UMIN3; 8939 default: 8940 llvm_unreachable("Not a min/max opcode"); 8941 } 8942 } 8943 8944 SDValue SITargetLowering::performIntMed3ImmCombine( 8945 SelectionDAG &DAG, const SDLoc &SL, 8946 SDValue Op0, SDValue Op1, bool Signed) const { 8947 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 8948 if (!K1) 8949 return SDValue(); 8950 8951 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 8952 if (!K0) 8953 return SDValue(); 8954 8955 if (Signed) { 8956 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 8957 return SDValue(); 8958 } else { 8959 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 8960 return SDValue(); 8961 } 8962 8963 EVT VT = K0->getValueType(0); 8964 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 8965 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 8966 return DAG.getNode(Med3Opc, SL, VT, 8967 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 8968 } 8969 8970 // If there isn't a 16-bit med3 operation, convert to 32-bit. 8971 MVT NVT = MVT::i32; 8972 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 8973 8974 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 8975 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 8976 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 8977 8978 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 8979 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 8980 } 8981 8982 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 8983 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 8984 return C; 8985 8986 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 8987 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 8988 return C; 8989 } 8990 8991 return nullptr; 8992 } 8993 8994 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 8995 const SDLoc &SL, 8996 SDValue Op0, 8997 SDValue Op1) const { 8998 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 8999 if (!K1) 9000 return SDValue(); 9001 9002 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9003 if (!K0) 9004 return SDValue(); 9005 9006 // Ordered >= (although NaN inputs should have folded away by now). 9007 APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF()); 9008 if (Cmp == APFloat::cmpGreaterThan) 9009 return SDValue(); 9010 9011 const MachineFunction &MF = DAG.getMachineFunction(); 9012 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9013 9014 // TODO: Check IEEE bit enabled? 9015 EVT VT = Op0.getValueType(); 9016 if (Info->getMode().DX10Clamp) { 9017 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9018 // hardware fmed3 behavior converting to a min. 9019 // FIXME: Should this be allowing -0.0? 9020 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9021 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9022 } 9023 9024 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9025 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9026 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9027 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9028 // then give the other result, which is different from med3 with a NaN 9029 // input. 9030 SDValue Var = Op0.getOperand(0); 9031 if (!DAG.isKnownNeverSNaN(Var)) 9032 return SDValue(); 9033 9034 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9035 9036 if ((!K0->hasOneUse() || 9037 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9038 (!K1->hasOneUse() || 9039 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9040 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9041 Var, SDValue(K0, 0), SDValue(K1, 0)); 9042 } 9043 } 9044 9045 return SDValue(); 9046 } 9047 9048 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9049 DAGCombinerInfo &DCI) const { 9050 SelectionDAG &DAG = DCI.DAG; 9051 9052 EVT VT = N->getValueType(0); 9053 unsigned Opc = N->getOpcode(); 9054 SDValue Op0 = N->getOperand(0); 9055 SDValue Op1 = N->getOperand(1); 9056 9057 // Only do this if the inner op has one use since this will just increases 9058 // register pressure for no benefit. 9059 9060 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9061 !VT.isVector() && 9062 (VT == MVT::i32 || VT == MVT::f32 || 9063 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9064 // max(max(a, b), c) -> max3(a, b, c) 9065 // min(min(a, b), c) -> min3(a, b, c) 9066 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9067 SDLoc DL(N); 9068 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9069 DL, 9070 N->getValueType(0), 9071 Op0.getOperand(0), 9072 Op0.getOperand(1), 9073 Op1); 9074 } 9075 9076 // Try commuted. 9077 // max(a, max(b, c)) -> max3(a, b, c) 9078 // min(a, min(b, c)) -> min3(a, b, c) 9079 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9080 SDLoc DL(N); 9081 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9082 DL, 9083 N->getValueType(0), 9084 Op0, 9085 Op1.getOperand(0), 9086 Op1.getOperand(1)); 9087 } 9088 } 9089 9090 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9091 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9092 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9093 return Med3; 9094 } 9095 9096 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9097 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9098 return Med3; 9099 } 9100 9101 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9102 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9103 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9104 (Opc == AMDGPUISD::FMIN_LEGACY && 9105 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9106 (VT == MVT::f32 || VT == MVT::f64 || 9107 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9108 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9109 Op0.hasOneUse()) { 9110 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9111 return Res; 9112 } 9113 9114 return SDValue(); 9115 } 9116 9117 static bool isClampZeroToOne(SDValue A, SDValue B) { 9118 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9119 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9120 // FIXME: Should this be allowing -0.0? 9121 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9122 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9123 } 9124 } 9125 9126 return false; 9127 } 9128 9129 // FIXME: Should only worry about snans for version with chain. 9130 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9131 DAGCombinerInfo &DCI) const { 9132 EVT VT = N->getValueType(0); 9133 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9134 // NaNs. With a NaN input, the order of the operands may change the result. 9135 9136 SelectionDAG &DAG = DCI.DAG; 9137 SDLoc SL(N); 9138 9139 SDValue Src0 = N->getOperand(0); 9140 SDValue Src1 = N->getOperand(1); 9141 SDValue Src2 = N->getOperand(2); 9142 9143 if (isClampZeroToOne(Src0, Src1)) { 9144 // const_a, const_b, x -> clamp is safe in all cases including signaling 9145 // nans. 9146 // FIXME: Should this be allowing -0.0? 9147 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9148 } 9149 9150 const MachineFunction &MF = DAG.getMachineFunction(); 9151 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9152 9153 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9154 // handling no dx10-clamp? 9155 if (Info->getMode().DX10Clamp) { 9156 // If NaNs is clamped to 0, we are free to reorder the inputs. 9157 9158 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9159 std::swap(Src0, Src1); 9160 9161 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9162 std::swap(Src1, Src2); 9163 9164 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9165 std::swap(Src0, Src1); 9166 9167 if (isClampZeroToOne(Src1, Src2)) 9168 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9169 } 9170 9171 return SDValue(); 9172 } 9173 9174 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9175 DAGCombinerInfo &DCI) const { 9176 SDValue Src0 = N->getOperand(0); 9177 SDValue Src1 = N->getOperand(1); 9178 if (Src0.isUndef() && Src1.isUndef()) 9179 return DCI.DAG.getUNDEF(N->getValueType(0)); 9180 return SDValue(); 9181 } 9182 9183 SDValue SITargetLowering::performExtractVectorEltCombine( 9184 SDNode *N, DAGCombinerInfo &DCI) const { 9185 SDValue Vec = N->getOperand(0); 9186 SelectionDAG &DAG = DCI.DAG; 9187 9188 EVT VecVT = Vec.getValueType(); 9189 EVT EltVT = VecVT.getVectorElementType(); 9190 9191 if ((Vec.getOpcode() == ISD::FNEG || 9192 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 9193 SDLoc SL(N); 9194 EVT EltVT = N->getValueType(0); 9195 SDValue Idx = N->getOperand(1); 9196 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9197 Vec.getOperand(0), Idx); 9198 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 9199 } 9200 9201 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 9202 // => 9203 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 9204 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 9205 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 9206 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 9207 SDLoc SL(N); 9208 EVT EltVT = N->getValueType(0); 9209 SDValue Idx = N->getOperand(1); 9210 unsigned Opc = Vec.getOpcode(); 9211 9212 switch(Opc) { 9213 default: 9214 break; 9215 // TODO: Support other binary operations. 9216 case ISD::FADD: 9217 case ISD::FSUB: 9218 case ISD::FMUL: 9219 case ISD::ADD: 9220 case ISD::UMIN: 9221 case ISD::UMAX: 9222 case ISD::SMIN: 9223 case ISD::SMAX: 9224 case ISD::FMAXNUM: 9225 case ISD::FMINNUM: 9226 case ISD::FMAXNUM_IEEE: 9227 case ISD::FMINNUM_IEEE: { 9228 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9229 Vec.getOperand(0), Idx); 9230 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 9231 Vec.getOperand(1), Idx); 9232 9233 DCI.AddToWorklist(Elt0.getNode()); 9234 DCI.AddToWorklist(Elt1.getNode()); 9235 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 9236 } 9237 } 9238 } 9239 9240 unsigned VecSize = VecVT.getSizeInBits(); 9241 unsigned EltSize = EltVT.getSizeInBits(); 9242 9243 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 9244 // This elminates non-constant index and subsequent movrel or scratch access. 9245 // Sub-dword vectors of size 2 dword or less have better implementation. 9246 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9247 // instructions. 9248 if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) && 9249 !isa<ConstantSDNode>(N->getOperand(1))) { 9250 SDLoc SL(N); 9251 SDValue Idx = N->getOperand(1); 9252 SDValue V; 9253 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9254 SDValue IC = DAG.getVectorIdxConstant(I, SL); 9255 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9256 if (I == 0) 9257 V = Elt; 9258 else 9259 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 9260 } 9261 return V; 9262 } 9263 9264 if (!DCI.isBeforeLegalize()) 9265 return SDValue(); 9266 9267 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 9268 // elements. This exposes more load reduction opportunities by replacing 9269 // multiple small extract_vector_elements with a single 32-bit extract. 9270 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9271 if (isa<MemSDNode>(Vec) && 9272 EltSize <= 16 && 9273 EltVT.isByteSized() && 9274 VecSize > 32 && 9275 VecSize % 32 == 0 && 9276 Idx) { 9277 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 9278 9279 unsigned BitIndex = Idx->getZExtValue() * EltSize; 9280 unsigned EltIdx = BitIndex / 32; 9281 unsigned LeftoverBitIdx = BitIndex % 32; 9282 SDLoc SL(N); 9283 9284 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 9285 DCI.AddToWorklist(Cast.getNode()); 9286 9287 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 9288 DAG.getConstant(EltIdx, SL, MVT::i32)); 9289 DCI.AddToWorklist(Elt.getNode()); 9290 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 9291 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 9292 DCI.AddToWorklist(Srl.getNode()); 9293 9294 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 9295 DCI.AddToWorklist(Trunc.getNode()); 9296 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 9297 } 9298 9299 return SDValue(); 9300 } 9301 9302 SDValue 9303 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 9304 DAGCombinerInfo &DCI) const { 9305 SDValue Vec = N->getOperand(0); 9306 SDValue Idx = N->getOperand(2); 9307 EVT VecVT = Vec.getValueType(); 9308 EVT EltVT = VecVT.getVectorElementType(); 9309 unsigned VecSize = VecVT.getSizeInBits(); 9310 unsigned EltSize = EltVT.getSizeInBits(); 9311 9312 // INSERT_VECTOR_ELT (<n x e>, var-idx) 9313 // => BUILD_VECTOR n x select (e, const-idx) 9314 // This elminates non-constant index and subsequent movrel or scratch access. 9315 // Sub-dword vectors of size 2 dword or less have better implementation. 9316 // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32 9317 // instructions. 9318 if (isa<ConstantSDNode>(Idx) || 9319 VecSize > 256 || (VecSize <= 64 && EltSize < 32)) 9320 return SDValue(); 9321 9322 SelectionDAG &DAG = DCI.DAG; 9323 SDLoc SL(N); 9324 SDValue Ins = N->getOperand(1); 9325 EVT IdxVT = Idx.getValueType(); 9326 9327 SmallVector<SDValue, 16> Ops; 9328 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 9329 SDValue IC = DAG.getConstant(I, SL, IdxVT); 9330 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 9331 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 9332 Ops.push_back(V); 9333 } 9334 9335 return DAG.getBuildVector(VecVT, SL, Ops); 9336 } 9337 9338 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 9339 const SDNode *N0, 9340 const SDNode *N1) const { 9341 EVT VT = N0->getValueType(0); 9342 9343 // Only do this if we are not trying to support denormals. v_mad_f32 does not 9344 // support denormals ever. 9345 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 9346 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 9347 getSubtarget()->hasMadF16())) && 9348 isOperationLegal(ISD::FMAD, VT)) 9349 return ISD::FMAD; 9350 9351 const TargetOptions &Options = DAG.getTarget().Options; 9352 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9353 (N0->getFlags().hasAllowContract() && 9354 N1->getFlags().hasAllowContract())) && 9355 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 9356 return ISD::FMA; 9357 } 9358 9359 return 0; 9360 } 9361 9362 // For a reassociatable opcode perform: 9363 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 9364 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 9365 SelectionDAG &DAG) const { 9366 EVT VT = N->getValueType(0); 9367 if (VT != MVT::i32 && VT != MVT::i64) 9368 return SDValue(); 9369 9370 unsigned Opc = N->getOpcode(); 9371 SDValue Op0 = N->getOperand(0); 9372 SDValue Op1 = N->getOperand(1); 9373 9374 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 9375 return SDValue(); 9376 9377 if (Op0->isDivergent()) 9378 std::swap(Op0, Op1); 9379 9380 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 9381 return SDValue(); 9382 9383 SDValue Op2 = Op1.getOperand(1); 9384 Op1 = Op1.getOperand(0); 9385 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 9386 return SDValue(); 9387 9388 if (Op1->isDivergent()) 9389 std::swap(Op1, Op2); 9390 9391 // If either operand is constant this will conflict with 9392 // DAGCombiner::ReassociateOps(). 9393 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 9394 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 9395 return SDValue(); 9396 9397 SDLoc SL(N); 9398 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 9399 return DAG.getNode(Opc, SL, VT, Add1, Op2); 9400 } 9401 9402 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 9403 EVT VT, 9404 SDValue N0, SDValue N1, SDValue N2, 9405 bool Signed) { 9406 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 9407 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 9408 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 9409 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 9410 } 9411 9412 SDValue SITargetLowering::performAddCombine(SDNode *N, 9413 DAGCombinerInfo &DCI) const { 9414 SelectionDAG &DAG = DCI.DAG; 9415 EVT VT = N->getValueType(0); 9416 SDLoc SL(N); 9417 SDValue LHS = N->getOperand(0); 9418 SDValue RHS = N->getOperand(1); 9419 9420 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 9421 && Subtarget->hasMad64_32() && 9422 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 9423 VT.getScalarSizeInBits() <= 64) { 9424 if (LHS.getOpcode() != ISD::MUL) 9425 std::swap(LHS, RHS); 9426 9427 SDValue MulLHS = LHS.getOperand(0); 9428 SDValue MulRHS = LHS.getOperand(1); 9429 SDValue AddRHS = RHS; 9430 9431 // TODO: Maybe restrict if SGPR inputs. 9432 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 9433 numBitsUnsigned(MulRHS, DAG) <= 32) { 9434 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 9435 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 9436 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 9437 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 9438 } 9439 9440 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 9441 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 9442 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 9443 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 9444 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 9445 } 9446 9447 return SDValue(); 9448 } 9449 9450 if (SDValue V = reassociateScalarOps(N, DAG)) { 9451 return V; 9452 } 9453 9454 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 9455 return SDValue(); 9456 9457 // add x, zext (setcc) => addcarry x, 0, setcc 9458 // add x, sext (setcc) => subcarry x, 0, setcc 9459 unsigned Opc = LHS.getOpcode(); 9460 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 9461 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 9462 std::swap(RHS, LHS); 9463 9464 Opc = RHS.getOpcode(); 9465 switch (Opc) { 9466 default: break; 9467 case ISD::ZERO_EXTEND: 9468 case ISD::SIGN_EXTEND: 9469 case ISD::ANY_EXTEND: { 9470 auto Cond = RHS.getOperand(0); 9471 // If this won't be a real VOPC output, we would still need to insert an 9472 // extra instruction anyway. 9473 if (!isBoolSGPR(Cond)) 9474 break; 9475 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9476 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9477 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 9478 return DAG.getNode(Opc, SL, VTList, Args); 9479 } 9480 case ISD::ADDCARRY: { 9481 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 9482 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9483 if (!C || C->getZExtValue() != 0) break; 9484 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 9485 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 9486 } 9487 } 9488 return SDValue(); 9489 } 9490 9491 SDValue SITargetLowering::performSubCombine(SDNode *N, 9492 DAGCombinerInfo &DCI) const { 9493 SelectionDAG &DAG = DCI.DAG; 9494 EVT VT = N->getValueType(0); 9495 9496 if (VT != MVT::i32) 9497 return SDValue(); 9498 9499 SDLoc SL(N); 9500 SDValue LHS = N->getOperand(0); 9501 SDValue RHS = N->getOperand(1); 9502 9503 // sub x, zext (setcc) => subcarry x, 0, setcc 9504 // sub x, sext (setcc) => addcarry x, 0, setcc 9505 unsigned Opc = RHS.getOpcode(); 9506 switch (Opc) { 9507 default: break; 9508 case ISD::ZERO_EXTEND: 9509 case ISD::SIGN_EXTEND: 9510 case ISD::ANY_EXTEND: { 9511 auto Cond = RHS.getOperand(0); 9512 // If this won't be a real VOPC output, we would still need to insert an 9513 // extra instruction anyway. 9514 if (!isBoolSGPR(Cond)) 9515 break; 9516 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 9517 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 9518 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 9519 return DAG.getNode(Opc, SL, VTList, Args); 9520 } 9521 } 9522 9523 if (LHS.getOpcode() == ISD::SUBCARRY) { 9524 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 9525 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9526 if (!C || !C->isNullValue()) 9527 return SDValue(); 9528 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 9529 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 9530 } 9531 return SDValue(); 9532 } 9533 9534 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 9535 DAGCombinerInfo &DCI) const { 9536 9537 if (N->getValueType(0) != MVT::i32) 9538 return SDValue(); 9539 9540 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9541 if (!C || C->getZExtValue() != 0) 9542 return SDValue(); 9543 9544 SelectionDAG &DAG = DCI.DAG; 9545 SDValue LHS = N->getOperand(0); 9546 9547 // addcarry (add x, y), 0, cc => addcarry x, y, cc 9548 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 9549 unsigned LHSOpc = LHS.getOpcode(); 9550 unsigned Opc = N->getOpcode(); 9551 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 9552 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 9553 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 9554 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 9555 } 9556 return SDValue(); 9557 } 9558 9559 SDValue SITargetLowering::performFAddCombine(SDNode *N, 9560 DAGCombinerInfo &DCI) const { 9561 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9562 return SDValue(); 9563 9564 SelectionDAG &DAG = DCI.DAG; 9565 EVT VT = N->getValueType(0); 9566 9567 SDLoc SL(N); 9568 SDValue LHS = N->getOperand(0); 9569 SDValue RHS = N->getOperand(1); 9570 9571 // These should really be instruction patterns, but writing patterns with 9572 // source modiifiers is a pain. 9573 9574 // fadd (fadd (a, a), b) -> mad 2.0, a, b 9575 if (LHS.getOpcode() == ISD::FADD) { 9576 SDValue A = LHS.getOperand(0); 9577 if (A == LHS.getOperand(1)) { 9578 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9579 if (FusedOp != 0) { 9580 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9581 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 9582 } 9583 } 9584 } 9585 9586 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 9587 if (RHS.getOpcode() == ISD::FADD) { 9588 SDValue A = RHS.getOperand(0); 9589 if (A == RHS.getOperand(1)) { 9590 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9591 if (FusedOp != 0) { 9592 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9593 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 9594 } 9595 } 9596 } 9597 9598 return SDValue(); 9599 } 9600 9601 SDValue SITargetLowering::performFSubCombine(SDNode *N, 9602 DAGCombinerInfo &DCI) const { 9603 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9604 return SDValue(); 9605 9606 SelectionDAG &DAG = DCI.DAG; 9607 SDLoc SL(N); 9608 EVT VT = N->getValueType(0); 9609 assert(!VT.isVector()); 9610 9611 // Try to get the fneg to fold into the source modifier. This undoes generic 9612 // DAG combines and folds them into the mad. 9613 // 9614 // Only do this if we are not trying to support denormals. v_mad_f32 does 9615 // not support denormals ever. 9616 SDValue LHS = N->getOperand(0); 9617 SDValue RHS = N->getOperand(1); 9618 if (LHS.getOpcode() == ISD::FADD) { 9619 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 9620 SDValue A = LHS.getOperand(0); 9621 if (A == LHS.getOperand(1)) { 9622 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 9623 if (FusedOp != 0){ 9624 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 9625 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 9626 9627 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 9628 } 9629 } 9630 } 9631 9632 if (RHS.getOpcode() == ISD::FADD) { 9633 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 9634 9635 SDValue A = RHS.getOperand(0); 9636 if (A == RHS.getOperand(1)) { 9637 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 9638 if (FusedOp != 0){ 9639 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 9640 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 9641 } 9642 } 9643 } 9644 9645 return SDValue(); 9646 } 9647 9648 SDValue SITargetLowering::performFMACombine(SDNode *N, 9649 DAGCombinerInfo &DCI) const { 9650 SelectionDAG &DAG = DCI.DAG; 9651 EVT VT = N->getValueType(0); 9652 SDLoc SL(N); 9653 9654 if (!Subtarget->hasDot2Insts() || VT != MVT::f32) 9655 return SDValue(); 9656 9657 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 9658 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 9659 SDValue Op1 = N->getOperand(0); 9660 SDValue Op2 = N->getOperand(1); 9661 SDValue FMA = N->getOperand(2); 9662 9663 if (FMA.getOpcode() != ISD::FMA || 9664 Op1.getOpcode() != ISD::FP_EXTEND || 9665 Op2.getOpcode() != ISD::FP_EXTEND) 9666 return SDValue(); 9667 9668 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 9669 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 9670 // is sufficient to allow generaing fdot2. 9671 const TargetOptions &Options = DAG.getTarget().Options; 9672 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 9673 (N->getFlags().hasAllowContract() && 9674 FMA->getFlags().hasAllowContract())) { 9675 Op1 = Op1.getOperand(0); 9676 Op2 = Op2.getOperand(0); 9677 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9678 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9679 return SDValue(); 9680 9681 SDValue Vec1 = Op1.getOperand(0); 9682 SDValue Idx1 = Op1.getOperand(1); 9683 SDValue Vec2 = Op2.getOperand(0); 9684 9685 SDValue FMAOp1 = FMA.getOperand(0); 9686 SDValue FMAOp2 = FMA.getOperand(1); 9687 SDValue FMAAcc = FMA.getOperand(2); 9688 9689 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 9690 FMAOp2.getOpcode() != ISD::FP_EXTEND) 9691 return SDValue(); 9692 9693 FMAOp1 = FMAOp1.getOperand(0); 9694 FMAOp2 = FMAOp2.getOperand(0); 9695 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9696 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9697 return SDValue(); 9698 9699 SDValue Vec3 = FMAOp1.getOperand(0); 9700 SDValue Vec4 = FMAOp2.getOperand(0); 9701 SDValue Idx2 = FMAOp1.getOperand(1); 9702 9703 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 9704 // Idx1 and Idx2 cannot be the same. 9705 Idx1 == Idx2) 9706 return SDValue(); 9707 9708 if (Vec1 == Vec2 || Vec3 == Vec4) 9709 return SDValue(); 9710 9711 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 9712 return SDValue(); 9713 9714 if ((Vec1 == Vec3 && Vec2 == Vec4) || 9715 (Vec1 == Vec4 && Vec2 == Vec3)) { 9716 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 9717 DAG.getTargetConstant(0, SL, MVT::i1)); 9718 } 9719 } 9720 return SDValue(); 9721 } 9722 9723 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 9724 DAGCombinerInfo &DCI) const { 9725 SelectionDAG &DAG = DCI.DAG; 9726 SDLoc SL(N); 9727 9728 SDValue LHS = N->getOperand(0); 9729 SDValue RHS = N->getOperand(1); 9730 EVT VT = LHS.getValueType(); 9731 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 9732 9733 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 9734 if (!CRHS) { 9735 CRHS = dyn_cast<ConstantSDNode>(LHS); 9736 if (CRHS) { 9737 std::swap(LHS, RHS); 9738 CC = getSetCCSwappedOperands(CC); 9739 } 9740 } 9741 9742 if (CRHS) { 9743 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 9744 isBoolSGPR(LHS.getOperand(0))) { 9745 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 9746 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 9747 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 9748 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 9749 if ((CRHS->isAllOnesValue() && 9750 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 9751 (CRHS->isNullValue() && 9752 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 9753 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9754 DAG.getConstant(-1, SL, MVT::i1)); 9755 if ((CRHS->isAllOnesValue() && 9756 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 9757 (CRHS->isNullValue() && 9758 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 9759 return LHS.getOperand(0); 9760 } 9761 9762 uint64_t CRHSVal = CRHS->getZExtValue(); 9763 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 9764 LHS.getOpcode() == ISD::SELECT && 9765 isa<ConstantSDNode>(LHS.getOperand(1)) && 9766 isa<ConstantSDNode>(LHS.getOperand(2)) && 9767 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 9768 isBoolSGPR(LHS.getOperand(0))) { 9769 // Given CT != FT: 9770 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 9771 // setcc (select cc, CT, CF), CF, ne => cc 9772 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 9773 // setcc (select cc, CT, CF), CT, eq => cc 9774 uint64_t CT = LHS.getConstantOperandVal(1); 9775 uint64_t CF = LHS.getConstantOperandVal(2); 9776 9777 if ((CF == CRHSVal && CC == ISD::SETEQ) || 9778 (CT == CRHSVal && CC == ISD::SETNE)) 9779 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 9780 DAG.getConstant(-1, SL, MVT::i1)); 9781 if ((CF == CRHSVal && CC == ISD::SETNE) || 9782 (CT == CRHSVal && CC == ISD::SETEQ)) 9783 return LHS.getOperand(0); 9784 } 9785 } 9786 9787 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 9788 VT != MVT::f16)) 9789 return SDValue(); 9790 9791 // Match isinf/isfinite pattern 9792 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 9793 // (fcmp one (fabs x), inf) -> (fp_class x, 9794 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 9795 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 9796 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 9797 if (!CRHS) 9798 return SDValue(); 9799 9800 const APFloat &APF = CRHS->getValueAPF(); 9801 if (APF.isInfinity() && !APF.isNegative()) { 9802 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 9803 SIInstrFlags::N_INFINITY; 9804 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 9805 SIInstrFlags::P_ZERO | 9806 SIInstrFlags::N_NORMAL | 9807 SIInstrFlags::P_NORMAL | 9808 SIInstrFlags::N_SUBNORMAL | 9809 SIInstrFlags::P_SUBNORMAL; 9810 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 9811 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 9812 DAG.getConstant(Mask, SL, MVT::i32)); 9813 } 9814 } 9815 9816 return SDValue(); 9817 } 9818 9819 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 9820 DAGCombinerInfo &DCI) const { 9821 SelectionDAG &DAG = DCI.DAG; 9822 SDLoc SL(N); 9823 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 9824 9825 SDValue Src = N->getOperand(0); 9826 SDValue Srl = N->getOperand(0); 9827 if (Srl.getOpcode() == ISD::ZERO_EXTEND) 9828 Srl = Srl.getOperand(0); 9829 9830 // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero. 9831 if (Srl.getOpcode() == ISD::SRL) { 9832 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 9833 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 9834 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 9835 9836 if (const ConstantSDNode *C = 9837 dyn_cast<ConstantSDNode>(Srl.getOperand(1))) { 9838 Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)), 9839 EVT(MVT::i32)); 9840 9841 unsigned SrcOffset = C->getZExtValue() + 8 * Offset; 9842 if (SrcOffset < 32 && SrcOffset % 8 == 0) { 9843 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL, 9844 MVT::f32, Srl); 9845 } 9846 } 9847 } 9848 9849 APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 9850 9851 KnownBits Known; 9852 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 9853 !DCI.isBeforeLegalizeOps()); 9854 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9855 if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) { 9856 DCI.CommitTargetLoweringOpt(TLO); 9857 } 9858 9859 return SDValue(); 9860 } 9861 9862 SDValue SITargetLowering::performClampCombine(SDNode *N, 9863 DAGCombinerInfo &DCI) const { 9864 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 9865 if (!CSrc) 9866 return SDValue(); 9867 9868 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 9869 const APFloat &F = CSrc->getValueAPF(); 9870 APFloat Zero = APFloat::getZero(F.getSemantics()); 9871 APFloat::cmpResult Cmp0 = F.compare(Zero); 9872 if (Cmp0 == APFloat::cmpLessThan || 9873 (Cmp0 == APFloat::cmpUnordered && 9874 MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 9875 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 9876 } 9877 9878 APFloat One(F.getSemantics(), "1.0"); 9879 APFloat::cmpResult Cmp1 = F.compare(One); 9880 if (Cmp1 == APFloat::cmpGreaterThan) 9881 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 9882 9883 return SDValue(CSrc, 0); 9884 } 9885 9886 9887 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 9888 DAGCombinerInfo &DCI) const { 9889 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 9890 return SDValue(); 9891 switch (N->getOpcode()) { 9892 default: 9893 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 9894 case ISD::ADD: 9895 return performAddCombine(N, DCI); 9896 case ISD::SUB: 9897 return performSubCombine(N, DCI); 9898 case ISD::ADDCARRY: 9899 case ISD::SUBCARRY: 9900 return performAddCarrySubCarryCombine(N, DCI); 9901 case ISD::FADD: 9902 return performFAddCombine(N, DCI); 9903 case ISD::FSUB: 9904 return performFSubCombine(N, DCI); 9905 case ISD::SETCC: 9906 return performSetCCCombine(N, DCI); 9907 case ISD::FMAXNUM: 9908 case ISD::FMINNUM: 9909 case ISD::FMAXNUM_IEEE: 9910 case ISD::FMINNUM_IEEE: 9911 case ISD::SMAX: 9912 case ISD::SMIN: 9913 case ISD::UMAX: 9914 case ISD::UMIN: 9915 case AMDGPUISD::FMIN_LEGACY: 9916 case AMDGPUISD::FMAX_LEGACY: 9917 return performMinMaxCombine(N, DCI); 9918 case ISD::FMA: 9919 return performFMACombine(N, DCI); 9920 case ISD::LOAD: { 9921 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 9922 return Widended; 9923 LLVM_FALLTHROUGH; 9924 } 9925 case ISD::STORE: 9926 case ISD::ATOMIC_LOAD: 9927 case ISD::ATOMIC_STORE: 9928 case ISD::ATOMIC_CMP_SWAP: 9929 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: 9930 case ISD::ATOMIC_SWAP: 9931 case ISD::ATOMIC_LOAD_ADD: 9932 case ISD::ATOMIC_LOAD_SUB: 9933 case ISD::ATOMIC_LOAD_AND: 9934 case ISD::ATOMIC_LOAD_OR: 9935 case ISD::ATOMIC_LOAD_XOR: 9936 case ISD::ATOMIC_LOAD_NAND: 9937 case ISD::ATOMIC_LOAD_MIN: 9938 case ISD::ATOMIC_LOAD_MAX: 9939 case ISD::ATOMIC_LOAD_UMIN: 9940 case ISD::ATOMIC_LOAD_UMAX: 9941 case ISD::ATOMIC_LOAD_FADD: 9942 case AMDGPUISD::ATOMIC_INC: 9943 case AMDGPUISD::ATOMIC_DEC: 9944 case AMDGPUISD::ATOMIC_LOAD_FMIN: 9945 case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics. 9946 if (DCI.isBeforeLegalize()) 9947 break; 9948 return performMemSDNodeCombine(cast<MemSDNode>(N), DCI); 9949 case ISD::AND: 9950 return performAndCombine(N, DCI); 9951 case ISD::OR: 9952 return performOrCombine(N, DCI); 9953 case ISD::XOR: 9954 return performXorCombine(N, DCI); 9955 case ISD::ZERO_EXTEND: 9956 return performZeroExtendCombine(N, DCI); 9957 case ISD::SIGN_EXTEND_INREG: 9958 return performSignExtendInRegCombine(N , DCI); 9959 case AMDGPUISD::FP_CLASS: 9960 return performClassCombine(N, DCI); 9961 case ISD::FCANONICALIZE: 9962 return performFCanonicalizeCombine(N, DCI); 9963 case AMDGPUISD::RCP: 9964 return performRcpCombine(N, DCI); 9965 case AMDGPUISD::FRACT: 9966 case AMDGPUISD::RSQ: 9967 case AMDGPUISD::RCP_LEGACY: 9968 case AMDGPUISD::RSQ_LEGACY: 9969 case AMDGPUISD::RCP_IFLAG: 9970 case AMDGPUISD::RSQ_CLAMP: 9971 case AMDGPUISD::LDEXP: { 9972 SDValue Src = N->getOperand(0); 9973 if (Src.isUndef()) 9974 return Src; 9975 break; 9976 } 9977 case ISD::SINT_TO_FP: 9978 case ISD::UINT_TO_FP: 9979 return performUCharToFloatCombine(N, DCI); 9980 case AMDGPUISD::CVT_F32_UBYTE0: 9981 case AMDGPUISD::CVT_F32_UBYTE1: 9982 case AMDGPUISD::CVT_F32_UBYTE2: 9983 case AMDGPUISD::CVT_F32_UBYTE3: 9984 return performCvtF32UByteNCombine(N, DCI); 9985 case AMDGPUISD::FMED3: 9986 return performFMed3Combine(N, DCI); 9987 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9988 return performCvtPkRTZCombine(N, DCI); 9989 case AMDGPUISD::CLAMP: 9990 return performClampCombine(N, DCI); 9991 case ISD::SCALAR_TO_VECTOR: { 9992 SelectionDAG &DAG = DCI.DAG; 9993 EVT VT = N->getValueType(0); 9994 9995 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 9996 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 9997 SDLoc SL(N); 9998 SDValue Src = N->getOperand(0); 9999 EVT EltVT = Src.getValueType(); 10000 if (EltVT == MVT::f16) 10001 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10002 10003 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10004 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10005 } 10006 10007 break; 10008 } 10009 case ISD::EXTRACT_VECTOR_ELT: 10010 return performExtractVectorEltCombine(N, DCI); 10011 case ISD::INSERT_VECTOR_ELT: 10012 return performInsertVectorEltCombine(N, DCI); 10013 } 10014 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10015 } 10016 10017 /// Helper function for adjustWritemask 10018 static unsigned SubIdx2Lane(unsigned Idx) { 10019 switch (Idx) { 10020 default: return 0; 10021 case AMDGPU::sub0: return 0; 10022 case AMDGPU::sub1: return 1; 10023 case AMDGPU::sub2: return 2; 10024 case AMDGPU::sub3: return 3; 10025 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10026 } 10027 } 10028 10029 /// Adjust the writemask of MIMG instructions 10030 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10031 SelectionDAG &DAG) const { 10032 unsigned Opcode = Node->getMachineOpcode(); 10033 10034 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10035 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10036 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10037 return Node; // not implemented for D16 10038 10039 SDNode *Users[5] = { nullptr }; 10040 unsigned Lane = 0; 10041 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10042 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10043 unsigned NewDmask = 0; 10044 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10045 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10046 bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) || 10047 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10048 unsigned TFCLane = 0; 10049 bool HasChain = Node->getNumValues() > 1; 10050 10051 if (OldDmask == 0) { 10052 // These are folded out, but on the chance it happens don't assert. 10053 return Node; 10054 } 10055 10056 unsigned OldBitsSet = countPopulation(OldDmask); 10057 // Work out which is the TFE/LWE lane if that is enabled. 10058 if (UsesTFC) { 10059 TFCLane = OldBitsSet; 10060 } 10061 10062 // Try to figure out the used register components 10063 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10064 I != E; ++I) { 10065 10066 // Don't look at users of the chain. 10067 if (I.getUse().getResNo() != 0) 10068 continue; 10069 10070 // Abort if we can't understand the usage 10071 if (!I->isMachineOpcode() || 10072 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10073 return Node; 10074 10075 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10076 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10077 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10078 // set, etc. 10079 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10080 10081 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10082 if (UsesTFC && Lane == TFCLane) { 10083 Users[Lane] = *I; 10084 } else { 10085 // Set which texture component corresponds to the lane. 10086 unsigned Comp; 10087 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10088 Comp = countTrailingZeros(Dmask); 10089 Dmask &= ~(1 << Comp); 10090 } 10091 10092 // Abort if we have more than one user per component. 10093 if (Users[Lane]) 10094 return Node; 10095 10096 Users[Lane] = *I; 10097 NewDmask |= 1 << Comp; 10098 } 10099 } 10100 10101 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10102 bool NoChannels = !NewDmask; 10103 if (NoChannels) { 10104 if (!UsesTFC) { 10105 // No uses of the result and not using TFC. Then do nothing. 10106 return Node; 10107 } 10108 // If the original dmask has one channel - then nothing to do 10109 if (OldBitsSet == 1) 10110 return Node; 10111 // Use an arbitrary dmask - required for the instruction to work 10112 NewDmask = 1; 10113 } 10114 // Abort if there's no change 10115 if (NewDmask == OldDmask) 10116 return Node; 10117 10118 unsigned BitsSet = countPopulation(NewDmask); 10119 10120 // Check for TFE or LWE - increase the number of channels by one to account 10121 // for the extra return value 10122 // This will need adjustment for D16 if this is also included in 10123 // adjustWriteMask (this function) but at present D16 are excluded. 10124 unsigned NewChannels = BitsSet + UsesTFC; 10125 10126 int NewOpcode = 10127 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10128 assert(NewOpcode != -1 && 10129 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10130 "failed to find equivalent MIMG op"); 10131 10132 // Adjust the writemask in the node 10133 SmallVector<SDValue, 12> Ops; 10134 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10135 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10136 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10137 10138 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10139 10140 MVT ResultVT = NewChannels == 1 ? 10141 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10142 NewChannels == 5 ? 8 : NewChannels); 10143 SDVTList NewVTList = HasChain ? 10144 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10145 10146 10147 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10148 NewVTList, Ops); 10149 10150 if (HasChain) { 10151 // Update chain. 10152 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10153 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10154 } 10155 10156 if (NewChannels == 1) { 10157 assert(Node->hasNUsesOfValue(1, 0)); 10158 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10159 SDLoc(Node), Users[Lane]->getValueType(0), 10160 SDValue(NewNode, 0)); 10161 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10162 return nullptr; 10163 } 10164 10165 // Update the users of the node with the new indices 10166 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10167 SDNode *User = Users[i]; 10168 if (!User) { 10169 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 10170 // Users[0] is still nullptr because channel 0 doesn't really have a use. 10171 if (i || !NoChannels) 10172 continue; 10173 } else { 10174 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 10175 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 10176 } 10177 10178 switch (Idx) { 10179 default: break; 10180 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 10181 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 10182 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 10183 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 10184 } 10185 } 10186 10187 DAG.RemoveDeadNode(Node); 10188 return nullptr; 10189 } 10190 10191 static bool isFrameIndexOp(SDValue Op) { 10192 if (Op.getOpcode() == ISD::AssertZext) 10193 Op = Op.getOperand(0); 10194 10195 return isa<FrameIndexSDNode>(Op); 10196 } 10197 10198 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 10199 /// with frame index operands. 10200 /// LLVM assumes that inputs are to these instructions are registers. 10201 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 10202 SelectionDAG &DAG) const { 10203 if (Node->getOpcode() == ISD::CopyToReg) { 10204 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 10205 SDValue SrcVal = Node->getOperand(2); 10206 10207 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 10208 // to try understanding copies to physical registers. 10209 if (SrcVal.getValueType() == MVT::i1 && 10210 Register::isPhysicalRegister(DestReg->getReg())) { 10211 SDLoc SL(Node); 10212 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10213 SDValue VReg = DAG.getRegister( 10214 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 10215 10216 SDNode *Glued = Node->getGluedNode(); 10217 SDValue ToVReg 10218 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 10219 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 10220 SDValue ToResultReg 10221 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 10222 VReg, ToVReg.getValue(1)); 10223 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 10224 DAG.RemoveDeadNode(Node); 10225 return ToResultReg.getNode(); 10226 } 10227 } 10228 10229 SmallVector<SDValue, 8> Ops; 10230 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 10231 if (!isFrameIndexOp(Node->getOperand(i))) { 10232 Ops.push_back(Node->getOperand(i)); 10233 continue; 10234 } 10235 10236 SDLoc DL(Node); 10237 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 10238 Node->getOperand(i).getValueType(), 10239 Node->getOperand(i)), 0)); 10240 } 10241 10242 return DAG.UpdateNodeOperands(Node, Ops); 10243 } 10244 10245 /// Fold the instructions after selecting them. 10246 /// Returns null if users were already updated. 10247 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 10248 SelectionDAG &DAG) const { 10249 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10250 unsigned Opcode = Node->getMachineOpcode(); 10251 10252 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 10253 !TII->isGather4(Opcode)) { 10254 return adjustWritemask(Node, DAG); 10255 } 10256 10257 if (Opcode == AMDGPU::INSERT_SUBREG || 10258 Opcode == AMDGPU::REG_SEQUENCE) { 10259 legalizeTargetIndependentNode(Node, DAG); 10260 return Node; 10261 } 10262 10263 switch (Opcode) { 10264 case AMDGPU::V_DIV_SCALE_F32: 10265 case AMDGPU::V_DIV_SCALE_F64: { 10266 // Satisfy the operand register constraint when one of the inputs is 10267 // undefined. Ordinarily each undef value will have its own implicit_def of 10268 // a vreg, so force these to use a single register. 10269 SDValue Src0 = Node->getOperand(0); 10270 SDValue Src1 = Node->getOperand(1); 10271 SDValue Src2 = Node->getOperand(2); 10272 10273 if ((Src0.isMachineOpcode() && 10274 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 10275 (Src0 == Src1 || Src0 == Src2)) 10276 break; 10277 10278 MVT VT = Src0.getValueType().getSimpleVT(); 10279 const TargetRegisterClass *RC = 10280 getRegClassFor(VT, Src0.getNode()->isDivergent()); 10281 10282 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 10283 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 10284 10285 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 10286 UndefReg, Src0, SDValue()); 10287 10288 // src0 must be the same register as src1 or src2, even if the value is 10289 // undefined, so make sure we don't violate this constraint. 10290 if (Src0.isMachineOpcode() && 10291 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 10292 if (Src1.isMachineOpcode() && 10293 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10294 Src0 = Src1; 10295 else if (Src2.isMachineOpcode() && 10296 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 10297 Src0 = Src2; 10298 else { 10299 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 10300 Src0 = UndefReg; 10301 Src1 = UndefReg; 10302 } 10303 } else 10304 break; 10305 10306 SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 }; 10307 for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I) 10308 Ops.push_back(Node->getOperand(I)); 10309 10310 Ops.push_back(ImpDef.getValue(1)); 10311 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 10312 } 10313 default: 10314 break; 10315 } 10316 10317 return Node; 10318 } 10319 10320 /// Assign the register class depending on the number of 10321 /// bits set in the writemask 10322 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10323 SDNode *Node) const { 10324 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10325 10326 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 10327 10328 if (TII->isVOP3(MI.getOpcode())) { 10329 // Make sure constant bus requirements are respected. 10330 TII->legalizeOperandsVOP3(MRI, MI); 10331 10332 // Prefer VGPRs over AGPRs in mAI instructions where possible. 10333 // This saves a chain-copy of registers and better ballance register 10334 // use between vgpr and agpr as agpr tuples tend to be big. 10335 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 10336 unsigned Opc = MI.getOpcode(); 10337 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10338 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 10339 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 10340 if (I == -1) 10341 break; 10342 MachineOperand &Op = MI.getOperand(I); 10343 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 10344 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 10345 !Register::isVirtualRegister(Op.getReg()) || 10346 !TRI->isAGPR(MRI, Op.getReg())) 10347 continue; 10348 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 10349 if (!Src || !Src->isCopy() || 10350 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 10351 continue; 10352 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 10353 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 10354 // All uses of agpr64 and agpr32 can also accept vgpr except for 10355 // v_accvgpr_read, but we do not produce agpr reads during selection, 10356 // so no use checks are needed. 10357 MRI.setRegClass(Op.getReg(), NewRC); 10358 } 10359 } 10360 10361 return; 10362 } 10363 10364 // Replace unused atomics with the no return version. 10365 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 10366 if (NoRetAtomicOp != -1) { 10367 if (!Node->hasAnyUseOfValue(0)) { 10368 MI.setDesc(TII->get(NoRetAtomicOp)); 10369 MI.RemoveOperand(0); 10370 return; 10371 } 10372 10373 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 10374 // instruction, because the return type of these instructions is a vec2 of 10375 // the memory type, so it can be tied to the input operand. 10376 // This means these instructions always have a use, so we need to add a 10377 // special case to check if the atomic has only one extract_subreg use, 10378 // which itself has no uses. 10379 if ((Node->hasNUsesOfValue(1, 0) && 10380 Node->use_begin()->isMachineOpcode() && 10381 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 10382 !Node->use_begin()->hasAnyUseOfValue(0))) { 10383 Register Def = MI.getOperand(0).getReg(); 10384 10385 // Change this into a noret atomic. 10386 MI.setDesc(TII->get(NoRetAtomicOp)); 10387 MI.RemoveOperand(0); 10388 10389 // If we only remove the def operand from the atomic instruction, the 10390 // extract_subreg will be left with a use of a vreg without a def. 10391 // So we need to insert an implicit_def to avoid machine verifier 10392 // errors. 10393 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 10394 TII->get(AMDGPU::IMPLICIT_DEF), Def); 10395 } 10396 return; 10397 } 10398 } 10399 10400 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 10401 uint64_t Val) { 10402 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 10403 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 10404 } 10405 10406 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 10407 const SDLoc &DL, 10408 SDValue Ptr) const { 10409 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10410 10411 // Build the half of the subregister with the constants before building the 10412 // full 128-bit register. If we are building multiple resource descriptors, 10413 // this will allow CSEing of the 2-component register. 10414 const SDValue Ops0[] = { 10415 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 10416 buildSMovImm32(DAG, DL, 0), 10417 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10418 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 10419 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 10420 }; 10421 10422 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 10423 MVT::v2i32, Ops0), 0); 10424 10425 // Combine the constants and the pointer. 10426 const SDValue Ops1[] = { 10427 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10428 Ptr, 10429 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 10430 SubRegHi, 10431 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 10432 }; 10433 10434 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 10435 } 10436 10437 /// Return a resource descriptor with the 'Add TID' bit enabled 10438 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 10439 /// of the resource descriptor) to create an offset, which is added to 10440 /// the resource pointer. 10441 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 10442 SDValue Ptr, uint32_t RsrcDword1, 10443 uint64_t RsrcDword2And3) const { 10444 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 10445 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 10446 if (RsrcDword1) { 10447 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 10448 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 10449 0); 10450 } 10451 10452 SDValue DataLo = buildSMovImm32(DAG, DL, 10453 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 10454 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 10455 10456 const SDValue Ops[] = { 10457 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 10458 PtrLo, 10459 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 10460 PtrHi, 10461 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 10462 DataLo, 10463 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 10464 DataHi, 10465 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 10466 }; 10467 10468 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 10469 } 10470 10471 //===----------------------------------------------------------------------===// 10472 // SI Inline Assembly Support 10473 //===----------------------------------------------------------------------===// 10474 10475 std::pair<unsigned, const TargetRegisterClass *> 10476 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 10477 StringRef Constraint, 10478 MVT VT) const { 10479 const TargetRegisterClass *RC = nullptr; 10480 if (Constraint.size() == 1) { 10481 switch (Constraint[0]) { 10482 default: 10483 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10484 case 's': 10485 case 'r': 10486 switch (VT.getSizeInBits()) { 10487 default: 10488 return std::make_pair(0U, nullptr); 10489 case 32: 10490 case 16: 10491 RC = &AMDGPU::SReg_32RegClass; 10492 break; 10493 case 64: 10494 RC = &AMDGPU::SGPR_64RegClass; 10495 break; 10496 case 96: 10497 RC = &AMDGPU::SReg_96RegClass; 10498 break; 10499 case 128: 10500 RC = &AMDGPU::SGPR_128RegClass; 10501 break; 10502 case 160: 10503 RC = &AMDGPU::SReg_160RegClass; 10504 break; 10505 case 256: 10506 RC = &AMDGPU::SReg_256RegClass; 10507 break; 10508 case 512: 10509 RC = &AMDGPU::SReg_512RegClass; 10510 break; 10511 } 10512 break; 10513 case 'v': 10514 switch (VT.getSizeInBits()) { 10515 default: 10516 return std::make_pair(0U, nullptr); 10517 case 32: 10518 case 16: 10519 RC = &AMDGPU::VGPR_32RegClass; 10520 break; 10521 case 64: 10522 RC = &AMDGPU::VReg_64RegClass; 10523 break; 10524 case 96: 10525 RC = &AMDGPU::VReg_96RegClass; 10526 break; 10527 case 128: 10528 RC = &AMDGPU::VReg_128RegClass; 10529 break; 10530 case 160: 10531 RC = &AMDGPU::VReg_160RegClass; 10532 break; 10533 case 256: 10534 RC = &AMDGPU::VReg_256RegClass; 10535 break; 10536 case 512: 10537 RC = &AMDGPU::VReg_512RegClass; 10538 break; 10539 } 10540 break; 10541 case 'a': 10542 if (!Subtarget->hasMAIInsts()) 10543 break; 10544 switch (VT.getSizeInBits()) { 10545 default: 10546 return std::make_pair(0U, nullptr); 10547 case 32: 10548 case 16: 10549 RC = &AMDGPU::AGPR_32RegClass; 10550 break; 10551 case 64: 10552 RC = &AMDGPU::AReg_64RegClass; 10553 break; 10554 case 128: 10555 RC = &AMDGPU::AReg_128RegClass; 10556 break; 10557 case 512: 10558 RC = &AMDGPU::AReg_512RegClass; 10559 break; 10560 case 1024: 10561 RC = &AMDGPU::AReg_1024RegClass; 10562 // v32 types are not legal but we support them here. 10563 return std::make_pair(0U, RC); 10564 } 10565 break; 10566 } 10567 // We actually support i128, i16 and f16 as inline parameters 10568 // even if they are not reported as legal 10569 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 10570 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 10571 return std::make_pair(0U, RC); 10572 } 10573 10574 if (Constraint.size() > 1) { 10575 if (Constraint[1] == 'v') { 10576 RC = &AMDGPU::VGPR_32RegClass; 10577 } else if (Constraint[1] == 's') { 10578 RC = &AMDGPU::SGPR_32RegClass; 10579 } else if (Constraint[1] == 'a') { 10580 RC = &AMDGPU::AGPR_32RegClass; 10581 } 10582 10583 if (RC) { 10584 uint32_t Idx; 10585 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 10586 if (!Failed && Idx < RC->getNumRegs()) 10587 return std::make_pair(RC->getRegister(Idx), RC); 10588 } 10589 } 10590 10591 // FIXME: Returns VS_32 for physical SGPR constraints 10592 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 10593 } 10594 10595 SITargetLowering::ConstraintType 10596 SITargetLowering::getConstraintType(StringRef Constraint) const { 10597 if (Constraint.size() == 1) { 10598 switch (Constraint[0]) { 10599 default: break; 10600 case 's': 10601 case 'v': 10602 case 'a': 10603 return C_RegisterClass; 10604 } 10605 } 10606 return TargetLowering::getConstraintType(Constraint); 10607 } 10608 10609 // Figure out which registers should be reserved for stack access. Only after 10610 // the function is legalized do we know all of the non-spill stack objects or if 10611 // calls are present. 10612 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 10613 MachineRegisterInfo &MRI = MF.getRegInfo(); 10614 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10615 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 10616 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10617 10618 if (Info->isEntryFunction()) { 10619 // Callable functions have fixed registers used for stack access. 10620 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 10621 } 10622 10623 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 10624 Info->getStackPtrOffsetReg())); 10625 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 10626 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 10627 10628 // We need to worry about replacing the default register with itself in case 10629 // of MIR testcases missing the MFI. 10630 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 10631 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 10632 10633 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 10634 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 10635 10636 if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) { 10637 MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG, 10638 Info->getScratchWaveOffsetReg()); 10639 } 10640 10641 Info->limitOccupancy(MF); 10642 10643 if (ST.isWave32() && !MF.empty()) { 10644 // Add VCC_HI def because many instructions marked as imp-use VCC where 10645 // we may only define VCC_LO. If nothing defines VCC_HI we may end up 10646 // having a use of undef. 10647 10648 const SIInstrInfo *TII = ST.getInstrInfo(); 10649 DebugLoc DL; 10650 10651 MachineBasicBlock &MBB = MF.front(); 10652 MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr(); 10653 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI); 10654 10655 for (auto &MBB : MF) { 10656 for (auto &MI : MBB) { 10657 TII->fixImplicitOperands(MI); 10658 } 10659 } 10660 } 10661 10662 TargetLoweringBase::finalizeLowering(MF); 10663 } 10664 10665 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op, 10666 KnownBits &Known, 10667 const APInt &DemandedElts, 10668 const SelectionDAG &DAG, 10669 unsigned Depth) const { 10670 TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts, 10671 DAG, Depth); 10672 10673 // Set the high bits to zero based on the maximum allowed scratch size per 10674 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 10675 // calculation won't overflow, so assume the sign bit is never set. 10676 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 10677 } 10678 10679 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 10680 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 10681 const Align CacheLineAlign = Align(64); 10682 10683 // Pre-GFX10 target did not benefit from loop alignment 10684 if (!ML || DisableLoopAlignment || 10685 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 10686 getSubtarget()->hasInstFwdPrefetchBug()) 10687 return PrefAlign; 10688 10689 // On GFX10 I$ is 4 x 64 bytes cache lines. 10690 // By default prefetcher keeps one cache line behind and reads two ahead. 10691 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 10692 // behind and one ahead. 10693 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 10694 // If loop fits 64 bytes it always spans no more than two cache lines and 10695 // does not need an alignment. 10696 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 10697 // Else if loop is less or equal 192 bytes we need two lines behind. 10698 10699 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 10700 const MachineBasicBlock *Header = ML->getHeader(); 10701 if (Header->getAlignment() != PrefAlign) 10702 return Header->getAlignment(); // Already processed. 10703 10704 unsigned LoopSize = 0; 10705 for (const MachineBasicBlock *MBB : ML->blocks()) { 10706 // If inner loop block is aligned assume in average half of the alignment 10707 // size to be added as nops. 10708 if (MBB != Header) 10709 LoopSize += MBB->getAlignment().value() / 2; 10710 10711 for (const MachineInstr &MI : *MBB) { 10712 LoopSize += TII->getInstSizeInBytes(MI); 10713 if (LoopSize > 192) 10714 return PrefAlign; 10715 } 10716 } 10717 10718 if (LoopSize <= 64) 10719 return PrefAlign; 10720 10721 if (LoopSize <= 128) 10722 return CacheLineAlign; 10723 10724 // If any of parent loops is surrounded by prefetch instructions do not 10725 // insert new for inner loop, which would reset parent's settings. 10726 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 10727 if (MachineBasicBlock *Exit = P->getExitBlock()) { 10728 auto I = Exit->getFirstNonDebugInstr(); 10729 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 10730 return CacheLineAlign; 10731 } 10732 } 10733 10734 MachineBasicBlock *Pre = ML->getLoopPreheader(); 10735 MachineBasicBlock *Exit = ML->getExitBlock(); 10736 10737 if (Pre && Exit) { 10738 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 10739 TII->get(AMDGPU::S_INST_PREFETCH)) 10740 .addImm(1); // prefetch 2 lines behind PC 10741 10742 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 10743 TII->get(AMDGPU::S_INST_PREFETCH)) 10744 .addImm(2); // prefetch 1 line behind PC 10745 } 10746 10747 return CacheLineAlign; 10748 } 10749 10750 LLVM_ATTRIBUTE_UNUSED 10751 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 10752 assert(N->getOpcode() == ISD::CopyFromReg); 10753 do { 10754 // Follow the chain until we find an INLINEASM node. 10755 N = N->getOperand(0).getNode(); 10756 if (N->getOpcode() == ISD::INLINEASM || 10757 N->getOpcode() == ISD::INLINEASM_BR) 10758 return true; 10759 } while (N->getOpcode() == ISD::CopyFromReg); 10760 return false; 10761 } 10762 10763 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N, 10764 FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const 10765 { 10766 switch (N->getOpcode()) { 10767 case ISD::CopyFromReg: 10768 { 10769 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 10770 const MachineFunction * MF = FLI->MF; 10771 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 10772 const MachineRegisterInfo &MRI = MF->getRegInfo(); 10773 const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo(); 10774 unsigned Reg = R->getReg(); 10775 if (Register::isPhysicalRegister(Reg)) 10776 return !TRI.isSGPRReg(MRI, Reg); 10777 10778 if (MRI.isLiveIn(Reg)) { 10779 // workitem.id.x workitem.id.y workitem.id.z 10780 // Any VGPR formal argument is also considered divergent 10781 if (!TRI.isSGPRReg(MRI, Reg)) 10782 return true; 10783 // Formal arguments of non-entry functions 10784 // are conservatively considered divergent 10785 else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv())) 10786 return true; 10787 return false; 10788 } 10789 const Value *V = FLI->getValueFromVirtualReg(Reg); 10790 if (V) 10791 return KDA->isDivergent(V); 10792 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 10793 return !TRI.isSGPRReg(MRI, Reg); 10794 } 10795 break; 10796 case ISD::LOAD: { 10797 const LoadSDNode *L = cast<LoadSDNode>(N); 10798 unsigned AS = L->getAddressSpace(); 10799 // A flat load may access private memory. 10800 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 10801 } break; 10802 case ISD::CALLSEQ_END: 10803 return true; 10804 break; 10805 case ISD::INTRINSIC_WO_CHAIN: 10806 { 10807 10808 } 10809 return AMDGPU::isIntrinsicSourceOfDivergence( 10810 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 10811 case ISD::INTRINSIC_W_CHAIN: 10812 return AMDGPU::isIntrinsicSourceOfDivergence( 10813 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 10814 } 10815 return false; 10816 } 10817 10818 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 10819 EVT VT) const { 10820 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 10821 case MVT::f32: 10822 return hasFP32Denormals(DAG.getMachineFunction()); 10823 case MVT::f64: 10824 case MVT::f16: 10825 return hasFP64FP16Denormals(DAG.getMachineFunction()); 10826 default: 10827 return false; 10828 } 10829 } 10830 10831 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 10832 const SelectionDAG &DAG, 10833 bool SNaN, 10834 unsigned Depth) const { 10835 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 10836 const MachineFunction &MF = DAG.getMachineFunction(); 10837 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 10838 10839 if (Info->getMode().DX10Clamp) 10840 return true; // Clamped to 0. 10841 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 10842 } 10843 10844 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 10845 SNaN, Depth); 10846 } 10847 10848 TargetLowering::AtomicExpansionKind 10849 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 10850 switch (RMW->getOperation()) { 10851 case AtomicRMWInst::FAdd: { 10852 Type *Ty = RMW->getType(); 10853 10854 // We don't have a way to support 16-bit atomics now, so just leave them 10855 // as-is. 10856 if (Ty->isHalfTy()) 10857 return AtomicExpansionKind::None; 10858 10859 if (!Ty->isFloatTy()) 10860 return AtomicExpansionKind::CmpXChg; 10861 10862 // TODO: Do have these for flat. Older targets also had them for buffers. 10863 unsigned AS = RMW->getPointerAddressSpace(); 10864 10865 if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) { 10866 return RMW->use_empty() ? AtomicExpansionKind::None : 10867 AtomicExpansionKind::CmpXChg; 10868 } 10869 10870 return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ? 10871 AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg; 10872 } 10873 default: 10874 break; 10875 } 10876 10877 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 10878 } 10879 10880 const TargetRegisterClass * 10881 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 10882 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 10883 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 10884 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 10885 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 10886 : &AMDGPU::SReg_32RegClass; 10887 if (!TRI->isSGPRClass(RC) && !isDivergent) 10888 return TRI->getEquivalentSGPRClass(RC); 10889 else if (TRI->isSGPRClass(RC) && isDivergent) 10890 return TRI->getEquivalentVGPRClass(RC); 10891 10892 return RC; 10893 } 10894 10895 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) { 10896 if (!isa<Instruction>(V)) 10897 return false; 10898 if (!Visited.insert(V).second) 10899 return false; 10900 bool Result = false; 10901 for (auto U : V->users()) { 10902 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 10903 if (V == U->getOperand(1)) { 10904 switch (Intrinsic->getIntrinsicID()) { 10905 default: 10906 Result = false; 10907 break; 10908 case Intrinsic::amdgcn_if_break: 10909 case Intrinsic::amdgcn_if: 10910 case Intrinsic::amdgcn_else: 10911 Result = true; 10912 break; 10913 } 10914 } 10915 if (V == U->getOperand(0)) { 10916 switch (Intrinsic->getIntrinsicID()) { 10917 default: 10918 Result = false; 10919 break; 10920 case Intrinsic::amdgcn_end_cf: 10921 case Intrinsic::amdgcn_loop: 10922 Result = true; 10923 break; 10924 } 10925 } 10926 } else { 10927 Result = hasCFUser(U, Visited); 10928 } 10929 if (Result) 10930 break; 10931 } 10932 return Result; 10933 } 10934 10935 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 10936 const Value *V) const { 10937 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) { 10938 switch (Intrinsic->getIntrinsicID()) { 10939 default: 10940 return false; 10941 case Intrinsic::amdgcn_if_break: 10942 return true; 10943 } 10944 } 10945 if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) { 10946 if (const IntrinsicInst *Intrinsic = 10947 dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) { 10948 switch (Intrinsic->getIntrinsicID()) { 10949 default: 10950 return false; 10951 case Intrinsic::amdgcn_if: 10952 case Intrinsic::amdgcn_else: { 10953 ArrayRef<unsigned> Indices = ExtValue->getIndices(); 10954 if (Indices.size() == 1 && Indices[0] == 1) { 10955 return true; 10956 } 10957 } 10958 } 10959 } 10960 } 10961 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 10962 if (isa<InlineAsm>(CI->getCalledValue())) { 10963 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 10964 ImmutableCallSite CS(CI); 10965 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 10966 MF.getDataLayout(), Subtarget->getRegisterInfo(), CS); 10967 for (auto &TC : TargetConstraints) { 10968 if (TC.Type == InlineAsm::isOutput) { 10969 ComputeConstraintToUse(TC, SDValue()); 10970 unsigned AssignedReg; 10971 const TargetRegisterClass *RC; 10972 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 10973 SIRI, TC.ConstraintCode, TC.ConstraintVT); 10974 if (RC) { 10975 MachineRegisterInfo &MRI = MF.getRegInfo(); 10976 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 10977 return true; 10978 else if (SIRI->isSGPRClass(RC)) 10979 return true; 10980 } 10981 } 10982 } 10983 } 10984 } 10985 SmallPtrSet<const Value *, 16> Visited; 10986 return hasCFUser(V, Visited); 10987 } 10988