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 #include "SIISelLowering.h" 15 #include "AMDGPU.h" 16 #include "AMDGPUInstrInfo.h" 17 #include "AMDGPUTargetMachine.h" 18 #include "SIMachineFunctionInfo.h" 19 #include "SIRegisterInfo.h" 20 #include "llvm/ADT/Statistic.h" 21 #include "llvm/Analysis/LegacyDivergenceAnalysis.h" 22 #include "llvm/CodeGen/Analysis.h" 23 #include "llvm/CodeGen/FunctionLoweringInfo.h" 24 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h" 25 #include "llvm/CodeGen/MachineLoopInfo.h" 26 #include "llvm/IR/DiagnosticInfo.h" 27 #include "llvm/IR/IntrinsicsAMDGPU.h" 28 #include "llvm/IR/IntrinsicsR600.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/KnownBits.h" 31 32 using namespace llvm; 33 34 #define DEBUG_TYPE "si-lower" 35 36 STATISTIC(NumTailCalls, "Number of tail calls"); 37 38 static cl::opt<bool> DisableLoopAlignment( 39 "amdgpu-disable-loop-alignment", 40 cl::desc("Do not align and prefetch loops"), 41 cl::init(false)); 42 43 static cl::opt<bool> VGPRReserveforSGPRSpill( 44 "amdgpu-reserve-vgpr-for-sgpr-spill", 45 cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true)); 46 47 static cl::opt<bool> UseDivergentRegisterIndexing( 48 "amdgpu-use-divergent-register-indexing", 49 cl::Hidden, 50 cl::desc("Use indirect register addressing for divergent indexes"), 51 cl::init(false)); 52 53 static bool hasFP32Denormals(const MachineFunction &MF) { 54 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 55 return Info->getMode().allFP32Denormals(); 56 } 57 58 static bool hasFP64FP16Denormals(const MachineFunction &MF) { 59 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 60 return Info->getMode().allFP64FP16Denormals(); 61 } 62 63 static unsigned findFirstFreeSGPR(CCState &CCInfo) { 64 unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs(); 65 for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) { 66 if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) { 67 return AMDGPU::SGPR0 + Reg; 68 } 69 } 70 llvm_unreachable("Cannot allocate sgpr"); 71 } 72 73 SITargetLowering::SITargetLowering(const TargetMachine &TM, 74 const GCNSubtarget &STI) 75 : AMDGPUTargetLowering(TM, STI), 76 Subtarget(&STI) { 77 addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass); 78 addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass); 79 80 addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass); 81 addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass); 82 83 addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass); 84 85 const SIRegisterInfo *TRI = STI.getRegisterInfo(); 86 const TargetRegisterClass *V64RegClass = TRI->getVGPR64Class(); 87 88 addRegisterClass(MVT::f64, V64RegClass); 89 addRegisterClass(MVT::v2f32, V64RegClass); 90 91 addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass); 92 addRegisterClass(MVT::v3f32, TRI->getVGPRClassForBitWidth(96)); 93 94 addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass); 95 addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass); 96 97 addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass); 98 addRegisterClass(MVT::v4f32, TRI->getVGPRClassForBitWidth(128)); 99 100 addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass); 101 addRegisterClass(MVT::v5f32, TRI->getVGPRClassForBitWidth(160)); 102 103 addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass); 104 addRegisterClass(MVT::v8f32, TRI->getVGPRClassForBitWidth(256)); 105 106 addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass); 107 addRegisterClass(MVT::v4f64, TRI->getVGPRClassForBitWidth(256)); 108 109 addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass); 110 addRegisterClass(MVT::v16f32, TRI->getVGPRClassForBitWidth(512)); 111 112 addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass); 113 addRegisterClass(MVT::v8f64, TRI->getVGPRClassForBitWidth(512)); 114 115 addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass); 116 addRegisterClass(MVT::v16f64, TRI->getVGPRClassForBitWidth(1024)); 117 118 if (Subtarget->has16BitInsts()) { 119 addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass); 120 addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass); 121 122 // Unless there are also VOP3P operations, not operations are really legal. 123 addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass); 124 addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass); 125 addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass); 126 addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass); 127 } 128 129 addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass); 130 addRegisterClass(MVT::v32f32, TRI->getVGPRClassForBitWidth(1024)); 131 132 computeRegisterProperties(Subtarget->getRegisterInfo()); 133 134 // The boolean content concept here is too inflexible. Compares only ever 135 // really produce a 1-bit result. Any copy/extend from these will turn into a 136 // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as 137 // it's what most targets use. 138 setBooleanContents(ZeroOrOneBooleanContent); 139 setBooleanVectorContents(ZeroOrOneBooleanContent); 140 141 // We need to custom lower vector stores from local memory 142 setOperationAction(ISD::LOAD, MVT::v2i32, Custom); 143 setOperationAction(ISD::LOAD, MVT::v3i32, Custom); 144 setOperationAction(ISD::LOAD, MVT::v4i32, Custom); 145 setOperationAction(ISD::LOAD, MVT::v5i32, Custom); 146 setOperationAction(ISD::LOAD, MVT::v8i32, Custom); 147 setOperationAction(ISD::LOAD, MVT::v16i32, Custom); 148 setOperationAction(ISD::LOAD, MVT::i1, Custom); 149 setOperationAction(ISD::LOAD, MVT::v32i32, Custom); 150 151 setOperationAction(ISD::STORE, MVT::v2i32, Custom); 152 setOperationAction(ISD::STORE, MVT::v3i32, Custom); 153 setOperationAction(ISD::STORE, MVT::v4i32, Custom); 154 setOperationAction(ISD::STORE, MVT::v5i32, Custom); 155 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 156 setOperationAction(ISD::STORE, MVT::v16i32, Custom); 157 setOperationAction(ISD::STORE, MVT::i1, Custom); 158 setOperationAction(ISD::STORE, MVT::v32i32, Custom); 159 160 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 161 setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand); 162 setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand); 163 setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand); 164 setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand); 165 setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand); 166 setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand); 167 setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand); 168 setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand); 169 setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand); 170 setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand); 171 setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand); 172 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand); 173 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand); 174 setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand); 175 setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand); 176 177 setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand); 178 setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand); 179 setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand); 180 setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand); 181 setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand); 182 183 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom); 184 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 185 186 setOperationAction(ISD::SELECT, MVT::i1, Promote); 187 setOperationAction(ISD::SELECT, MVT::i64, Custom); 188 setOperationAction(ISD::SELECT, MVT::f64, Promote); 189 AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64); 190 191 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 192 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand); 193 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand); 194 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 195 setOperationAction(ISD::SELECT_CC, MVT::i1, Expand); 196 197 setOperationAction(ISD::SETCC, MVT::i1, Promote); 198 setOperationAction(ISD::SETCC, MVT::v2i1, Expand); 199 setOperationAction(ISD::SETCC, MVT::v4i1, Expand); 200 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32); 201 202 setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand); 203 setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand); 204 setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand); 205 setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand); 206 setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand); 207 setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand); 208 setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand); 209 setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand); 210 211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom); 212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom); 213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom); 214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom); 215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom); 216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom); 217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom); 218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom); 219 220 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 221 setOperationAction(ISD::BR_CC, MVT::i1, Expand); 222 setOperationAction(ISD::BR_CC, MVT::i32, Expand); 223 setOperationAction(ISD::BR_CC, MVT::i64, Expand); 224 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 225 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 226 227 setOperationAction(ISD::UADDO, MVT::i32, Legal); 228 setOperationAction(ISD::USUBO, MVT::i32, Legal); 229 230 setOperationAction(ISD::ADDCARRY, MVT::i32, Legal); 231 setOperationAction(ISD::SUBCARRY, MVT::i32, Legal); 232 233 setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand); 234 setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand); 235 setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand); 236 237 #if 0 238 setOperationAction(ISD::ADDCARRY, MVT::i64, Legal); 239 setOperationAction(ISD::SUBCARRY, MVT::i64, Legal); 240 #endif 241 242 // We only support LOAD/STORE and vector manipulation ops for vectors 243 // with > 4 elements. 244 for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32, 245 MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, 246 MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64, 247 MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) { 248 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 249 switch (Op) { 250 case ISD::LOAD: 251 case ISD::STORE: 252 case ISD::BUILD_VECTOR: 253 case ISD::BITCAST: 254 case ISD::EXTRACT_VECTOR_ELT: 255 case ISD::INSERT_VECTOR_ELT: 256 case ISD::INSERT_SUBVECTOR: 257 case ISD::EXTRACT_SUBVECTOR: 258 case ISD::SCALAR_TO_VECTOR: 259 break; 260 case ISD::CONCAT_VECTORS: 261 setOperationAction(Op, VT, Custom); 262 break; 263 default: 264 setOperationAction(Op, VT, Expand); 265 break; 266 } 267 } 268 } 269 270 setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand); 271 272 // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that 273 // is expanded to avoid having two separate loops in case the index is a VGPR. 274 275 // Most operations are naturally 32-bit vector operations. We only support 276 // load and store of i64 vectors, so promote v2i64 vector operations to v4i32. 277 for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) { 278 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 279 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32); 280 281 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 282 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32); 283 284 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 285 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32); 286 287 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 288 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32); 289 } 290 291 for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) { 292 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 293 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32); 294 295 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 296 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32); 297 298 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 299 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32); 300 301 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 302 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32); 303 } 304 305 for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) { 306 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 307 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32); 308 309 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 310 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32); 311 312 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 313 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32); 314 315 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 316 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32); 317 } 318 319 for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) { 320 setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote); 321 AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32); 322 323 setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote); 324 AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32); 325 326 setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote); 327 AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32); 328 329 setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote); 330 AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32); 331 } 332 333 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand); 334 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand); 335 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand); 336 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand); 337 338 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom); 339 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom); 340 341 // Avoid stack access for these. 342 // TODO: Generalize to more vector types. 343 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom); 344 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom); 345 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 346 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 347 348 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 349 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 350 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom); 351 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom); 352 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom); 353 354 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom); 355 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom); 356 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom); 357 358 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom); 359 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom); 360 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom); 361 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom); 362 363 // Deal with vec3 vector operations when widened to vec4. 364 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom); 365 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom); 366 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom); 367 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom); 368 369 // Deal with vec5 vector operations when widened to vec8. 370 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom); 371 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom); 372 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom); 373 setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom); 374 375 // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling, 376 // and output demarshalling 377 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom); 378 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom); 379 380 // We can't return success/failure, only the old value, 381 // let LLVM add the comparison 382 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand); 383 setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand); 384 385 if (Subtarget->hasFlatAddressSpace()) { 386 setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom); 387 setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom); 388 } 389 390 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 391 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 392 393 // FIXME: This should be narrowed to i32, but that only happens if i64 is 394 // illegal. 395 // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32. 396 setOperationAction(ISD::BSWAP, MVT::i64, Legal); 397 setOperationAction(ISD::BSWAP, MVT::i32, Legal); 398 399 // On SI this is s_memtime and s_memrealtime on VI. 400 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 401 setOperationAction(ISD::TRAP, MVT::Other, Custom); 402 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom); 403 404 if (Subtarget->has16BitInsts()) { 405 setOperationAction(ISD::FPOW, MVT::f16, Promote); 406 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 407 setOperationAction(ISD::FLOG, MVT::f16, Custom); 408 setOperationAction(ISD::FEXP, MVT::f16, Custom); 409 setOperationAction(ISD::FLOG10, MVT::f16, Custom); 410 } 411 412 if (Subtarget->hasMadMacF32Insts()) 413 setOperationAction(ISD::FMAD, MVT::f32, Legal); 414 415 if (!Subtarget->hasBFI()) { 416 // fcopysign can be done in a single instruction with BFI. 417 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand); 418 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand); 419 } 420 421 if (!Subtarget->hasBCNT(32)) 422 setOperationAction(ISD::CTPOP, MVT::i32, Expand); 423 424 if (!Subtarget->hasBCNT(64)) 425 setOperationAction(ISD::CTPOP, MVT::i64, Expand); 426 427 if (Subtarget->hasFFBH()) 428 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom); 429 430 if (Subtarget->hasFFBL()) 431 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom); 432 433 // We only really have 32-bit BFE instructions (and 16-bit on VI). 434 // 435 // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any 436 // effort to match them now. We want this to be false for i64 cases when the 437 // extraction isn't restricted to the upper or lower half. Ideally we would 438 // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that 439 // span the midpoint are probably relatively rare, so don't worry about them 440 // for now. 441 if (Subtarget->hasBFE()) 442 setHasExtractBitsInsn(true); 443 444 // Clamp modifier on add/sub 445 if (Subtarget->hasIntClamp()) { 446 setOperationAction(ISD::UADDSAT, MVT::i32, Legal); 447 setOperationAction(ISD::USUBSAT, MVT::i32, Legal); 448 } 449 450 if (Subtarget->hasAddNoCarry()) { 451 setOperationAction(ISD::SADDSAT, MVT::i16, Legal); 452 setOperationAction(ISD::SSUBSAT, MVT::i16, Legal); 453 setOperationAction(ISD::SADDSAT, MVT::i32, Legal); 454 setOperationAction(ISD::SSUBSAT, MVT::i32, Legal); 455 } 456 457 setOperationAction(ISD::FMINNUM, MVT::f32, Custom); 458 setOperationAction(ISD::FMAXNUM, MVT::f32, Custom); 459 setOperationAction(ISD::FMINNUM, MVT::f64, Custom); 460 setOperationAction(ISD::FMAXNUM, MVT::f64, Custom); 461 462 463 // These are really only legal for ieee_mode functions. We should be avoiding 464 // them for functions that don't have ieee_mode enabled, so just say they are 465 // legal. 466 setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal); 467 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal); 468 setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal); 469 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal); 470 471 472 if (Subtarget->haveRoundOpsF64()) { 473 setOperationAction(ISD::FTRUNC, MVT::f64, Legal); 474 setOperationAction(ISD::FCEIL, MVT::f64, Legal); 475 setOperationAction(ISD::FRINT, MVT::f64, Legal); 476 } else { 477 setOperationAction(ISD::FCEIL, MVT::f64, Custom); 478 setOperationAction(ISD::FTRUNC, MVT::f64, Custom); 479 setOperationAction(ISD::FRINT, MVT::f64, Custom); 480 setOperationAction(ISD::FFLOOR, MVT::f64, Custom); 481 } 482 483 setOperationAction(ISD::FFLOOR, MVT::f64, Legal); 484 485 setOperationAction(ISD::FSIN, MVT::f32, Custom); 486 setOperationAction(ISD::FCOS, MVT::f32, Custom); 487 setOperationAction(ISD::FDIV, MVT::f32, Custom); 488 setOperationAction(ISD::FDIV, MVT::f64, Custom); 489 490 if (Subtarget->has16BitInsts()) { 491 setOperationAction(ISD::Constant, MVT::i16, Legal); 492 493 setOperationAction(ISD::SMIN, MVT::i16, Legal); 494 setOperationAction(ISD::SMAX, MVT::i16, Legal); 495 496 setOperationAction(ISD::UMIN, MVT::i16, Legal); 497 setOperationAction(ISD::UMAX, MVT::i16, Legal); 498 499 setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote); 500 AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32); 501 502 setOperationAction(ISD::ROTR, MVT::i16, Expand); 503 setOperationAction(ISD::ROTL, MVT::i16, Expand); 504 505 setOperationAction(ISD::SDIV, MVT::i16, Promote); 506 setOperationAction(ISD::UDIV, MVT::i16, Promote); 507 setOperationAction(ISD::SREM, MVT::i16, Promote); 508 setOperationAction(ISD::UREM, MVT::i16, Promote); 509 setOperationAction(ISD::UADDSAT, MVT::i16, Legal); 510 setOperationAction(ISD::USUBSAT, MVT::i16, Legal); 511 512 setOperationAction(ISD::BITREVERSE, MVT::i16, Promote); 513 514 setOperationAction(ISD::CTTZ, MVT::i16, Promote); 515 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote); 516 setOperationAction(ISD::CTLZ, MVT::i16, Promote); 517 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote); 518 setOperationAction(ISD::CTPOP, MVT::i16, Promote); 519 520 setOperationAction(ISD::SELECT_CC, MVT::i16, Expand); 521 522 setOperationAction(ISD::BR_CC, MVT::i16, Expand); 523 524 setOperationAction(ISD::LOAD, MVT::i16, Custom); 525 526 setTruncStoreAction(MVT::i64, MVT::i16, Expand); 527 528 setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote); 529 AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32); 530 setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote); 531 AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32); 532 533 setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote); 534 setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote); 535 536 // F16 - Constant Actions. 537 setOperationAction(ISD::ConstantFP, MVT::f16, Legal); 538 539 // F16 - Load/Store Actions. 540 setOperationAction(ISD::LOAD, MVT::f16, Promote); 541 AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16); 542 setOperationAction(ISD::STORE, MVT::f16, Promote); 543 AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16); 544 545 // F16 - VOP1 Actions. 546 setOperationAction(ISD::FP_ROUND, MVT::f16, Custom); 547 setOperationAction(ISD::FCOS, MVT::f16, Custom); 548 setOperationAction(ISD::FSIN, MVT::f16, Custom); 549 550 setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom); 551 setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom); 552 553 setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote); 554 setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote); 555 setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote); 556 setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote); 557 setOperationAction(ISD::FROUND, MVT::f16, Custom); 558 559 // F16 - VOP2 Actions. 560 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 561 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 562 563 setOperationAction(ISD::FDIV, MVT::f16, Custom); 564 565 // F16 - VOP3 Actions. 566 setOperationAction(ISD::FMA, MVT::f16, Legal); 567 if (STI.hasMadF16()) 568 setOperationAction(ISD::FMAD, MVT::f16, Legal); 569 570 for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) { 571 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) { 572 switch (Op) { 573 case ISD::LOAD: 574 case ISD::STORE: 575 case ISD::BUILD_VECTOR: 576 case ISD::BITCAST: 577 case ISD::EXTRACT_VECTOR_ELT: 578 case ISD::INSERT_VECTOR_ELT: 579 case ISD::INSERT_SUBVECTOR: 580 case ISD::EXTRACT_SUBVECTOR: 581 case ISD::SCALAR_TO_VECTOR: 582 break; 583 case ISD::CONCAT_VECTORS: 584 setOperationAction(Op, VT, Custom); 585 break; 586 default: 587 setOperationAction(Op, VT, Expand); 588 break; 589 } 590 } 591 } 592 593 // v_perm_b32 can handle either of these. 594 setOperationAction(ISD::BSWAP, MVT::i16, Legal); 595 setOperationAction(ISD::BSWAP, MVT::v2i16, Legal); 596 setOperationAction(ISD::BSWAP, MVT::v4i16, Custom); 597 598 // XXX - Do these do anything? Vector constants turn into build_vector. 599 setOperationAction(ISD::Constant, MVT::v2i16, Legal); 600 setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal); 601 602 setOperationAction(ISD::UNDEF, MVT::v2i16, Legal); 603 setOperationAction(ISD::UNDEF, MVT::v2f16, Legal); 604 605 setOperationAction(ISD::STORE, MVT::v2i16, Promote); 606 AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32); 607 setOperationAction(ISD::STORE, MVT::v2f16, Promote); 608 AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32); 609 610 setOperationAction(ISD::LOAD, MVT::v2i16, Promote); 611 AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32); 612 setOperationAction(ISD::LOAD, MVT::v2f16, Promote); 613 AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32); 614 615 setOperationAction(ISD::AND, MVT::v2i16, Promote); 616 AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32); 617 setOperationAction(ISD::OR, MVT::v2i16, Promote); 618 AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32); 619 setOperationAction(ISD::XOR, MVT::v2i16, Promote); 620 AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32); 621 622 setOperationAction(ISD::LOAD, MVT::v4i16, Promote); 623 AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32); 624 setOperationAction(ISD::LOAD, MVT::v4f16, Promote); 625 AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32); 626 627 setOperationAction(ISD::STORE, MVT::v4i16, Promote); 628 AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32); 629 setOperationAction(ISD::STORE, MVT::v4f16, Promote); 630 AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32); 631 632 setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand); 633 setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand); 634 setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand); 635 setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand); 636 637 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand); 638 setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand); 639 setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand); 640 641 if (!Subtarget->hasVOP3PInsts()) { 642 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom); 643 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom); 644 } 645 646 setOperationAction(ISD::FNEG, MVT::v2f16, Legal); 647 // This isn't really legal, but this avoids the legalizer unrolling it (and 648 // allows matching fneg (fabs x) patterns) 649 setOperationAction(ISD::FABS, MVT::v2f16, Legal); 650 651 setOperationAction(ISD::FMAXNUM, MVT::f16, Custom); 652 setOperationAction(ISD::FMINNUM, MVT::f16, Custom); 653 setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal); 654 setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal); 655 656 setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom); 657 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom); 658 659 setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand); 660 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand); 661 } 662 663 if (Subtarget->hasVOP3PInsts()) { 664 setOperationAction(ISD::ADD, MVT::v2i16, Legal); 665 setOperationAction(ISD::SUB, MVT::v2i16, Legal); 666 setOperationAction(ISD::MUL, MVT::v2i16, Legal); 667 setOperationAction(ISD::SHL, MVT::v2i16, Legal); 668 setOperationAction(ISD::SRL, MVT::v2i16, Legal); 669 setOperationAction(ISD::SRA, MVT::v2i16, Legal); 670 setOperationAction(ISD::SMIN, MVT::v2i16, Legal); 671 setOperationAction(ISD::UMIN, MVT::v2i16, Legal); 672 setOperationAction(ISD::SMAX, MVT::v2i16, Legal); 673 setOperationAction(ISD::UMAX, MVT::v2i16, Legal); 674 675 setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal); 676 setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal); 677 setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal); 678 setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal); 679 680 setOperationAction(ISD::FADD, MVT::v2f16, Legal); 681 setOperationAction(ISD::FMUL, MVT::v2f16, Legal); 682 setOperationAction(ISD::FMA, MVT::v2f16, Legal); 683 684 setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal); 685 setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal); 686 687 setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal); 688 689 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom); 690 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom); 691 692 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom); 693 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom); 694 695 setOperationAction(ISD::SHL, MVT::v4i16, Custom); 696 setOperationAction(ISD::SRA, MVT::v4i16, Custom); 697 setOperationAction(ISD::SRL, MVT::v4i16, Custom); 698 setOperationAction(ISD::ADD, MVT::v4i16, Custom); 699 setOperationAction(ISD::SUB, MVT::v4i16, Custom); 700 setOperationAction(ISD::MUL, MVT::v4i16, Custom); 701 702 setOperationAction(ISD::SMIN, MVT::v4i16, Custom); 703 setOperationAction(ISD::SMAX, MVT::v4i16, Custom); 704 setOperationAction(ISD::UMIN, MVT::v4i16, Custom); 705 setOperationAction(ISD::UMAX, MVT::v4i16, Custom); 706 707 setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom); 708 setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom); 709 setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom); 710 setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom); 711 712 setOperationAction(ISD::FADD, MVT::v4f16, Custom); 713 setOperationAction(ISD::FMUL, MVT::v4f16, Custom); 714 setOperationAction(ISD::FMA, MVT::v4f16, Custom); 715 716 setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom); 717 setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom); 718 719 setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom); 720 setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom); 721 setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom); 722 723 setOperationAction(ISD::FEXP, MVT::v2f16, Custom); 724 setOperationAction(ISD::SELECT, MVT::v4i16, Custom); 725 setOperationAction(ISD::SELECT, MVT::v4f16, Custom); 726 727 if (Subtarget->hasPackedFP32Ops()) { 728 setOperationAction(ISD::FADD, MVT::v2f32, Legal); 729 setOperationAction(ISD::FMUL, MVT::v2f32, Legal); 730 setOperationAction(ISD::FMA, MVT::v2f32, Legal); 731 setOperationAction(ISD::FNEG, MVT::v2f32, Legal); 732 733 for (MVT VT : { MVT::v4f32, MVT::v8f32, MVT::v16f32, MVT::v32f32 }) { 734 setOperationAction(ISD::FADD, VT, Custom); 735 setOperationAction(ISD::FMUL, VT, Custom); 736 setOperationAction(ISD::FMA, VT, Custom); 737 } 738 } 739 } 740 741 setOperationAction(ISD::FNEG, MVT::v4f16, Custom); 742 setOperationAction(ISD::FABS, MVT::v4f16, Custom); 743 744 if (Subtarget->has16BitInsts()) { 745 setOperationAction(ISD::SELECT, MVT::v2i16, Promote); 746 AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32); 747 setOperationAction(ISD::SELECT, MVT::v2f16, Promote); 748 AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32); 749 } else { 750 // Legalization hack. 751 setOperationAction(ISD::SELECT, MVT::v2i16, Custom); 752 setOperationAction(ISD::SELECT, MVT::v2f16, Custom); 753 754 setOperationAction(ISD::FNEG, MVT::v2f16, Custom); 755 setOperationAction(ISD::FABS, MVT::v2f16, Custom); 756 } 757 758 for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) { 759 setOperationAction(ISD::SELECT, VT, Custom); 760 } 761 762 setOperationAction(ISD::SMULO, MVT::i64, Custom); 763 setOperationAction(ISD::UMULO, MVT::i64, Custom); 764 765 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 766 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom); 767 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom); 768 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 769 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom); 770 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom); 771 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom); 772 773 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom); 774 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom); 775 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom); 776 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom); 777 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom); 778 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom); 779 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom); 780 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom); 781 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom); 782 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom); 783 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom); 784 785 setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom); 786 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom); 787 setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom); 788 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom); 789 setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom); 790 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom); 791 setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom); 792 setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom); 793 setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom); 794 setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom); 795 796 setTargetDAGCombine(ISD::ADD); 797 setTargetDAGCombine(ISD::ADDCARRY); 798 setTargetDAGCombine(ISD::SUB); 799 setTargetDAGCombine(ISD::SUBCARRY); 800 setTargetDAGCombine(ISD::FADD); 801 setTargetDAGCombine(ISD::FSUB); 802 setTargetDAGCombine(ISD::FMINNUM); 803 setTargetDAGCombine(ISD::FMAXNUM); 804 setTargetDAGCombine(ISD::FMINNUM_IEEE); 805 setTargetDAGCombine(ISD::FMAXNUM_IEEE); 806 setTargetDAGCombine(ISD::FMA); 807 setTargetDAGCombine(ISD::SMIN); 808 setTargetDAGCombine(ISD::SMAX); 809 setTargetDAGCombine(ISD::UMIN); 810 setTargetDAGCombine(ISD::UMAX); 811 setTargetDAGCombine(ISD::SETCC); 812 setTargetDAGCombine(ISD::AND); 813 setTargetDAGCombine(ISD::OR); 814 setTargetDAGCombine(ISD::XOR); 815 setTargetDAGCombine(ISD::SINT_TO_FP); 816 setTargetDAGCombine(ISD::UINT_TO_FP); 817 setTargetDAGCombine(ISD::FCANONICALIZE); 818 setTargetDAGCombine(ISD::SCALAR_TO_VECTOR); 819 setTargetDAGCombine(ISD::ZERO_EXTEND); 820 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 821 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 822 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 823 824 // All memory operations. Some folding on the pointer operand is done to help 825 // matching the constant offsets in the addressing modes. 826 setTargetDAGCombine(ISD::LOAD); 827 setTargetDAGCombine(ISD::STORE); 828 setTargetDAGCombine(ISD::ATOMIC_LOAD); 829 setTargetDAGCombine(ISD::ATOMIC_STORE); 830 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP); 831 setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS); 832 setTargetDAGCombine(ISD::ATOMIC_SWAP); 833 setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD); 834 setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB); 835 setTargetDAGCombine(ISD::ATOMIC_LOAD_AND); 836 setTargetDAGCombine(ISD::ATOMIC_LOAD_OR); 837 setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR); 838 setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND); 839 setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN); 840 setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX); 841 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN); 842 setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX); 843 setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD); 844 setTargetDAGCombine(ISD::INTRINSIC_VOID); 845 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 846 847 // FIXME: In other contexts we pretend this is a per-function property. 848 setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32); 849 850 setSchedulingPreference(Sched::RegPressure); 851 } 852 853 const GCNSubtarget *SITargetLowering::getSubtarget() const { 854 return Subtarget; 855 } 856 857 //===----------------------------------------------------------------------===// 858 // TargetLowering queries 859 //===----------------------------------------------------------------------===// 860 861 // v_mad_mix* support a conversion from f16 to f32. 862 // 863 // There is only one special case when denormals are enabled we don't currently, 864 // where this is OK to use. 865 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode, 866 EVT DestVT, EVT SrcVT) const { 867 return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) || 868 (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) && 869 DestVT.getScalarType() == MVT::f32 && 870 SrcVT.getScalarType() == MVT::f16 && 871 // TODO: This probably only requires no input flushing? 872 !hasFP32Denormals(DAG.getMachineFunction()); 873 } 874 875 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const { 876 // SI has some legal vector types, but no legal vector operations. Say no 877 // shuffles are legal in order to prefer scalarizing some vector operations. 878 return false; 879 } 880 881 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 882 CallingConv::ID CC, 883 EVT VT) const { 884 if (CC == CallingConv::AMDGPU_KERNEL) 885 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 886 887 if (VT.isVector()) { 888 EVT ScalarVT = VT.getScalarType(); 889 unsigned Size = ScalarVT.getSizeInBits(); 890 if (Size == 16) { 891 if (Subtarget->has16BitInsts()) 892 return VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 893 return VT.isInteger() ? MVT::i32 : MVT::f32; 894 } 895 896 if (Size < 16) 897 return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32; 898 return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32; 899 } 900 901 if (VT.getSizeInBits() > 32) 902 return MVT::i32; 903 904 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 905 } 906 907 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 908 CallingConv::ID CC, 909 EVT VT) const { 910 if (CC == CallingConv::AMDGPU_KERNEL) 911 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 912 913 if (VT.isVector()) { 914 unsigned NumElts = VT.getVectorNumElements(); 915 EVT ScalarVT = VT.getScalarType(); 916 unsigned Size = ScalarVT.getSizeInBits(); 917 918 // FIXME: Should probably promote 8-bit vectors to i16. 919 if (Size == 16 && Subtarget->has16BitInsts()) 920 return (NumElts + 1) / 2; 921 922 if (Size <= 32) 923 return NumElts; 924 925 if (Size > 32) 926 return NumElts * ((Size + 31) / 32); 927 } else if (VT.getSizeInBits() > 32) 928 return (VT.getSizeInBits() + 31) / 32; 929 930 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 931 } 932 933 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv( 934 LLVMContext &Context, CallingConv::ID CC, 935 EVT VT, EVT &IntermediateVT, 936 unsigned &NumIntermediates, MVT &RegisterVT) const { 937 if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) { 938 unsigned NumElts = VT.getVectorNumElements(); 939 EVT ScalarVT = VT.getScalarType(); 940 unsigned Size = ScalarVT.getSizeInBits(); 941 // FIXME: We should fix the ABI to be the same on targets without 16-bit 942 // support, but unless we can properly handle 3-vectors, it will be still be 943 // inconsistent. 944 if (Size == 16 && Subtarget->has16BitInsts()) { 945 RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16; 946 IntermediateVT = RegisterVT; 947 NumIntermediates = (NumElts + 1) / 2; 948 return NumIntermediates; 949 } 950 951 if (Size == 32) { 952 RegisterVT = ScalarVT.getSimpleVT(); 953 IntermediateVT = RegisterVT; 954 NumIntermediates = NumElts; 955 return NumIntermediates; 956 } 957 958 if (Size < 16 && Subtarget->has16BitInsts()) { 959 // FIXME: Should probably form v2i16 pieces 960 RegisterVT = MVT::i16; 961 IntermediateVT = ScalarVT; 962 NumIntermediates = NumElts; 963 return NumIntermediates; 964 } 965 966 967 if (Size != 16 && Size <= 32) { 968 RegisterVT = MVT::i32; 969 IntermediateVT = ScalarVT; 970 NumIntermediates = NumElts; 971 return NumIntermediates; 972 } 973 974 if (Size > 32) { 975 RegisterVT = MVT::i32; 976 IntermediateVT = RegisterVT; 977 NumIntermediates = NumElts * ((Size + 31) / 32); 978 return NumIntermediates; 979 } 980 } 981 982 return TargetLowering::getVectorTypeBreakdownForCallingConv( 983 Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT); 984 } 985 986 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) { 987 assert(DMaskLanes != 0); 988 989 if (auto *VT = dyn_cast<FixedVectorType>(Ty)) { 990 unsigned NumElts = std::min(DMaskLanes, VT->getNumElements()); 991 return EVT::getVectorVT(Ty->getContext(), 992 EVT::getEVT(VT->getElementType()), 993 NumElts); 994 } 995 996 return EVT::getEVT(Ty); 997 } 998 999 // Peek through TFE struct returns to only use the data size. 1000 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) { 1001 auto *ST = dyn_cast<StructType>(Ty); 1002 if (!ST) 1003 return memVTFromImageData(Ty, DMaskLanes); 1004 1005 // Some intrinsics return an aggregate type - special case to work out the 1006 // correct memVT. 1007 // 1008 // Only limited forms of aggregate type currently expected. 1009 if (ST->getNumContainedTypes() != 2 || 1010 !ST->getContainedType(1)->isIntegerTy(32)) 1011 return EVT(); 1012 return memVTFromImageData(ST->getContainedType(0), DMaskLanes); 1013 } 1014 1015 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 1016 const CallInst &CI, 1017 MachineFunction &MF, 1018 unsigned IntrID) const { 1019 if (const AMDGPU::RsrcIntrinsic *RsrcIntr = 1020 AMDGPU::lookupRsrcIntrinsic(IntrID)) { 1021 AttributeList Attr = Intrinsic::getAttributes(CI.getContext(), 1022 (Intrinsic::ID)IntrID); 1023 if (Attr.hasFnAttribute(Attribute::ReadNone)) 1024 return false; 1025 1026 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1027 1028 if (RsrcIntr->IsImage) { 1029 Info.ptrVal = 1030 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1031 Info.align.reset(); 1032 } else { 1033 Info.ptrVal = 1034 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1035 } 1036 1037 Info.flags = MachineMemOperand::MODereferenceable; 1038 if (Attr.hasFnAttribute(Attribute::ReadOnly)) { 1039 unsigned DMaskLanes = 4; 1040 1041 if (RsrcIntr->IsImage) { 1042 const AMDGPU::ImageDimIntrinsicInfo *Intr 1043 = AMDGPU::getImageDimIntrinsicInfo(IntrID); 1044 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 1045 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 1046 1047 if (!BaseOpcode->Gather4) { 1048 // If this isn't a gather, we may have excess loaded elements in the 1049 // IR type. Check the dmask for the real number of elements loaded. 1050 unsigned DMask 1051 = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue(); 1052 DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1053 } 1054 1055 Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes); 1056 } else 1057 Info.memVT = EVT::getEVT(CI.getType()); 1058 1059 // FIXME: What does alignment mean for an image? 1060 Info.opc = ISD::INTRINSIC_W_CHAIN; 1061 Info.flags |= MachineMemOperand::MOLoad; 1062 } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) { 1063 Info.opc = ISD::INTRINSIC_VOID; 1064 1065 Type *DataTy = CI.getArgOperand(0)->getType(); 1066 if (RsrcIntr->IsImage) { 1067 unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue(); 1068 unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask); 1069 Info.memVT = memVTFromImageData(DataTy, DMaskLanes); 1070 } else 1071 Info.memVT = EVT::getEVT(DataTy); 1072 1073 Info.flags |= MachineMemOperand::MOStore; 1074 } else { 1075 // Atomic 1076 Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID : 1077 ISD::INTRINSIC_W_CHAIN; 1078 Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType()); 1079 Info.flags = MachineMemOperand::MOLoad | 1080 MachineMemOperand::MOStore | 1081 MachineMemOperand::MODereferenceable; 1082 1083 // XXX - Should this be volatile without known ordering? 1084 Info.flags |= MachineMemOperand::MOVolatile; 1085 } 1086 return true; 1087 } 1088 1089 switch (IntrID) { 1090 case Intrinsic::amdgcn_atomic_inc: 1091 case Intrinsic::amdgcn_atomic_dec: 1092 case Intrinsic::amdgcn_ds_ordered_add: 1093 case Intrinsic::amdgcn_ds_ordered_swap: 1094 case Intrinsic::amdgcn_ds_fadd: 1095 case Intrinsic::amdgcn_ds_fmin: 1096 case Intrinsic::amdgcn_ds_fmax: { 1097 Info.opc = ISD::INTRINSIC_W_CHAIN; 1098 Info.memVT = MVT::getVT(CI.getType()); 1099 Info.ptrVal = CI.getOperand(0); 1100 Info.align.reset(); 1101 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1102 1103 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4)); 1104 if (!Vol->isZero()) 1105 Info.flags |= MachineMemOperand::MOVolatile; 1106 1107 return true; 1108 } 1109 case Intrinsic::amdgcn_buffer_atomic_fadd: { 1110 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1111 1112 Info.opc = ISD::INTRINSIC_W_CHAIN; 1113 Info.memVT = MVT::getVT(CI.getOperand(0)->getType()); 1114 Info.ptrVal = 1115 MFI->getBufferPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1116 Info.align.reset(); 1117 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1118 1119 const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4)); 1120 if (!Vol || !Vol->isZero()) 1121 Info.flags |= MachineMemOperand::MOVolatile; 1122 1123 return true; 1124 } 1125 case Intrinsic::amdgcn_ds_append: 1126 case Intrinsic::amdgcn_ds_consume: { 1127 Info.opc = ISD::INTRINSIC_W_CHAIN; 1128 Info.memVT = MVT::getVT(CI.getType()); 1129 Info.ptrVal = CI.getOperand(0); 1130 Info.align.reset(); 1131 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore; 1132 1133 const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1)); 1134 if (!Vol->isZero()) 1135 Info.flags |= MachineMemOperand::MOVolatile; 1136 1137 return true; 1138 } 1139 case Intrinsic::amdgcn_global_atomic_csub: { 1140 Info.opc = ISD::INTRINSIC_W_CHAIN; 1141 Info.memVT = MVT::getVT(CI.getType()); 1142 Info.ptrVal = CI.getOperand(0); 1143 Info.align.reset(); 1144 Info.flags = MachineMemOperand::MOLoad | 1145 MachineMemOperand::MOStore | 1146 MachineMemOperand::MOVolatile; 1147 return true; 1148 } 1149 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 1150 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1151 Info.opc = ISD::INTRINSIC_W_CHAIN; 1152 Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT? 1153 Info.ptrVal = 1154 MFI->getImagePSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1155 Info.align.reset(); 1156 Info.flags = MachineMemOperand::MOLoad | 1157 MachineMemOperand::MODereferenceable; 1158 return true; 1159 } 1160 case Intrinsic::amdgcn_global_atomic_fadd: 1161 case Intrinsic::amdgcn_global_atomic_fmin: 1162 case Intrinsic::amdgcn_global_atomic_fmax: 1163 case Intrinsic::amdgcn_flat_atomic_fadd: 1164 case Intrinsic::amdgcn_flat_atomic_fmin: 1165 case Intrinsic::amdgcn_flat_atomic_fmax: { 1166 Info.opc = ISD::INTRINSIC_W_CHAIN; 1167 Info.memVT = MVT::getVT(CI.getType()); 1168 Info.ptrVal = CI.getOperand(0); 1169 Info.align.reset(); 1170 Info.flags = MachineMemOperand::MOLoad | 1171 MachineMemOperand::MOStore | 1172 MachineMemOperand::MODereferenceable | 1173 MachineMemOperand::MOVolatile; 1174 return true; 1175 } 1176 case Intrinsic::amdgcn_ds_gws_init: 1177 case Intrinsic::amdgcn_ds_gws_barrier: 1178 case Intrinsic::amdgcn_ds_gws_sema_v: 1179 case Intrinsic::amdgcn_ds_gws_sema_br: 1180 case Intrinsic::amdgcn_ds_gws_sema_p: 1181 case Intrinsic::amdgcn_ds_gws_sema_release_all: { 1182 Info.opc = ISD::INTRINSIC_VOID; 1183 1184 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1185 Info.ptrVal = 1186 MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo()); 1187 1188 // This is an abstract access, but we need to specify a type and size. 1189 Info.memVT = MVT::i32; 1190 Info.size = 4; 1191 Info.align = Align(4); 1192 1193 Info.flags = MachineMemOperand::MOStore; 1194 if (IntrID == Intrinsic::amdgcn_ds_gws_barrier) 1195 Info.flags = MachineMemOperand::MOLoad; 1196 return true; 1197 } 1198 default: 1199 return false; 1200 } 1201 } 1202 1203 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II, 1204 SmallVectorImpl<Value*> &Ops, 1205 Type *&AccessTy) const { 1206 switch (II->getIntrinsicID()) { 1207 case Intrinsic::amdgcn_atomic_inc: 1208 case Intrinsic::amdgcn_atomic_dec: 1209 case Intrinsic::amdgcn_ds_ordered_add: 1210 case Intrinsic::amdgcn_ds_ordered_swap: 1211 case Intrinsic::amdgcn_ds_append: 1212 case Intrinsic::amdgcn_ds_consume: 1213 case Intrinsic::amdgcn_ds_fadd: 1214 case Intrinsic::amdgcn_ds_fmin: 1215 case Intrinsic::amdgcn_ds_fmax: 1216 case Intrinsic::amdgcn_global_atomic_fadd: 1217 case Intrinsic::amdgcn_flat_atomic_fadd: 1218 case Intrinsic::amdgcn_flat_atomic_fmin: 1219 case Intrinsic::amdgcn_flat_atomic_fmax: 1220 case Intrinsic::amdgcn_global_atomic_csub: { 1221 Value *Ptr = II->getArgOperand(0); 1222 AccessTy = II->getType(); 1223 Ops.push_back(Ptr); 1224 return true; 1225 } 1226 default: 1227 return false; 1228 } 1229 } 1230 1231 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const { 1232 if (!Subtarget->hasFlatInstOffsets()) { 1233 // Flat instructions do not have offsets, and only have the register 1234 // address. 1235 return AM.BaseOffs == 0 && AM.Scale == 0; 1236 } 1237 1238 return AM.Scale == 0 && 1239 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1240 AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS, 1241 /*Signed=*/false)); 1242 } 1243 1244 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const { 1245 if (Subtarget->hasFlatGlobalInsts()) 1246 return AM.Scale == 0 && 1247 (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset( 1248 AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS, 1249 /*Signed=*/true)); 1250 1251 if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) { 1252 // Assume the we will use FLAT for all global memory accesses 1253 // on VI. 1254 // FIXME: This assumption is currently wrong. On VI we still use 1255 // MUBUF instructions for the r + i addressing mode. As currently 1256 // implemented, the MUBUF instructions only work on buffer < 4GB. 1257 // It may be possible to support > 4GB buffers with MUBUF instructions, 1258 // by setting the stride value in the resource descriptor which would 1259 // increase the size limit to (stride * 4GB). However, this is risky, 1260 // because it has never been validated. 1261 return isLegalFlatAddressingMode(AM); 1262 } 1263 1264 return isLegalMUBUFAddressingMode(AM); 1265 } 1266 1267 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const { 1268 // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and 1269 // additionally can do r + r + i with addr64. 32-bit has more addressing 1270 // mode options. Depending on the resource constant, it can also do 1271 // (i64 r0) + (i32 r1) * (i14 i). 1272 // 1273 // Private arrays end up using a scratch buffer most of the time, so also 1274 // assume those use MUBUF instructions. Scratch loads / stores are currently 1275 // implemented as mubuf instructions with offen bit set, so slightly 1276 // different than the normal addr64. 1277 if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs)) 1278 return false; 1279 1280 // FIXME: Since we can split immediate into soffset and immediate offset, 1281 // would it make sense to allow any immediate? 1282 1283 switch (AM.Scale) { 1284 case 0: // r + i or just i, depending on HasBaseReg. 1285 return true; 1286 case 1: 1287 return true; // We have r + r or r + i. 1288 case 2: 1289 if (AM.HasBaseReg) { 1290 // Reject 2 * r + r. 1291 return false; 1292 } 1293 1294 // Allow 2 * r as r + r 1295 // Or 2 * r + i is allowed as r + r + i. 1296 return true; 1297 default: // Don't allow n * r 1298 return false; 1299 } 1300 } 1301 1302 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL, 1303 const AddrMode &AM, Type *Ty, 1304 unsigned AS, Instruction *I) const { 1305 // No global is ever allowed as a base. 1306 if (AM.BaseGV) 1307 return false; 1308 1309 if (AS == AMDGPUAS::GLOBAL_ADDRESS) 1310 return isLegalGlobalAddressingMode(AM); 1311 1312 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 1313 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 1314 AS == AMDGPUAS::BUFFER_FAT_POINTER) { 1315 // If the offset isn't a multiple of 4, it probably isn't going to be 1316 // correctly aligned. 1317 // FIXME: Can we get the real alignment here? 1318 if (AM.BaseOffs % 4 != 0) 1319 return isLegalMUBUFAddressingMode(AM); 1320 1321 // There are no SMRD extloads, so if we have to do a small type access we 1322 // will use a MUBUF load. 1323 // FIXME?: We also need to do this if unaligned, but we don't know the 1324 // alignment here. 1325 if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4) 1326 return isLegalGlobalAddressingMode(AM); 1327 1328 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) { 1329 // SMRD instructions have an 8-bit, dword offset on SI. 1330 if (!isUInt<8>(AM.BaseOffs / 4)) 1331 return false; 1332 } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) { 1333 // On CI+, this can also be a 32-bit literal constant offset. If it fits 1334 // in 8-bits, it can use a smaller encoding. 1335 if (!isUInt<32>(AM.BaseOffs / 4)) 1336 return false; 1337 } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) { 1338 // On VI, these use the SMEM format and the offset is 20-bit in bytes. 1339 if (!isUInt<20>(AM.BaseOffs)) 1340 return false; 1341 } else 1342 llvm_unreachable("unhandled generation"); 1343 1344 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1345 return true; 1346 1347 if (AM.Scale == 1 && AM.HasBaseReg) 1348 return true; 1349 1350 return false; 1351 1352 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1353 return isLegalMUBUFAddressingMode(AM); 1354 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || 1355 AS == AMDGPUAS::REGION_ADDRESS) { 1356 // Basic, single offset DS instructions allow a 16-bit unsigned immediate 1357 // field. 1358 // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have 1359 // an 8-bit dword offset but we don't know the alignment here. 1360 if (!isUInt<16>(AM.BaseOffs)) 1361 return false; 1362 1363 if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg. 1364 return true; 1365 1366 if (AM.Scale == 1 && AM.HasBaseReg) 1367 return true; 1368 1369 return false; 1370 } else if (AS == AMDGPUAS::FLAT_ADDRESS || 1371 AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) { 1372 // For an unknown address space, this usually means that this is for some 1373 // reason being used for pure arithmetic, and not based on some addressing 1374 // computation. We don't have instructions that compute pointers with any 1375 // addressing modes, so treat them as having no offset like flat 1376 // instructions. 1377 return isLegalFlatAddressingMode(AM); 1378 } 1379 1380 // Assume a user alias of global for unknown address spaces. 1381 return isLegalGlobalAddressingMode(AM); 1382 } 1383 1384 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT, 1385 const SelectionDAG &DAG) const { 1386 if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) { 1387 return (MemVT.getSizeInBits() <= 4 * 32); 1388 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 1389 unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize(); 1390 return (MemVT.getSizeInBits() <= MaxPrivateBits); 1391 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 1392 return (MemVT.getSizeInBits() <= 2 * 32); 1393 } 1394 return true; 1395 } 1396 1397 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl( 1398 unsigned Size, unsigned AddrSpace, Align Alignment, 1399 MachineMemOperand::Flags Flags, bool *IsFast) const { 1400 if (IsFast) 1401 *IsFast = false; 1402 1403 if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1404 AddrSpace == AMDGPUAS::REGION_ADDRESS) { 1405 // Check if alignment requirements for ds_read/write instructions are 1406 // disabled. 1407 if (Subtarget->hasUnalignedDSAccessEnabled() && 1408 !Subtarget->hasLDSMisalignedBug()) { 1409 if (IsFast) 1410 *IsFast = Alignment != Align(2); 1411 return true; 1412 } 1413 1414 if (Size == 64) { 1415 // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte 1416 // aligned, 8 byte access in a single operation using ds_read2/write2_b32 1417 // with adjacent offsets. 1418 bool AlignedBy4 = Alignment >= Align(4); 1419 if (IsFast) 1420 *IsFast = AlignedBy4; 1421 1422 return AlignedBy4; 1423 } 1424 if (Size == 96) { 1425 // ds_read/write_b96 require 16-byte alignment on gfx8 and older. 1426 bool Aligned = Alignment >= Align(16); 1427 if (IsFast) 1428 *IsFast = Aligned; 1429 1430 return Aligned; 1431 } 1432 if (Size == 128) { 1433 // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we 1434 // can do a 8 byte aligned, 16 byte access in a single operation using 1435 // ds_read2/write2_b64. 1436 bool Aligned = Alignment >= Align(8); 1437 if (IsFast) 1438 *IsFast = Aligned; 1439 1440 return Aligned; 1441 } 1442 } 1443 1444 if (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS) { 1445 bool AlignedBy4 = Alignment >= Align(4); 1446 if (IsFast) 1447 *IsFast = AlignedBy4; 1448 1449 return AlignedBy4 || 1450 Subtarget->enableFlatScratch() || 1451 Subtarget->hasUnalignedScratchAccess(); 1452 } 1453 1454 // FIXME: We have to be conservative here and assume that flat operations 1455 // will access scratch. If we had access to the IR function, then we 1456 // could determine if any private memory was used in the function. 1457 if (AddrSpace == AMDGPUAS::FLAT_ADDRESS && 1458 !Subtarget->hasUnalignedScratchAccess()) { 1459 bool AlignedBy4 = Alignment >= Align(4); 1460 if (IsFast) 1461 *IsFast = AlignedBy4; 1462 1463 return AlignedBy4; 1464 } 1465 1466 if (Subtarget->hasUnalignedBufferAccessEnabled() && 1467 !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS || 1468 AddrSpace == AMDGPUAS::REGION_ADDRESS)) { 1469 // If we have an uniform constant load, it still requires using a slow 1470 // buffer instruction if unaligned. 1471 if (IsFast) { 1472 // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so 1473 // 2-byte alignment is worse than 1 unless doing a 2-byte accesss. 1474 *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS || 1475 AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ? 1476 Alignment >= Align(4) : Alignment != Align(2); 1477 } 1478 1479 return true; 1480 } 1481 1482 // Smaller than dword value must be aligned. 1483 if (Size < 32) 1484 return false; 1485 1486 // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the 1487 // byte-address are ignored, thus forcing Dword alignment. 1488 // This applies to private, global, and constant memory. 1489 if (IsFast) 1490 *IsFast = true; 1491 1492 return Size >= 32 && Alignment >= Align(4); 1493 } 1494 1495 bool SITargetLowering::allowsMisalignedMemoryAccesses( 1496 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 1497 bool *IsFast) const { 1498 if (IsFast) 1499 *IsFast = false; 1500 1501 // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96, 1502 // which isn't a simple VT. 1503 // Until MVT is extended to handle this, simply check for the size and 1504 // rely on the condition below: allow accesses if the size is a multiple of 4. 1505 if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 && 1506 VT.getStoreSize() > 16)) { 1507 return false; 1508 } 1509 1510 return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace, 1511 Alignment, Flags, IsFast); 1512 } 1513 1514 EVT SITargetLowering::getOptimalMemOpType( 1515 const MemOp &Op, const AttributeList &FuncAttributes) const { 1516 // FIXME: Should account for address space here. 1517 1518 // The default fallback uses the private pointer size as a guess for a type to 1519 // use. Make sure we switch these to 64-bit accesses. 1520 1521 if (Op.size() >= 16 && 1522 Op.isDstAligned(Align(4))) // XXX: Should only do for global 1523 return MVT::v4i32; 1524 1525 if (Op.size() >= 8 && Op.isDstAligned(Align(4))) 1526 return MVT::v2i32; 1527 1528 // Use the default. 1529 return MVT::Other; 1530 } 1531 1532 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const { 1533 const MemSDNode *MemNode = cast<MemSDNode>(N); 1534 const Value *Ptr = MemNode->getMemOperand()->getValue(); 1535 const Instruction *I = dyn_cast_or_null<Instruction>(Ptr); 1536 return I && I->getMetadata("amdgpu.noclobber"); 1537 } 1538 1539 bool SITargetLowering::isNonGlobalAddrSpace(unsigned AS) { 1540 return AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS || 1541 AS == AMDGPUAS::PRIVATE_ADDRESS; 1542 } 1543 1544 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS, 1545 unsigned DestAS) const { 1546 // Flat -> private/local is a simple truncate. 1547 // Flat -> global is no-op 1548 if (SrcAS == AMDGPUAS::FLAT_ADDRESS) 1549 return true; 1550 1551 const GCNTargetMachine &TM = 1552 static_cast<const GCNTargetMachine &>(getTargetMachine()); 1553 return TM.isNoopAddrSpaceCast(SrcAS, DestAS); 1554 } 1555 1556 bool SITargetLowering::isMemOpUniform(const SDNode *N) const { 1557 const MemSDNode *MemNode = cast<MemSDNode>(N); 1558 1559 return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand()); 1560 } 1561 1562 TargetLoweringBase::LegalizeTypeAction 1563 SITargetLowering::getPreferredVectorAction(MVT VT) const { 1564 int NumElts = VT.getVectorNumElements(); 1565 if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16)) 1566 return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector; 1567 return TargetLoweringBase::getPreferredVectorAction(VT); 1568 } 1569 1570 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1571 Type *Ty) const { 1572 // FIXME: Could be smarter if called for vector constants. 1573 return true; 1574 } 1575 1576 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const { 1577 if (Subtarget->has16BitInsts() && VT == MVT::i16) { 1578 switch (Op) { 1579 case ISD::LOAD: 1580 case ISD::STORE: 1581 1582 // These operations are done with 32-bit instructions anyway. 1583 case ISD::AND: 1584 case ISD::OR: 1585 case ISD::XOR: 1586 case ISD::SELECT: 1587 // TODO: Extensions? 1588 return true; 1589 default: 1590 return false; 1591 } 1592 } 1593 1594 // SimplifySetCC uses this function to determine whether or not it should 1595 // create setcc with i1 operands. We don't have instructions for i1 setcc. 1596 if (VT == MVT::i1 && Op == ISD::SETCC) 1597 return false; 1598 1599 return TargetLowering::isTypeDesirableForOp(Op, VT); 1600 } 1601 1602 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG, 1603 const SDLoc &SL, 1604 SDValue Chain, 1605 uint64_t Offset) const { 1606 const DataLayout &DL = DAG.getDataLayout(); 1607 MachineFunction &MF = DAG.getMachineFunction(); 1608 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 1609 1610 const ArgDescriptor *InputPtrReg; 1611 const TargetRegisterClass *RC; 1612 LLT ArgTy; 1613 1614 std::tie(InputPtrReg, RC, ArgTy) = 1615 Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 1616 1617 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 1618 MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS); 1619 SDValue BasePtr = DAG.getCopyFromReg(Chain, SL, 1620 MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT); 1621 1622 return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset)); 1623 } 1624 1625 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG, 1626 const SDLoc &SL) const { 1627 uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(), 1628 FIRST_IMPLICIT); 1629 return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset); 1630 } 1631 1632 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT, 1633 const SDLoc &SL, SDValue Val, 1634 bool Signed, 1635 const ISD::InputArg *Arg) const { 1636 // First, if it is a widened vector, narrow it. 1637 if (VT.isVector() && 1638 VT.getVectorNumElements() != MemVT.getVectorNumElements()) { 1639 EVT NarrowedVT = 1640 EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(), 1641 VT.getVectorNumElements()); 1642 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val, 1643 DAG.getConstant(0, SL, MVT::i32)); 1644 } 1645 1646 // Then convert the vector elements or scalar value. 1647 if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) && 1648 VT.bitsLT(MemVT)) { 1649 unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext; 1650 Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT)); 1651 } 1652 1653 if (MemVT.isFloatingPoint()) 1654 Val = getFPExtOrFPRound(DAG, Val, SL, VT); 1655 else if (Signed) 1656 Val = DAG.getSExtOrTrunc(Val, SL, VT); 1657 else 1658 Val = DAG.getZExtOrTrunc(Val, SL, VT); 1659 1660 return Val; 1661 } 1662 1663 SDValue SITargetLowering::lowerKernargMemParameter( 1664 SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain, 1665 uint64_t Offset, Align Alignment, bool Signed, 1666 const ISD::InputArg *Arg) const { 1667 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 1668 1669 // Try to avoid using an extload by loading earlier than the argument address, 1670 // and extracting the relevant bits. The load should hopefully be merged with 1671 // the previous argument. 1672 if (MemVT.getStoreSize() < 4 && Alignment < 4) { 1673 // TODO: Handle align < 4 and size >= 4 (can happen with packed structs). 1674 int64_t AlignDownOffset = alignDown(Offset, 4); 1675 int64_t OffsetDiff = Offset - AlignDownOffset; 1676 1677 EVT IntVT = MemVT.changeTypeToInteger(); 1678 1679 // TODO: If we passed in the base kernel offset we could have a better 1680 // alignment than 4, but we don't really need it. 1681 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset); 1682 SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4), 1683 MachineMemOperand::MODereferenceable | 1684 MachineMemOperand::MOInvariant); 1685 1686 SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32); 1687 SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt); 1688 1689 SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract); 1690 ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal); 1691 ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg); 1692 1693 1694 return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL); 1695 } 1696 1697 SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset); 1698 SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment, 1699 MachineMemOperand::MODereferenceable | 1700 MachineMemOperand::MOInvariant); 1701 1702 SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg); 1703 return DAG.getMergeValues({ Val, Load.getValue(1) }, SL); 1704 } 1705 1706 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA, 1707 const SDLoc &SL, SDValue Chain, 1708 const ISD::InputArg &Arg) const { 1709 MachineFunction &MF = DAG.getMachineFunction(); 1710 MachineFrameInfo &MFI = MF.getFrameInfo(); 1711 1712 if (Arg.Flags.isByVal()) { 1713 unsigned Size = Arg.Flags.getByValSize(); 1714 int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false); 1715 return DAG.getFrameIndex(FrameIdx, MVT::i32); 1716 } 1717 1718 unsigned ArgOffset = VA.getLocMemOffset(); 1719 unsigned ArgSize = VA.getValVT().getStoreSize(); 1720 1721 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true); 1722 1723 // Create load nodes to retrieve arguments from the stack. 1724 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 1725 SDValue ArgValue; 1726 1727 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 1728 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 1729 MVT MemVT = VA.getValVT(); 1730 1731 switch (VA.getLocInfo()) { 1732 default: 1733 break; 1734 case CCValAssign::BCvt: 1735 MemVT = VA.getLocVT(); 1736 break; 1737 case CCValAssign::SExt: 1738 ExtType = ISD::SEXTLOAD; 1739 break; 1740 case CCValAssign::ZExt: 1741 ExtType = ISD::ZEXTLOAD; 1742 break; 1743 case CCValAssign::AExt: 1744 ExtType = ISD::EXTLOAD; 1745 break; 1746 } 1747 1748 ArgValue = DAG.getExtLoad( 1749 ExtType, SL, VA.getLocVT(), Chain, FIN, 1750 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 1751 MemVT); 1752 return ArgValue; 1753 } 1754 1755 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG, 1756 const SIMachineFunctionInfo &MFI, 1757 EVT VT, 1758 AMDGPUFunctionArgInfo::PreloadedValue PVID) const { 1759 const ArgDescriptor *Reg; 1760 const TargetRegisterClass *RC; 1761 LLT Ty; 1762 1763 std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID); 1764 return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT); 1765 } 1766 1767 static void processPSInputArgs(SmallVectorImpl<ISD::InputArg> &Splits, 1768 CallingConv::ID CallConv, 1769 ArrayRef<ISD::InputArg> Ins, BitVector &Skipped, 1770 FunctionType *FType, 1771 SIMachineFunctionInfo *Info) { 1772 for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) { 1773 const ISD::InputArg *Arg = &Ins[I]; 1774 1775 assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) && 1776 "vector type argument should have been split"); 1777 1778 // First check if it's a PS input addr. 1779 if (CallConv == CallingConv::AMDGPU_PS && 1780 !Arg->Flags.isInReg() && PSInputNum <= 15) { 1781 bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum); 1782 1783 // Inconveniently only the first part of the split is marked as isSplit, 1784 // so skip to the end. We only want to increment PSInputNum once for the 1785 // entire split argument. 1786 if (Arg->Flags.isSplit()) { 1787 while (!Arg->Flags.isSplitEnd()) { 1788 assert((!Arg->VT.isVector() || 1789 Arg->VT.getScalarSizeInBits() == 16) && 1790 "unexpected vector split in ps argument type"); 1791 if (!SkipArg) 1792 Splits.push_back(*Arg); 1793 Arg = &Ins[++I]; 1794 } 1795 } 1796 1797 if (SkipArg) { 1798 // We can safely skip PS inputs. 1799 Skipped.set(Arg->getOrigArgIndex()); 1800 ++PSInputNum; 1801 continue; 1802 } 1803 1804 Info->markPSInputAllocated(PSInputNum); 1805 if (Arg->Used) 1806 Info->markPSInputEnabled(PSInputNum); 1807 1808 ++PSInputNum; 1809 } 1810 1811 Splits.push_back(*Arg); 1812 } 1813 } 1814 1815 // Allocate special inputs passed in VGPRs. 1816 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo, 1817 MachineFunction &MF, 1818 const SIRegisterInfo &TRI, 1819 SIMachineFunctionInfo &Info) const { 1820 const LLT S32 = LLT::scalar(32); 1821 MachineRegisterInfo &MRI = MF.getRegInfo(); 1822 1823 if (Info.hasWorkItemIDX()) { 1824 Register Reg = AMDGPU::VGPR0; 1825 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1826 1827 CCInfo.AllocateReg(Reg); 1828 unsigned Mask = (Subtarget->hasPackedTID() && 1829 Info.hasWorkItemIDY()) ? 0x3ff : ~0u; 1830 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1831 } 1832 1833 if (Info.hasWorkItemIDY()) { 1834 assert(Info.hasWorkItemIDX()); 1835 if (Subtarget->hasPackedTID()) { 1836 Info.setWorkItemIDY(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1837 0x3ff << 10)); 1838 } else { 1839 unsigned Reg = AMDGPU::VGPR1; 1840 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1841 1842 CCInfo.AllocateReg(Reg); 1843 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg)); 1844 } 1845 } 1846 1847 if (Info.hasWorkItemIDZ()) { 1848 assert(Info.hasWorkItemIDX() && Info.hasWorkItemIDY()); 1849 if (Subtarget->hasPackedTID()) { 1850 Info.setWorkItemIDZ(ArgDescriptor::createRegister(AMDGPU::VGPR0, 1851 0x3ff << 20)); 1852 } else { 1853 unsigned Reg = AMDGPU::VGPR2; 1854 MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32); 1855 1856 CCInfo.AllocateReg(Reg); 1857 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg)); 1858 } 1859 } 1860 } 1861 1862 // Try to allocate a VGPR at the end of the argument list, or if no argument 1863 // VGPRs are left allocating a stack slot. 1864 // If \p Mask is is given it indicates bitfield position in the register. 1865 // If \p Arg is given use it with new ]p Mask instead of allocating new. 1866 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u, 1867 ArgDescriptor Arg = ArgDescriptor()) { 1868 if (Arg.isSet()) 1869 return ArgDescriptor::createArg(Arg, Mask); 1870 1871 ArrayRef<MCPhysReg> ArgVGPRs 1872 = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32); 1873 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs); 1874 if (RegIdx == ArgVGPRs.size()) { 1875 // Spill to stack required. 1876 int64_t Offset = CCInfo.AllocateStack(4, Align(4)); 1877 1878 return ArgDescriptor::createStack(Offset, Mask); 1879 } 1880 1881 unsigned Reg = ArgVGPRs[RegIdx]; 1882 Reg = CCInfo.AllocateReg(Reg); 1883 assert(Reg != AMDGPU::NoRegister); 1884 1885 MachineFunction &MF = CCInfo.getMachineFunction(); 1886 Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass); 1887 MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32)); 1888 return ArgDescriptor::createRegister(Reg, Mask); 1889 } 1890 1891 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo, 1892 const TargetRegisterClass *RC, 1893 unsigned NumArgRegs) { 1894 ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32); 1895 unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs); 1896 if (RegIdx == ArgSGPRs.size()) 1897 report_fatal_error("ran out of SGPRs for arguments"); 1898 1899 unsigned Reg = ArgSGPRs[RegIdx]; 1900 Reg = CCInfo.AllocateReg(Reg); 1901 assert(Reg != AMDGPU::NoRegister); 1902 1903 MachineFunction &MF = CCInfo.getMachineFunction(); 1904 MF.addLiveIn(Reg, RC); 1905 return ArgDescriptor::createRegister(Reg); 1906 } 1907 1908 // If this has a fixed position, we still should allocate the register in the 1909 // CCInfo state. Technically we could get away with this for values passed 1910 // outside of the normal argument range. 1911 static void allocateFixedSGPRInputImpl(CCState &CCInfo, 1912 const TargetRegisterClass *RC, 1913 MCRegister Reg) { 1914 Reg = CCInfo.AllocateReg(Reg); 1915 assert(Reg != AMDGPU::NoRegister); 1916 MachineFunction &MF = CCInfo.getMachineFunction(); 1917 MF.addLiveIn(Reg, RC); 1918 } 1919 1920 static void allocateSGPR32Input(CCState &CCInfo, ArgDescriptor &Arg) { 1921 if (Arg) { 1922 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 1923 Arg.getRegister()); 1924 } else 1925 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32); 1926 } 1927 1928 static void allocateSGPR64Input(CCState &CCInfo, ArgDescriptor &Arg) { 1929 if (Arg) { 1930 allocateFixedSGPRInputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 1931 Arg.getRegister()); 1932 } else 1933 Arg = allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16); 1934 } 1935 1936 /// Allocate implicit function VGPR arguments at the end of allocated user 1937 /// arguments. 1938 void SITargetLowering::allocateSpecialInputVGPRs( 1939 CCState &CCInfo, MachineFunction &MF, 1940 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1941 const unsigned Mask = 0x3ff; 1942 ArgDescriptor Arg; 1943 1944 if (Info.hasWorkItemIDX()) { 1945 Arg = allocateVGPR32Input(CCInfo, Mask); 1946 Info.setWorkItemIDX(Arg); 1947 } 1948 1949 if (Info.hasWorkItemIDY()) { 1950 Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg); 1951 Info.setWorkItemIDY(Arg); 1952 } 1953 1954 if (Info.hasWorkItemIDZ()) 1955 Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg)); 1956 } 1957 1958 /// Allocate implicit function VGPR arguments in fixed registers. 1959 void SITargetLowering::allocateSpecialInputVGPRsFixed( 1960 CCState &CCInfo, MachineFunction &MF, 1961 const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const { 1962 Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31); 1963 if (!Reg) 1964 report_fatal_error("failed to allocated VGPR for implicit arguments"); 1965 1966 const unsigned Mask = 0x3ff; 1967 Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask)); 1968 Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10)); 1969 Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20)); 1970 } 1971 1972 void SITargetLowering::allocateSpecialInputSGPRs( 1973 CCState &CCInfo, 1974 MachineFunction &MF, 1975 const SIRegisterInfo &TRI, 1976 SIMachineFunctionInfo &Info) const { 1977 auto &ArgInfo = Info.getArgInfo(); 1978 1979 // TODO: Unify handling with private memory pointers. 1980 1981 if (Info.hasDispatchPtr()) 1982 allocateSGPR64Input(CCInfo, ArgInfo.DispatchPtr); 1983 1984 if (Info.hasQueuePtr()) 1985 allocateSGPR64Input(CCInfo, ArgInfo.QueuePtr); 1986 1987 // Implicit arg ptr takes the place of the kernarg segment pointer. This is a 1988 // constant offset from the kernarg segment. 1989 if (Info.hasImplicitArgPtr()) 1990 allocateSGPR64Input(CCInfo, ArgInfo.ImplicitArgPtr); 1991 1992 if (Info.hasDispatchID()) 1993 allocateSGPR64Input(CCInfo, ArgInfo.DispatchID); 1994 1995 // flat_scratch_init is not applicable for non-kernel functions. 1996 1997 if (Info.hasWorkGroupIDX()) 1998 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDX); 1999 2000 if (Info.hasWorkGroupIDY()) 2001 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDY); 2002 2003 if (Info.hasWorkGroupIDZ()) 2004 allocateSGPR32Input(CCInfo, ArgInfo.WorkGroupIDZ); 2005 } 2006 2007 // Allocate special inputs passed in user SGPRs. 2008 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo, 2009 MachineFunction &MF, 2010 const SIRegisterInfo &TRI, 2011 SIMachineFunctionInfo &Info) const { 2012 if (Info.hasImplicitBufferPtr()) { 2013 Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI); 2014 MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass); 2015 CCInfo.AllocateReg(ImplicitBufferPtrReg); 2016 } 2017 2018 // FIXME: How should these inputs interact with inreg / custom SGPR inputs? 2019 if (Info.hasPrivateSegmentBuffer()) { 2020 Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI); 2021 MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass); 2022 CCInfo.AllocateReg(PrivateSegmentBufferReg); 2023 } 2024 2025 if (Info.hasDispatchPtr()) { 2026 Register DispatchPtrReg = Info.addDispatchPtr(TRI); 2027 MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass); 2028 CCInfo.AllocateReg(DispatchPtrReg); 2029 } 2030 2031 if (Info.hasQueuePtr()) { 2032 Register QueuePtrReg = Info.addQueuePtr(TRI); 2033 MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass); 2034 CCInfo.AllocateReg(QueuePtrReg); 2035 } 2036 2037 if (Info.hasKernargSegmentPtr()) { 2038 MachineRegisterInfo &MRI = MF.getRegInfo(); 2039 Register InputPtrReg = Info.addKernargSegmentPtr(TRI); 2040 CCInfo.AllocateReg(InputPtrReg); 2041 2042 Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass); 2043 MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64)); 2044 } 2045 2046 if (Info.hasDispatchID()) { 2047 Register DispatchIDReg = Info.addDispatchID(TRI); 2048 MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass); 2049 CCInfo.AllocateReg(DispatchIDReg); 2050 } 2051 2052 if (Info.hasFlatScratchInit() && !getSubtarget()->isAmdPalOS()) { 2053 Register FlatScratchInitReg = Info.addFlatScratchInit(TRI); 2054 MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass); 2055 CCInfo.AllocateReg(FlatScratchInitReg); 2056 } 2057 2058 // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read 2059 // these from the dispatch pointer. 2060 } 2061 2062 // Allocate special input registers that are initialized per-wave. 2063 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo, 2064 MachineFunction &MF, 2065 SIMachineFunctionInfo &Info, 2066 CallingConv::ID CallConv, 2067 bool IsShader) const { 2068 if (Info.hasWorkGroupIDX()) { 2069 Register Reg = Info.addWorkGroupIDX(); 2070 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2071 CCInfo.AllocateReg(Reg); 2072 } 2073 2074 if (Info.hasWorkGroupIDY()) { 2075 Register Reg = Info.addWorkGroupIDY(); 2076 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2077 CCInfo.AllocateReg(Reg); 2078 } 2079 2080 if (Info.hasWorkGroupIDZ()) { 2081 Register Reg = Info.addWorkGroupIDZ(); 2082 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2083 CCInfo.AllocateReg(Reg); 2084 } 2085 2086 if (Info.hasWorkGroupInfo()) { 2087 Register Reg = Info.addWorkGroupInfo(); 2088 MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass); 2089 CCInfo.AllocateReg(Reg); 2090 } 2091 2092 if (Info.hasPrivateSegmentWaveByteOffset()) { 2093 // Scratch wave offset passed in system SGPR. 2094 unsigned PrivateSegmentWaveByteOffsetReg; 2095 2096 if (IsShader) { 2097 PrivateSegmentWaveByteOffsetReg = 2098 Info.getPrivateSegmentWaveByteOffsetSystemSGPR(); 2099 2100 // This is true if the scratch wave byte offset doesn't have a fixed 2101 // location. 2102 if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) { 2103 PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo); 2104 Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg); 2105 } 2106 } else 2107 PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset(); 2108 2109 MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass); 2110 CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg); 2111 } 2112 } 2113 2114 static void reservePrivateMemoryRegs(const TargetMachine &TM, 2115 MachineFunction &MF, 2116 const SIRegisterInfo &TRI, 2117 SIMachineFunctionInfo &Info) { 2118 // Now that we've figured out where the scratch register inputs are, see if 2119 // should reserve the arguments and use them directly. 2120 MachineFrameInfo &MFI = MF.getFrameInfo(); 2121 bool HasStackObjects = MFI.hasStackObjects(); 2122 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 2123 2124 // Record that we know we have non-spill stack objects so we don't need to 2125 // check all stack objects later. 2126 if (HasStackObjects) 2127 Info.setHasNonSpillStackObjects(true); 2128 2129 // Everything live out of a block is spilled with fast regalloc, so it's 2130 // almost certain that spilling will be required. 2131 if (TM.getOptLevel() == CodeGenOpt::None) 2132 HasStackObjects = true; 2133 2134 // For now assume stack access is needed in any callee functions, so we need 2135 // the scratch registers to pass in. 2136 bool RequiresStackAccess = HasStackObjects || MFI.hasCalls(); 2137 2138 if (!ST.enableFlatScratch()) { 2139 if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) { 2140 // If we have stack objects, we unquestionably need the private buffer 2141 // resource. For the Code Object V2 ABI, this will be the first 4 user 2142 // SGPR inputs. We can reserve those and use them directly. 2143 2144 Register PrivateSegmentBufferReg = 2145 Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER); 2146 Info.setScratchRSrcReg(PrivateSegmentBufferReg); 2147 } else { 2148 unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF); 2149 // We tentatively reserve the last registers (skipping the last registers 2150 // which may contain VCC, FLAT_SCR, and XNACK). After register allocation, 2151 // we'll replace these with the ones immediately after those which were 2152 // really allocated. In the prologue copies will be inserted from the 2153 // argument to these reserved registers. 2154 2155 // Without HSA, relocations are used for the scratch pointer and the 2156 // buffer resource setup is always inserted in the prologue. Scratch wave 2157 // offset is still in an input SGPR. 2158 Info.setScratchRSrcReg(ReservedBufferReg); 2159 } 2160 } 2161 2162 MachineRegisterInfo &MRI = MF.getRegInfo(); 2163 2164 // For entry functions we have to set up the stack pointer if we use it, 2165 // whereas non-entry functions get this "for free". This means there is no 2166 // intrinsic advantage to using S32 over S34 in cases where we do not have 2167 // calls but do need a frame pointer (i.e. if we are requested to have one 2168 // because frame pointer elimination is disabled). To keep things simple we 2169 // only ever use S32 as the call ABI stack pointer, and so using it does not 2170 // imply we need a separate frame pointer. 2171 // 2172 // Try to use s32 as the SP, but move it if it would interfere with input 2173 // arguments. This won't work with calls though. 2174 // 2175 // FIXME: Move SP to avoid any possible inputs, or find a way to spill input 2176 // registers. 2177 if (!MRI.isLiveIn(AMDGPU::SGPR32)) { 2178 Info.setStackPtrOffsetReg(AMDGPU::SGPR32); 2179 } else { 2180 assert(AMDGPU::isShader(MF.getFunction().getCallingConv())); 2181 2182 if (MFI.hasCalls()) 2183 report_fatal_error("call in graphics shader with too many input SGPRs"); 2184 2185 for (unsigned Reg : AMDGPU::SGPR_32RegClass) { 2186 if (!MRI.isLiveIn(Reg)) { 2187 Info.setStackPtrOffsetReg(Reg); 2188 break; 2189 } 2190 } 2191 2192 if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG) 2193 report_fatal_error("failed to find register for SP"); 2194 } 2195 2196 // hasFP should be accurate for entry functions even before the frame is 2197 // finalized, because it does not rely on the known stack size, only 2198 // properties like whether variable sized objects are present. 2199 if (ST.getFrameLowering()->hasFP(MF)) { 2200 Info.setFrameOffsetReg(AMDGPU::SGPR33); 2201 } 2202 } 2203 2204 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const { 2205 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 2206 return !Info->isEntryFunction(); 2207 } 2208 2209 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 2210 2211 } 2212 2213 void SITargetLowering::insertCopiesSplitCSR( 2214 MachineBasicBlock *Entry, 2215 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 2216 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2217 2218 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 2219 if (!IStart) 2220 return; 2221 2222 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 2223 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 2224 MachineBasicBlock::iterator MBBI = Entry->begin(); 2225 for (const MCPhysReg *I = IStart; *I; ++I) { 2226 const TargetRegisterClass *RC = nullptr; 2227 if (AMDGPU::SReg_64RegClass.contains(*I)) 2228 RC = &AMDGPU::SGPR_64RegClass; 2229 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2230 RC = &AMDGPU::SGPR_32RegClass; 2231 else 2232 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2233 2234 Register NewVR = MRI->createVirtualRegister(RC); 2235 // Create copy from CSR to a virtual register. 2236 Entry->addLiveIn(*I); 2237 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 2238 .addReg(*I); 2239 2240 // Insert the copy-back instructions right before the terminator. 2241 for (auto *Exit : Exits) 2242 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 2243 TII->get(TargetOpcode::COPY), *I) 2244 .addReg(NewVR); 2245 } 2246 } 2247 2248 SDValue SITargetLowering::LowerFormalArguments( 2249 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2250 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2251 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2252 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2253 2254 MachineFunction &MF = DAG.getMachineFunction(); 2255 const Function &Fn = MF.getFunction(); 2256 FunctionType *FType = MF.getFunction().getFunctionType(); 2257 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2258 2259 if (Subtarget->isAmdHsaOS() && AMDGPU::isGraphics(CallConv)) { 2260 DiagnosticInfoUnsupported NoGraphicsHSA( 2261 Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc()); 2262 DAG.getContext()->diagnose(NoGraphicsHSA); 2263 return DAG.getEntryNode(); 2264 } 2265 2266 Info->allocateModuleLDSGlobal(Fn.getParent()); 2267 2268 SmallVector<ISD::InputArg, 16> Splits; 2269 SmallVector<CCValAssign, 16> ArgLocs; 2270 BitVector Skipped(Ins.size()); 2271 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2272 *DAG.getContext()); 2273 2274 bool IsGraphics = AMDGPU::isGraphics(CallConv); 2275 bool IsKernel = AMDGPU::isKernel(CallConv); 2276 bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv); 2277 2278 if (IsGraphics) { 2279 assert(!Info->hasDispatchPtr() && !Info->hasKernargSegmentPtr() && 2280 (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) && 2281 !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() && 2282 !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() && 2283 !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() && 2284 !Info->hasWorkItemIDZ()); 2285 } 2286 2287 if (CallConv == CallingConv::AMDGPU_PS) { 2288 processPSInputArgs(Splits, CallConv, Ins, Skipped, FType, Info); 2289 2290 // At least one interpolation mode must be enabled or else the GPU will 2291 // hang. 2292 // 2293 // Check PSInputAddr instead of PSInputEnable. The idea is that if the user 2294 // set PSInputAddr, the user wants to enable some bits after the compilation 2295 // based on run-time states. Since we can't know what the final PSInputEna 2296 // will look like, so we shouldn't do anything here and the user should take 2297 // responsibility for the correct programming. 2298 // 2299 // Otherwise, the following restrictions apply: 2300 // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled. 2301 // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be 2302 // enabled too. 2303 if ((Info->getPSInputAddr() & 0x7F) == 0 || 2304 ((Info->getPSInputAddr() & 0xF) == 0 && Info->isPSInputAllocated(11))) { 2305 CCInfo.AllocateReg(AMDGPU::VGPR0); 2306 CCInfo.AllocateReg(AMDGPU::VGPR1); 2307 Info->markPSInputAllocated(0); 2308 Info->markPSInputEnabled(0); 2309 } 2310 if (Subtarget->isAmdPalOS()) { 2311 // For isAmdPalOS, the user does not enable some bits after compilation 2312 // based on run-time states; the register values being generated here are 2313 // the final ones set in hardware. Therefore we need to apply the 2314 // workaround to PSInputAddr and PSInputEnable together. (The case where 2315 // a bit is set in PSInputAddr but not PSInputEnable is where the 2316 // frontend set up an input arg for a particular interpolation mode, but 2317 // nothing uses that input arg. Really we should have an earlier pass 2318 // that removes such an arg.) 2319 unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable(); 2320 if ((PsInputBits & 0x7F) == 0 || 2321 ((PsInputBits & 0xF) == 0 && (PsInputBits >> 11 & 1))) 2322 Info->markPSInputEnabled( 2323 countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined)); 2324 } 2325 } else if (IsKernel) { 2326 assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX()); 2327 } else { 2328 Splits.append(Ins.begin(), Ins.end()); 2329 } 2330 2331 if (IsEntryFunc) { 2332 allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info); 2333 allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info); 2334 } else { 2335 // For the fixed ABI, pass workitem IDs in the last argument register. 2336 if (AMDGPUTargetMachine::EnableFixedFunctionABI) 2337 allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info); 2338 } 2339 2340 if (IsKernel) { 2341 analyzeFormalArgumentsCompute(CCInfo, Ins); 2342 } else { 2343 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg); 2344 CCInfo.AnalyzeFormalArguments(Splits, AssignFn); 2345 } 2346 2347 SmallVector<SDValue, 16> Chains; 2348 2349 // FIXME: This is the minimum kernel argument alignment. We should improve 2350 // this to the maximum alignment of the arguments. 2351 // 2352 // FIXME: Alignment of explicit arguments totally broken with non-0 explicit 2353 // kern arg offset. 2354 const Align KernelArgBaseAlign = Align(16); 2355 2356 for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) { 2357 const ISD::InputArg &Arg = Ins[i]; 2358 if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) { 2359 InVals.push_back(DAG.getUNDEF(Arg.VT)); 2360 continue; 2361 } 2362 2363 CCValAssign &VA = ArgLocs[ArgIdx++]; 2364 MVT VT = VA.getLocVT(); 2365 2366 if (IsEntryFunc && VA.isMemLoc()) { 2367 VT = Ins[i].VT; 2368 EVT MemVT = VA.getLocVT(); 2369 2370 const uint64_t Offset = VA.getLocMemOffset(); 2371 Align Alignment = commonAlignment(KernelArgBaseAlign, Offset); 2372 2373 if (Arg.Flags.isByRef()) { 2374 SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset); 2375 2376 const GCNTargetMachine &TM = 2377 static_cast<const GCNTargetMachine &>(getTargetMachine()); 2378 if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS, 2379 Arg.Flags.getPointerAddrSpace())) { 2380 Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS, 2381 Arg.Flags.getPointerAddrSpace()); 2382 } 2383 2384 InVals.push_back(Ptr); 2385 continue; 2386 } 2387 2388 SDValue Arg = lowerKernargMemParameter( 2389 DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]); 2390 Chains.push_back(Arg.getValue(1)); 2391 2392 auto *ParamTy = 2393 dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex())); 2394 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 2395 ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS || 2396 ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) { 2397 // On SI local pointers are just offsets into LDS, so they are always 2398 // less than 16-bits. On CI and newer they could potentially be 2399 // real pointers, so we can't guarantee their size. 2400 Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg, 2401 DAG.getValueType(MVT::i16)); 2402 } 2403 2404 InVals.push_back(Arg); 2405 continue; 2406 } else if (!IsEntryFunc && VA.isMemLoc()) { 2407 SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg); 2408 InVals.push_back(Val); 2409 if (!Arg.Flags.isByVal()) 2410 Chains.push_back(Val.getValue(1)); 2411 continue; 2412 } 2413 2414 assert(VA.isRegLoc() && "Parameter must be in a register!"); 2415 2416 Register Reg = VA.getLocReg(); 2417 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT); 2418 EVT ValVT = VA.getValVT(); 2419 2420 Reg = MF.addLiveIn(Reg, RC); 2421 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT); 2422 2423 if (Arg.Flags.isSRet()) { 2424 // The return object should be reasonably addressable. 2425 2426 // FIXME: This helps when the return is a real sret. If it is a 2427 // automatically inserted sret (i.e. CanLowerReturn returns false), an 2428 // extra copy is inserted in SelectionDAGBuilder which obscures this. 2429 unsigned NumBits 2430 = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex(); 2431 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2432 DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits))); 2433 } 2434 2435 // If this is an 8 or 16-bit value, it is really passed promoted 2436 // to 32 bits. Insert an assert[sz]ext to capture this, then 2437 // truncate to the right size. 2438 switch (VA.getLocInfo()) { 2439 case CCValAssign::Full: 2440 break; 2441 case CCValAssign::BCvt: 2442 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val); 2443 break; 2444 case CCValAssign::SExt: 2445 Val = DAG.getNode(ISD::AssertSext, DL, VT, Val, 2446 DAG.getValueType(ValVT)); 2447 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2448 break; 2449 case CCValAssign::ZExt: 2450 Val = DAG.getNode(ISD::AssertZext, DL, VT, Val, 2451 DAG.getValueType(ValVT)); 2452 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2453 break; 2454 case CCValAssign::AExt: 2455 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val); 2456 break; 2457 default: 2458 llvm_unreachable("Unknown loc info!"); 2459 } 2460 2461 InVals.push_back(Val); 2462 } 2463 2464 if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) { 2465 // Special inputs come after user arguments. 2466 allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info); 2467 } 2468 2469 // Start adding system SGPRs. 2470 if (IsEntryFunc) { 2471 allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsGraphics); 2472 } else { 2473 CCInfo.AllocateReg(Info->getScratchRSrcReg()); 2474 allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info); 2475 } 2476 2477 auto &ArgUsageInfo = 2478 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2479 ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo()); 2480 2481 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2482 Info->setBytesInStackArgArea(StackArgSize); 2483 2484 return Chains.empty() ? Chain : 2485 DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains); 2486 } 2487 2488 // TODO: If return values can't fit in registers, we should return as many as 2489 // possible in registers before passing on stack. 2490 bool SITargetLowering::CanLowerReturn( 2491 CallingConv::ID CallConv, 2492 MachineFunction &MF, bool IsVarArg, 2493 const SmallVectorImpl<ISD::OutputArg> &Outs, 2494 LLVMContext &Context) const { 2495 // Replacing returns with sret/stack usage doesn't make sense for shaders. 2496 // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn 2497 // for shaders. Vector types should be explicitly handled by CC. 2498 if (AMDGPU::isEntryFunctionCC(CallConv)) 2499 return true; 2500 2501 SmallVector<CCValAssign, 16> RVLocs; 2502 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 2503 return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg)); 2504 } 2505 2506 SDValue 2507 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 2508 bool isVarArg, 2509 const SmallVectorImpl<ISD::OutputArg> &Outs, 2510 const SmallVectorImpl<SDValue> &OutVals, 2511 const SDLoc &DL, SelectionDAG &DAG) const { 2512 MachineFunction &MF = DAG.getMachineFunction(); 2513 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2514 2515 if (AMDGPU::isKernel(CallConv)) { 2516 return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs, 2517 OutVals, DL, DAG); 2518 } 2519 2520 bool IsShader = AMDGPU::isShader(CallConv); 2521 2522 Info->setIfReturnsVoid(Outs.empty()); 2523 bool IsWaveEnd = Info->returnsVoid() && IsShader; 2524 2525 // CCValAssign - represent the assignment of the return value to a location. 2526 SmallVector<CCValAssign, 48> RVLocs; 2527 SmallVector<ISD::OutputArg, 48> Splits; 2528 2529 // CCState - Info about the registers and stack slots. 2530 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2531 *DAG.getContext()); 2532 2533 // Analyze outgoing return values. 2534 CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg)); 2535 2536 SDValue Flag; 2537 SmallVector<SDValue, 48> RetOps; 2538 RetOps.push_back(Chain); // Operand #0 = Chain (updated below) 2539 2540 // Add return address for callable functions. 2541 if (!Info->isEntryFunction()) { 2542 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2543 SDValue ReturnAddrReg = CreateLiveInRegister( 2544 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 2545 2546 SDValue ReturnAddrVirtualReg = DAG.getRegister( 2547 MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass), 2548 MVT::i64); 2549 Chain = 2550 DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag); 2551 Flag = Chain.getValue(1); 2552 RetOps.push_back(ReturnAddrVirtualReg); 2553 } 2554 2555 // Copy the result values into the output registers. 2556 for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E; 2557 ++I, ++RealRVLocIdx) { 2558 CCValAssign &VA = RVLocs[I]; 2559 assert(VA.isRegLoc() && "Can only return in registers!"); 2560 // TODO: Partially return in registers if return values don't fit. 2561 SDValue Arg = OutVals[RealRVLocIdx]; 2562 2563 // Copied from other backends. 2564 switch (VA.getLocInfo()) { 2565 case CCValAssign::Full: 2566 break; 2567 case CCValAssign::BCvt: 2568 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 2569 break; 2570 case CCValAssign::SExt: 2571 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 2572 break; 2573 case CCValAssign::ZExt: 2574 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 2575 break; 2576 case CCValAssign::AExt: 2577 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 2578 break; 2579 default: 2580 llvm_unreachable("Unknown loc info!"); 2581 } 2582 2583 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 2584 Flag = Chain.getValue(1); 2585 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 2586 } 2587 2588 // FIXME: Does sret work properly? 2589 if (!Info->isEntryFunction()) { 2590 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2591 const MCPhysReg *I = 2592 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 2593 if (I) { 2594 for (; *I; ++I) { 2595 if (AMDGPU::SReg_64RegClass.contains(*I)) 2596 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 2597 else if (AMDGPU::SReg_32RegClass.contains(*I)) 2598 RetOps.push_back(DAG.getRegister(*I, MVT::i32)); 2599 else 2600 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 2601 } 2602 } 2603 } 2604 2605 // Update chain and glue. 2606 RetOps[0] = Chain; 2607 if (Flag.getNode()) 2608 RetOps.push_back(Flag); 2609 2610 unsigned Opc = AMDGPUISD::ENDPGM; 2611 if (!IsWaveEnd) 2612 Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG; 2613 return DAG.getNode(Opc, DL, MVT::Other, RetOps); 2614 } 2615 2616 SDValue SITargetLowering::LowerCallResult( 2617 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg, 2618 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2619 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn, 2620 SDValue ThisVal) const { 2621 CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg); 2622 2623 // Assign locations to each value returned by this call. 2624 SmallVector<CCValAssign, 16> RVLocs; 2625 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 2626 *DAG.getContext()); 2627 CCInfo.AnalyzeCallResult(Ins, RetCC); 2628 2629 // Copy all of the result registers out of their specified physreg. 2630 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2631 CCValAssign VA = RVLocs[i]; 2632 SDValue Val; 2633 2634 if (VA.isRegLoc()) { 2635 Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2636 Chain = Val.getValue(1); 2637 InFlag = Val.getValue(2); 2638 } else if (VA.isMemLoc()) { 2639 report_fatal_error("TODO: return values in memory"); 2640 } else 2641 llvm_unreachable("unknown argument location type"); 2642 2643 switch (VA.getLocInfo()) { 2644 case CCValAssign::Full: 2645 break; 2646 case CCValAssign::BCvt: 2647 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2648 break; 2649 case CCValAssign::ZExt: 2650 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val, 2651 DAG.getValueType(VA.getValVT())); 2652 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2653 break; 2654 case CCValAssign::SExt: 2655 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val, 2656 DAG.getValueType(VA.getValVT())); 2657 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2658 break; 2659 case CCValAssign::AExt: 2660 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val); 2661 break; 2662 default: 2663 llvm_unreachable("Unknown loc info!"); 2664 } 2665 2666 InVals.push_back(Val); 2667 } 2668 2669 return Chain; 2670 } 2671 2672 // Add code to pass special inputs required depending on used features separate 2673 // from the explicit user arguments present in the IR. 2674 void SITargetLowering::passSpecialInputs( 2675 CallLoweringInfo &CLI, 2676 CCState &CCInfo, 2677 const SIMachineFunctionInfo &Info, 2678 SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass, 2679 SmallVectorImpl<SDValue> &MemOpChains, 2680 SDValue Chain) const { 2681 // If we don't have a call site, this was a call inserted by 2682 // legalization. These can never use special inputs. 2683 if (!CLI.CB) 2684 return; 2685 2686 SelectionDAG &DAG = CLI.DAG; 2687 const SDLoc &DL = CLI.DL; 2688 2689 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 2690 const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo(); 2691 2692 const AMDGPUFunctionArgInfo *CalleeArgInfo 2693 = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo; 2694 if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) { 2695 auto &ArgUsageInfo = 2696 DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>(); 2697 CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc); 2698 } 2699 2700 // TODO: Unify with private memory register handling. This is complicated by 2701 // the fact that at least in kernels, the input argument is not necessarily 2702 // in the same location as the input. 2703 AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = { 2704 AMDGPUFunctionArgInfo::DISPATCH_PTR, 2705 AMDGPUFunctionArgInfo::QUEUE_PTR, 2706 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR, 2707 AMDGPUFunctionArgInfo::DISPATCH_ID, 2708 AMDGPUFunctionArgInfo::WORKGROUP_ID_X, 2709 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y, 2710 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z 2711 }; 2712 2713 for (auto InputID : InputRegs) { 2714 const ArgDescriptor *OutgoingArg; 2715 const TargetRegisterClass *ArgRC; 2716 LLT ArgTy; 2717 2718 std::tie(OutgoingArg, ArgRC, ArgTy) = 2719 CalleeArgInfo->getPreloadedValue(InputID); 2720 if (!OutgoingArg) 2721 continue; 2722 2723 const ArgDescriptor *IncomingArg; 2724 const TargetRegisterClass *IncomingArgRC; 2725 LLT Ty; 2726 std::tie(IncomingArg, IncomingArgRC, Ty) = 2727 CallerArgInfo.getPreloadedValue(InputID); 2728 assert(IncomingArgRC == ArgRC); 2729 2730 // All special arguments are ints for now. 2731 EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32; 2732 SDValue InputReg; 2733 2734 if (IncomingArg) { 2735 InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg); 2736 } else { 2737 // The implicit arg ptr is special because it doesn't have a corresponding 2738 // input for kernels, and is computed from the kernarg segment pointer. 2739 assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 2740 InputReg = getImplicitArgPtr(DAG, DL); 2741 } 2742 2743 if (OutgoingArg->isRegister()) { 2744 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2745 if (!CCInfo.AllocateReg(OutgoingArg->getRegister())) 2746 report_fatal_error("failed to allocate implicit input argument"); 2747 } else { 2748 unsigned SpecialArgOffset = 2749 CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4)); 2750 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2751 SpecialArgOffset); 2752 MemOpChains.push_back(ArgStore); 2753 } 2754 } 2755 2756 // Pack workitem IDs into a single register or pass it as is if already 2757 // packed. 2758 const ArgDescriptor *OutgoingArg; 2759 const TargetRegisterClass *ArgRC; 2760 LLT Ty; 2761 2762 std::tie(OutgoingArg, ArgRC, Ty) = 2763 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X); 2764 if (!OutgoingArg) 2765 std::tie(OutgoingArg, ArgRC, Ty) = 2766 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y); 2767 if (!OutgoingArg) 2768 std::tie(OutgoingArg, ArgRC, Ty) = 2769 CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z); 2770 if (!OutgoingArg) 2771 return; 2772 2773 const ArgDescriptor *IncomingArgX = std::get<0>( 2774 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X)); 2775 const ArgDescriptor *IncomingArgY = std::get<0>( 2776 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y)); 2777 const ArgDescriptor *IncomingArgZ = std::get<0>( 2778 CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z)); 2779 2780 SDValue InputReg; 2781 SDLoc SL; 2782 2783 // If incoming ids are not packed we need to pack them. 2784 if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX) 2785 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX); 2786 2787 if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) { 2788 SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY); 2789 Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y, 2790 DAG.getShiftAmountConstant(10, MVT::i32, SL)); 2791 InputReg = InputReg.getNode() ? 2792 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y; 2793 } 2794 2795 if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) { 2796 SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ); 2797 Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z, 2798 DAG.getShiftAmountConstant(20, MVT::i32, SL)); 2799 InputReg = InputReg.getNode() ? 2800 DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z; 2801 } 2802 2803 if (!InputReg.getNode()) { 2804 // Workitem ids are already packed, any of present incoming arguments 2805 // will carry all required fields. 2806 ArgDescriptor IncomingArg = ArgDescriptor::createArg( 2807 IncomingArgX ? *IncomingArgX : 2808 IncomingArgY ? *IncomingArgY : 2809 *IncomingArgZ, ~0u); 2810 InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg); 2811 } 2812 2813 if (OutgoingArg->isRegister()) { 2814 RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg); 2815 CCInfo.AllocateReg(OutgoingArg->getRegister()); 2816 } else { 2817 unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4)); 2818 SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg, 2819 SpecialArgOffset); 2820 MemOpChains.push_back(ArgStore); 2821 } 2822 } 2823 2824 static bool canGuaranteeTCO(CallingConv::ID CC) { 2825 return CC == CallingConv::Fast; 2826 } 2827 2828 /// Return true if we might ever do TCO for calls with this calling convention. 2829 static bool mayTailCallThisCC(CallingConv::ID CC) { 2830 switch (CC) { 2831 case CallingConv::C: 2832 return true; 2833 default: 2834 return canGuaranteeTCO(CC); 2835 } 2836 } 2837 2838 bool SITargetLowering::isEligibleForTailCallOptimization( 2839 SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg, 2840 const SmallVectorImpl<ISD::OutputArg> &Outs, 2841 const SmallVectorImpl<SDValue> &OutVals, 2842 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2843 if (!mayTailCallThisCC(CalleeCC)) 2844 return false; 2845 2846 MachineFunction &MF = DAG.getMachineFunction(); 2847 const Function &CallerF = MF.getFunction(); 2848 CallingConv::ID CallerCC = CallerF.getCallingConv(); 2849 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 2850 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2851 2852 // Kernels aren't callable, and don't have a live in return address so it 2853 // doesn't make sense to do a tail call with entry functions. 2854 if (!CallerPreserved) 2855 return false; 2856 2857 bool CCMatch = CallerCC == CalleeCC; 2858 2859 if (DAG.getTarget().Options.GuaranteedTailCallOpt) { 2860 if (canGuaranteeTCO(CalleeCC) && CCMatch) 2861 return true; 2862 return false; 2863 } 2864 2865 // TODO: Can we handle var args? 2866 if (IsVarArg) 2867 return false; 2868 2869 for (const Argument &Arg : CallerF.args()) { 2870 if (Arg.hasByValAttr()) 2871 return false; 2872 } 2873 2874 LLVMContext &Ctx = *DAG.getContext(); 2875 2876 // Check that the call results are passed in the same way. 2877 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins, 2878 CCAssignFnForCall(CalleeCC, IsVarArg), 2879 CCAssignFnForCall(CallerCC, IsVarArg))) 2880 return false; 2881 2882 // The callee has to preserve all registers the caller needs to preserve. 2883 if (!CCMatch) { 2884 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2885 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2886 return false; 2887 } 2888 2889 // Nothing more to check if the callee is taking no arguments. 2890 if (Outs.empty()) 2891 return true; 2892 2893 SmallVector<CCValAssign, 16> ArgLocs; 2894 CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx); 2895 2896 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg)); 2897 2898 const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>(); 2899 // If the stack arguments for this call do not fit into our own save area then 2900 // the call cannot be made tail. 2901 // TODO: Is this really necessary? 2902 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2903 return false; 2904 2905 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2906 return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals); 2907 } 2908 2909 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 2910 if (!CI->isTailCall()) 2911 return false; 2912 2913 const Function *ParentFn = CI->getParent()->getParent(); 2914 if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv())) 2915 return false; 2916 return true; 2917 } 2918 2919 // The wave scratch offset register is used as the global base pointer. 2920 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI, 2921 SmallVectorImpl<SDValue> &InVals) const { 2922 SelectionDAG &DAG = CLI.DAG; 2923 const SDLoc &DL = CLI.DL; 2924 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2925 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2926 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2927 SDValue Chain = CLI.Chain; 2928 SDValue Callee = CLI.Callee; 2929 bool &IsTailCall = CLI.IsTailCall; 2930 CallingConv::ID CallConv = CLI.CallConv; 2931 bool IsVarArg = CLI.IsVarArg; 2932 bool IsSibCall = false; 2933 bool IsThisReturn = false; 2934 MachineFunction &MF = DAG.getMachineFunction(); 2935 2936 if (Callee.isUndef() || isNullConstant(Callee)) { 2937 if (!CLI.IsTailCall) { 2938 for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I) 2939 InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT)); 2940 } 2941 2942 return Chain; 2943 } 2944 2945 if (IsVarArg) { 2946 return lowerUnhandledCall(CLI, InVals, 2947 "unsupported call to variadic function "); 2948 } 2949 2950 if (!CLI.CB) 2951 report_fatal_error("unsupported libcall legalization"); 2952 2953 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 2954 !CLI.CB->getCalledFunction() && CallConv != CallingConv::AMDGPU_Gfx) { 2955 return lowerUnhandledCall(CLI, InVals, 2956 "unsupported indirect call to function "); 2957 } 2958 2959 if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) { 2960 return lowerUnhandledCall(CLI, InVals, 2961 "unsupported required tail call to function "); 2962 } 2963 2964 if (AMDGPU::isShader(CallConv)) { 2965 // Note the issue is with the CC of the called function, not of the call 2966 // itself. 2967 return lowerUnhandledCall(CLI, InVals, 2968 "unsupported call to a shader function "); 2969 } 2970 2971 if (AMDGPU::isShader(MF.getFunction().getCallingConv()) && 2972 CallConv != CallingConv::AMDGPU_Gfx) { 2973 // Only allow calls with specific calling conventions. 2974 return lowerUnhandledCall(CLI, InVals, 2975 "unsupported calling convention for call from " 2976 "graphics shader of function "); 2977 } 2978 2979 if (IsTailCall) { 2980 IsTailCall = isEligibleForTailCallOptimization( 2981 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2982 if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) { 2983 report_fatal_error("failed to perform tail call elimination on a call " 2984 "site marked musttail"); 2985 } 2986 2987 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2988 2989 // A sibling call is one where we're under the usual C ABI and not planning 2990 // to change that but can still do a tail call: 2991 if (!TailCallOpt && IsTailCall) 2992 IsSibCall = true; 2993 2994 if (IsTailCall) 2995 ++NumTailCalls; 2996 } 2997 2998 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 2999 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3000 SmallVector<SDValue, 8> MemOpChains; 3001 3002 // Analyze operands of the call, assigning locations to each operand. 3003 SmallVector<CCValAssign, 16> ArgLocs; 3004 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 3005 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg); 3006 3007 if (AMDGPUTargetMachine::EnableFixedFunctionABI && 3008 CallConv != CallingConv::AMDGPU_Gfx) { 3009 // With a fixed ABI, allocate fixed registers before user arguments. 3010 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3011 } 3012 3013 CCInfo.AnalyzeCallOperands(Outs, AssignFn); 3014 3015 // Get a count of how many bytes are to be pushed on the stack. 3016 unsigned NumBytes = CCInfo.getNextStackOffset(); 3017 3018 if (IsSibCall) { 3019 // Since we're not changing the ABI to make this a tail call, the memory 3020 // operands are already available in the caller's incoming argument space. 3021 NumBytes = 0; 3022 } 3023 3024 // FPDiff is the byte offset of the call's argument area from the callee's. 3025 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3026 // by this amount for a tail call. In a sibling call it must be 0 because the 3027 // caller will deallocate the entire stack and the callee still expects its 3028 // arguments to begin at SP+0. Completely unused for non-tail calls. 3029 int32_t FPDiff = 0; 3030 MachineFrameInfo &MFI = MF.getFrameInfo(); 3031 3032 // Adjust the stack pointer for the new arguments... 3033 // These operations are automatically eliminated by the prolog/epilog pass 3034 if (!IsSibCall) { 3035 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL); 3036 3037 if (!Subtarget->enableFlatScratch()) { 3038 SmallVector<SDValue, 4> CopyFromChains; 3039 3040 // In the HSA case, this should be an identity copy. 3041 SDValue ScratchRSrcReg 3042 = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32); 3043 RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg); 3044 CopyFromChains.push_back(ScratchRSrcReg.getValue(1)); 3045 Chain = DAG.getTokenFactor(DL, CopyFromChains); 3046 } 3047 } 3048 3049 MVT PtrVT = MVT::i32; 3050 3051 // Walk the register/memloc assignments, inserting copies/loads. 3052 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3053 CCValAssign &VA = ArgLocs[i]; 3054 SDValue Arg = OutVals[i]; 3055 3056 // Promote the value if needed. 3057 switch (VA.getLocInfo()) { 3058 case CCValAssign::Full: 3059 break; 3060 case CCValAssign::BCvt: 3061 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3062 break; 3063 case CCValAssign::ZExt: 3064 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3065 break; 3066 case CCValAssign::SExt: 3067 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3068 break; 3069 case CCValAssign::AExt: 3070 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3071 break; 3072 case CCValAssign::FPExt: 3073 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3074 break; 3075 default: 3076 llvm_unreachable("Unknown loc info!"); 3077 } 3078 3079 if (VA.isRegLoc()) { 3080 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3081 } else { 3082 assert(VA.isMemLoc()); 3083 3084 SDValue DstAddr; 3085 MachinePointerInfo DstInfo; 3086 3087 unsigned LocMemOffset = VA.getLocMemOffset(); 3088 int32_t Offset = LocMemOffset; 3089 3090 SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT); 3091 MaybeAlign Alignment; 3092 3093 if (IsTailCall) { 3094 ISD::ArgFlagsTy Flags = Outs[i].Flags; 3095 unsigned OpSize = Flags.isByVal() ? 3096 Flags.getByValSize() : VA.getValVT().getStoreSize(); 3097 3098 // FIXME: We can have better than the minimum byval required alignment. 3099 Alignment = 3100 Flags.isByVal() 3101 ? Flags.getNonZeroByValAlign() 3102 : commonAlignment(Subtarget->getStackAlignment(), Offset); 3103 3104 Offset = Offset + FPDiff; 3105 int FI = MFI.CreateFixedObject(OpSize, Offset, true); 3106 3107 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3108 DstInfo = MachinePointerInfo::getFixedStack(MF, FI); 3109 3110 // Make sure any stack arguments overlapping with where we're storing 3111 // are loaded before this eventual operation. Otherwise they'll be 3112 // clobbered. 3113 3114 // FIXME: Why is this really necessary? This seems to just result in a 3115 // lot of code to copy the stack and write them back to the same 3116 // locations, which are supposed to be immutable? 3117 Chain = addTokenForArgument(Chain, DAG, MFI, FI); 3118 } else { 3119 DstAddr = PtrOff; 3120 DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset); 3121 Alignment = 3122 commonAlignment(Subtarget->getStackAlignment(), LocMemOffset); 3123 } 3124 3125 if (Outs[i].Flags.isByVal()) { 3126 SDValue SizeNode = 3127 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32); 3128 SDValue Cpy = 3129 DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode, 3130 Outs[i].Flags.getNonZeroByValAlign(), 3131 /*isVol = */ false, /*AlwaysInline = */ true, 3132 /*isTailCall = */ false, DstInfo, 3133 MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS)); 3134 3135 MemOpChains.push_back(Cpy); 3136 } else { 3137 SDValue Store = 3138 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment); 3139 MemOpChains.push_back(Store); 3140 } 3141 } 3142 } 3143 3144 if (!AMDGPUTargetMachine::EnableFixedFunctionABI && 3145 CallConv != CallingConv::AMDGPU_Gfx) { 3146 // Copy special input registers after user input arguments. 3147 passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain); 3148 } 3149 3150 if (!MemOpChains.empty()) 3151 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3152 3153 // Build a sequence of copy-to-reg nodes chained together with token chain 3154 // and flag operands which copy the outgoing args into the appropriate regs. 3155 SDValue InFlag; 3156 for (auto &RegToPass : RegsToPass) { 3157 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3158 RegToPass.second, InFlag); 3159 InFlag = Chain.getValue(1); 3160 } 3161 3162 3163 SDValue PhysReturnAddrReg; 3164 if (IsTailCall) { 3165 // Since the return is being combined with the call, we need to pass on the 3166 // return address. 3167 3168 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 3169 SDValue ReturnAddrReg = CreateLiveInRegister( 3170 DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64); 3171 3172 PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF), 3173 MVT::i64); 3174 Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag); 3175 InFlag = Chain.getValue(1); 3176 } 3177 3178 // We don't usually want to end the call-sequence here because we would tidy 3179 // the frame up *after* the call, however in the ABI-changing tail-call case 3180 // we've carefully laid out the parameters so that when sp is reset they'll be 3181 // in the correct location. 3182 if (IsTailCall && !IsSibCall) { 3183 Chain = DAG.getCALLSEQ_END(Chain, 3184 DAG.getTargetConstant(NumBytes, DL, MVT::i32), 3185 DAG.getTargetConstant(0, DL, MVT::i32), 3186 InFlag, DL); 3187 InFlag = Chain.getValue(1); 3188 } 3189 3190 std::vector<SDValue> Ops; 3191 Ops.push_back(Chain); 3192 Ops.push_back(Callee); 3193 // Add a redundant copy of the callee global which will not be legalized, as 3194 // we need direct access to the callee later. 3195 if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) { 3196 const GlobalValue *GV = GSD->getGlobal(); 3197 Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64)); 3198 } else { 3199 Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64)); 3200 } 3201 3202 if (IsTailCall) { 3203 // Each tail call may have to adjust the stack by a different amount, so 3204 // this information must travel along with the operation for eventual 3205 // consumption by emitEpilogue. 3206 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3207 3208 Ops.push_back(PhysReturnAddrReg); 3209 } 3210 3211 // Add argument registers to the end of the list so that they are known live 3212 // into the call. 3213 for (auto &RegToPass : RegsToPass) { 3214 Ops.push_back(DAG.getRegister(RegToPass.first, 3215 RegToPass.second.getValueType())); 3216 } 3217 3218 // Add a register mask operand representing the call-preserved registers. 3219 3220 auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo()); 3221 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 3222 assert(Mask && "Missing call preserved mask for calling convention"); 3223 Ops.push_back(DAG.getRegisterMask(Mask)); 3224 3225 if (InFlag.getNode()) 3226 Ops.push_back(InFlag); 3227 3228 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3229 3230 // If we're doing a tall call, use a TC_RETURN here rather than an 3231 // actual call instruction. 3232 if (IsTailCall) { 3233 MFI.setHasTailCall(); 3234 return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops); 3235 } 3236 3237 // Returns a chain and a flag for retval copy to use. 3238 SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops); 3239 Chain = Call.getValue(0); 3240 InFlag = Call.getValue(1); 3241 3242 uint64_t CalleePopBytes = NumBytes; 3243 Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32), 3244 DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32), 3245 InFlag, DL); 3246 if (!Ins.empty()) 3247 InFlag = Chain.getValue(1); 3248 3249 // Handle result values, copying them out of physregs into vregs that we 3250 // return. 3251 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3252 InVals, IsThisReturn, 3253 IsThisReturn ? OutVals[0] : SDValue()); 3254 } 3255 3256 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC, 3257 // except for applying the wave size scale to the increment amount. 3258 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl( 3259 SDValue Op, SelectionDAG &DAG) const { 3260 const MachineFunction &MF = DAG.getMachineFunction(); 3261 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 3262 3263 SDLoc dl(Op); 3264 EVT VT = Op.getValueType(); 3265 SDValue Tmp1 = Op; 3266 SDValue Tmp2 = Op.getValue(1); 3267 SDValue Tmp3 = Op.getOperand(2); 3268 SDValue Chain = Tmp1.getOperand(0); 3269 3270 Register SPReg = Info->getStackPtrOffsetReg(); 3271 3272 // Chain the dynamic stack allocation so that it doesn't modify the stack 3273 // pointer when other instructions are using the stack. 3274 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 3275 3276 SDValue Size = Tmp2.getOperand(1); 3277 SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT); 3278 Chain = SP.getValue(1); 3279 MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue(); 3280 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 3281 const TargetFrameLowering *TFL = ST.getFrameLowering(); 3282 unsigned Opc = 3283 TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ? 3284 ISD::ADD : ISD::SUB; 3285 3286 SDValue ScaledSize = DAG.getNode( 3287 ISD::SHL, dl, VT, Size, 3288 DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32)); 3289 3290 Align StackAlign = TFL->getStackAlign(); 3291 Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value 3292 if (Alignment && *Alignment > StackAlign) { 3293 Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1, 3294 DAG.getConstant(-(uint64_t)Alignment->value() 3295 << ST.getWavefrontSizeLog2(), 3296 dl, VT)); 3297 } 3298 3299 Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain 3300 Tmp2 = DAG.getCALLSEQ_END( 3301 Chain, DAG.getIntPtrConstant(0, dl, true), 3302 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 3303 3304 return DAG.getMergeValues({Tmp1, Tmp2}, dl); 3305 } 3306 3307 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 3308 SelectionDAG &DAG) const { 3309 // We only handle constant sizes here to allow non-entry block, static sized 3310 // allocas. A truly dynamic value is more difficult to support because we 3311 // don't know if the size value is uniform or not. If the size isn't uniform, 3312 // we would need to do a wave reduction to get the maximum size to know how 3313 // much to increment the uniform stack pointer. 3314 SDValue Size = Op.getOperand(1); 3315 if (isa<ConstantSDNode>(Size)) 3316 return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion. 3317 3318 return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG); 3319 } 3320 3321 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT, 3322 const MachineFunction &MF) const { 3323 Register Reg = StringSwitch<Register>(RegName) 3324 .Case("m0", AMDGPU::M0) 3325 .Case("exec", AMDGPU::EXEC) 3326 .Case("exec_lo", AMDGPU::EXEC_LO) 3327 .Case("exec_hi", AMDGPU::EXEC_HI) 3328 .Case("flat_scratch", AMDGPU::FLAT_SCR) 3329 .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO) 3330 .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI) 3331 .Default(Register()); 3332 3333 if (Reg == AMDGPU::NoRegister) { 3334 report_fatal_error(Twine("invalid register name \"" 3335 + StringRef(RegName) + "\".")); 3336 3337 } 3338 3339 if (!Subtarget->hasFlatScrRegister() && 3340 Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) { 3341 report_fatal_error(Twine("invalid register \"" 3342 + StringRef(RegName) + "\" for subtarget.")); 3343 } 3344 3345 switch (Reg) { 3346 case AMDGPU::M0: 3347 case AMDGPU::EXEC_LO: 3348 case AMDGPU::EXEC_HI: 3349 case AMDGPU::FLAT_SCR_LO: 3350 case AMDGPU::FLAT_SCR_HI: 3351 if (VT.getSizeInBits() == 32) 3352 return Reg; 3353 break; 3354 case AMDGPU::EXEC: 3355 case AMDGPU::FLAT_SCR: 3356 if (VT.getSizeInBits() == 64) 3357 return Reg; 3358 break; 3359 default: 3360 llvm_unreachable("missing register type checking"); 3361 } 3362 3363 report_fatal_error(Twine("invalid type for register \"" 3364 + StringRef(RegName) + "\".")); 3365 } 3366 3367 // If kill is not the last instruction, split the block so kill is always a 3368 // proper terminator. 3369 MachineBasicBlock * 3370 SITargetLowering::splitKillBlock(MachineInstr &MI, 3371 MachineBasicBlock *BB) const { 3372 MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/); 3373 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3374 MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode())); 3375 return SplitBB; 3376 } 3377 3378 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true, 3379 // \p MI will be the only instruction in the loop body block. Otherwise, it will 3380 // be the first instruction in the remainder block. 3381 // 3382 /// \returns { LoopBody, Remainder } 3383 static std::pair<MachineBasicBlock *, MachineBasicBlock *> 3384 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) { 3385 MachineFunction *MF = MBB.getParent(); 3386 MachineBasicBlock::iterator I(&MI); 3387 3388 // To insert the loop we need to split the block. Move everything after this 3389 // point to a new block, and insert a new empty block between the two. 3390 MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock(); 3391 MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock(); 3392 MachineFunction::iterator MBBI(MBB); 3393 ++MBBI; 3394 3395 MF->insert(MBBI, LoopBB); 3396 MF->insert(MBBI, RemainderBB); 3397 3398 LoopBB->addSuccessor(LoopBB); 3399 LoopBB->addSuccessor(RemainderBB); 3400 3401 // Move the rest of the block into a new block. 3402 RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB); 3403 3404 if (InstInLoop) { 3405 auto Next = std::next(I); 3406 3407 // Move instruction to loop body. 3408 LoopBB->splice(LoopBB->begin(), &MBB, I, Next); 3409 3410 // Move the rest of the block. 3411 RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end()); 3412 } else { 3413 RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end()); 3414 } 3415 3416 MBB.addSuccessor(LoopBB); 3417 3418 return std::make_pair(LoopBB, RemainderBB); 3419 } 3420 3421 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it. 3422 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const { 3423 MachineBasicBlock *MBB = MI.getParent(); 3424 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3425 auto I = MI.getIterator(); 3426 auto E = std::next(I); 3427 3428 BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT)) 3429 .addImm(0); 3430 3431 MIBundleBuilder Bundler(*MBB, I, E); 3432 finalizeBundle(*MBB, Bundler.begin()); 3433 } 3434 3435 MachineBasicBlock * 3436 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI, 3437 MachineBasicBlock *BB) const { 3438 const DebugLoc &DL = MI.getDebugLoc(); 3439 3440 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3441 3442 MachineBasicBlock *LoopBB; 3443 MachineBasicBlock *RemainderBB; 3444 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3445 3446 // Apparently kill flags are only valid if the def is in the same block? 3447 if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0)) 3448 Src->setIsKill(false); 3449 3450 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true); 3451 3452 MachineBasicBlock::iterator I = LoopBB->end(); 3453 3454 const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg( 3455 AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1); 3456 3457 // Clear TRAP_STS.MEM_VIOL 3458 BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32)) 3459 .addImm(0) 3460 .addImm(EncodedReg); 3461 3462 bundleInstWithWaitcnt(MI); 3463 3464 Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3465 3466 // Load and check TRAP_STS.MEM_VIOL 3467 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg) 3468 .addImm(EncodedReg); 3469 3470 // FIXME: Do we need to use an isel pseudo that may clobber scc? 3471 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 3472 .addReg(Reg, RegState::Kill) 3473 .addImm(0); 3474 BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 3475 .addMBB(LoopBB); 3476 3477 return RemainderBB; 3478 } 3479 3480 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the 3481 // wavefront. If the value is uniform and just happens to be in a VGPR, this 3482 // will only do one iteration. In the worst case, this will loop 64 times. 3483 // 3484 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value. 3485 static MachineBasicBlock::iterator 3486 emitLoadM0FromVGPRLoop(const SIInstrInfo *TII, MachineRegisterInfo &MRI, 3487 MachineBasicBlock &OrigBB, MachineBasicBlock &LoopBB, 3488 const DebugLoc &DL, const MachineOperand &Idx, 3489 unsigned InitReg, unsigned ResultReg, unsigned PhiReg, 3490 unsigned InitSaveExecReg, int Offset, bool UseGPRIdxMode, 3491 Register &SGPRIdxReg) { 3492 3493 MachineFunction *MF = OrigBB.getParent(); 3494 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3495 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3496 MachineBasicBlock::iterator I = LoopBB.begin(); 3497 3498 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3499 Register PhiExec = MRI.createVirtualRegister(BoolRC); 3500 Register NewExec = MRI.createVirtualRegister(BoolRC); 3501 Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3502 Register CondReg = MRI.createVirtualRegister(BoolRC); 3503 3504 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg) 3505 .addReg(InitReg) 3506 .addMBB(&OrigBB) 3507 .addReg(ResultReg) 3508 .addMBB(&LoopBB); 3509 3510 BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec) 3511 .addReg(InitSaveExecReg) 3512 .addMBB(&OrigBB) 3513 .addReg(NewExec) 3514 .addMBB(&LoopBB); 3515 3516 // Read the next variant <- also loop target. 3517 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg) 3518 .addReg(Idx.getReg(), getUndefRegState(Idx.isUndef())); 3519 3520 // Compare the just read M0 value to all possible Idx values. 3521 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg) 3522 .addReg(CurrentIdxReg) 3523 .addReg(Idx.getReg(), 0, Idx.getSubReg()); 3524 3525 // Update EXEC, save the original EXEC value to VCC. 3526 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32 3527 : AMDGPU::S_AND_SAVEEXEC_B64), 3528 NewExec) 3529 .addReg(CondReg, RegState::Kill); 3530 3531 MRI.setSimpleHint(NewExec, CondReg); 3532 3533 if (UseGPRIdxMode) { 3534 if (Offset == 0) { 3535 SGPRIdxReg = CurrentIdxReg; 3536 } else { 3537 SGPRIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass); 3538 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), SGPRIdxReg) 3539 .addReg(CurrentIdxReg, RegState::Kill) 3540 .addImm(Offset); 3541 } 3542 } else { 3543 // Move index from VCC into M0 3544 if (Offset == 0) { 3545 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 3546 .addReg(CurrentIdxReg, RegState::Kill); 3547 } else { 3548 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3549 .addReg(CurrentIdxReg, RegState::Kill) 3550 .addImm(Offset); 3551 } 3552 } 3553 3554 // Update EXEC, switch all done bits to 0 and all todo bits to 1. 3555 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3556 MachineInstr *InsertPt = 3557 BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term 3558 : AMDGPU::S_XOR_B64_term), Exec) 3559 .addReg(Exec) 3560 .addReg(NewExec); 3561 3562 // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use 3563 // s_cbranch_scc0? 3564 3565 // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover. 3566 BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) 3567 .addMBB(&LoopBB); 3568 3569 return InsertPt->getIterator(); 3570 } 3571 3572 // This has slightly sub-optimal regalloc when the source vector is killed by 3573 // the read. The register allocator does not understand that the kill is 3574 // per-workitem, so is kept alive for the whole loop so we end up not re-using a 3575 // subregister from it, using 1 more VGPR than necessary. This was saved when 3576 // this was expanded after register allocation. 3577 static MachineBasicBlock::iterator 3578 loadM0FromVGPR(const SIInstrInfo *TII, MachineBasicBlock &MBB, MachineInstr &MI, 3579 unsigned InitResultReg, unsigned PhiReg, int Offset, 3580 bool UseGPRIdxMode, Register &SGPRIdxReg) { 3581 MachineFunction *MF = MBB.getParent(); 3582 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3583 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3584 MachineRegisterInfo &MRI = MF->getRegInfo(); 3585 const DebugLoc &DL = MI.getDebugLoc(); 3586 MachineBasicBlock::iterator I(&MI); 3587 3588 const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3589 Register DstReg = MI.getOperand(0).getReg(); 3590 Register SaveExec = MRI.createVirtualRegister(BoolXExecRC); 3591 Register TmpExec = MRI.createVirtualRegister(BoolXExecRC); 3592 unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; 3593 unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64; 3594 3595 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec); 3596 3597 // Save the EXEC mask 3598 BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec) 3599 .addReg(Exec); 3600 3601 MachineBasicBlock *LoopBB; 3602 MachineBasicBlock *RemainderBB; 3603 std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false); 3604 3605 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3606 3607 auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx, 3608 InitResultReg, DstReg, PhiReg, TmpExec, 3609 Offset, UseGPRIdxMode, SGPRIdxReg); 3610 3611 MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock(); 3612 MachineFunction::iterator MBBI(LoopBB); 3613 ++MBBI; 3614 MF->insert(MBBI, LandingPad); 3615 LoopBB->removeSuccessor(RemainderBB); 3616 LandingPad->addSuccessor(RemainderBB); 3617 LoopBB->addSuccessor(LandingPad); 3618 MachineBasicBlock::iterator First = LandingPad->begin(); 3619 BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec) 3620 .addReg(SaveExec); 3621 3622 return InsPt; 3623 } 3624 3625 // Returns subreg index, offset 3626 static std::pair<unsigned, int> 3627 computeIndirectRegAndOffset(const SIRegisterInfo &TRI, 3628 const TargetRegisterClass *SuperRC, 3629 unsigned VecReg, 3630 int Offset) { 3631 int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32; 3632 3633 // Skip out of bounds offsets, or else we would end up using an undefined 3634 // register. 3635 if (Offset >= NumElts || Offset < 0) 3636 return std::make_pair(AMDGPU::sub0, Offset); 3637 3638 return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0); 3639 } 3640 3641 static void setM0ToIndexFromSGPR(const SIInstrInfo *TII, 3642 MachineRegisterInfo &MRI, MachineInstr &MI, 3643 int Offset) { 3644 MachineBasicBlock *MBB = MI.getParent(); 3645 const DebugLoc &DL = MI.getDebugLoc(); 3646 MachineBasicBlock::iterator I(&MI); 3647 3648 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3649 3650 assert(Idx->getReg() != AMDGPU::NoRegister); 3651 3652 if (Offset == 0) { 3653 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0).add(*Idx); 3654 } else { 3655 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0) 3656 .add(*Idx) 3657 .addImm(Offset); 3658 } 3659 } 3660 3661 static Register getIndirectSGPRIdx(const SIInstrInfo *TII, 3662 MachineRegisterInfo &MRI, MachineInstr &MI, 3663 int Offset) { 3664 MachineBasicBlock *MBB = MI.getParent(); 3665 const DebugLoc &DL = MI.getDebugLoc(); 3666 MachineBasicBlock::iterator I(&MI); 3667 3668 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3669 3670 if (Offset == 0) 3671 return Idx->getReg(); 3672 3673 Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass); 3674 BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp) 3675 .add(*Idx) 3676 .addImm(Offset); 3677 return Tmp; 3678 } 3679 3680 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI, 3681 MachineBasicBlock &MBB, 3682 const GCNSubtarget &ST) { 3683 const SIInstrInfo *TII = ST.getInstrInfo(); 3684 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3685 MachineFunction *MF = MBB.getParent(); 3686 MachineRegisterInfo &MRI = MF->getRegInfo(); 3687 3688 Register Dst = MI.getOperand(0).getReg(); 3689 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3690 Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg(); 3691 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3692 3693 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg); 3694 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3695 3696 unsigned SubReg; 3697 std::tie(SubReg, Offset) 3698 = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset); 3699 3700 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3701 3702 // Check for a SGPR index. 3703 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3704 MachineBasicBlock::iterator I(&MI); 3705 const DebugLoc &DL = MI.getDebugLoc(); 3706 3707 if (UseGPRIdxMode) { 3708 // TODO: Look at the uses to avoid the copy. This may require rescheduling 3709 // to avoid interfering with other uses, so probably requires a new 3710 // optimization pass. 3711 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3712 3713 const MCInstrDesc &GPRIDXDesc = 3714 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3715 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3716 .addReg(SrcReg) 3717 .addReg(Idx) 3718 .addImm(SubReg); 3719 } else { 3720 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3721 3722 BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3723 .addReg(SrcReg, 0, SubReg) 3724 .addReg(SrcReg, RegState::Implicit); 3725 } 3726 3727 MI.eraseFromParent(); 3728 3729 return &MBB; 3730 } 3731 3732 // Control flow needs to be inserted if indexing with a VGPR. 3733 const DebugLoc &DL = MI.getDebugLoc(); 3734 MachineBasicBlock::iterator I(&MI); 3735 3736 Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3737 Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3738 3739 BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg); 3740 3741 Register SGPRIdxReg; 3742 auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg, Offset, 3743 UseGPRIdxMode, SGPRIdxReg); 3744 3745 MachineBasicBlock *LoopBB = InsPt->getParent(); 3746 3747 if (UseGPRIdxMode) { 3748 const MCInstrDesc &GPRIDXDesc = 3749 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), true); 3750 3751 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3752 .addReg(SrcReg) 3753 .addReg(SGPRIdxReg) 3754 .addImm(SubReg); 3755 } else { 3756 BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst) 3757 .addReg(SrcReg, 0, SubReg) 3758 .addReg(SrcReg, RegState::Implicit); 3759 } 3760 3761 MI.eraseFromParent(); 3762 3763 return LoopBB; 3764 } 3765 3766 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI, 3767 MachineBasicBlock &MBB, 3768 const GCNSubtarget &ST) { 3769 const SIInstrInfo *TII = ST.getInstrInfo(); 3770 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 3771 MachineFunction *MF = MBB.getParent(); 3772 MachineRegisterInfo &MRI = MF->getRegInfo(); 3773 3774 Register Dst = MI.getOperand(0).getReg(); 3775 const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src); 3776 const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx); 3777 const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val); 3778 int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm(); 3779 const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg()); 3780 const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg()); 3781 3782 // This can be an immediate, but will be folded later. 3783 assert(Val->getReg()); 3784 3785 unsigned SubReg; 3786 std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC, 3787 SrcVec->getReg(), 3788 Offset); 3789 const bool UseGPRIdxMode = ST.useVGPRIndexMode(); 3790 3791 if (Idx->getReg() == AMDGPU::NoRegister) { 3792 MachineBasicBlock::iterator I(&MI); 3793 const DebugLoc &DL = MI.getDebugLoc(); 3794 3795 assert(Offset == 0); 3796 3797 BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst) 3798 .add(*SrcVec) 3799 .add(*Val) 3800 .addImm(SubReg); 3801 3802 MI.eraseFromParent(); 3803 return &MBB; 3804 } 3805 3806 // Check for a SGPR index. 3807 if (TII->getRegisterInfo().isSGPRClass(IdxRC)) { 3808 MachineBasicBlock::iterator I(&MI); 3809 const DebugLoc &DL = MI.getDebugLoc(); 3810 3811 if (UseGPRIdxMode) { 3812 Register Idx = getIndirectSGPRIdx(TII, MRI, MI, Offset); 3813 3814 const MCInstrDesc &GPRIDXDesc = 3815 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3816 BuildMI(MBB, I, DL, GPRIDXDesc, Dst) 3817 .addReg(SrcVec->getReg()) 3818 .add(*Val) 3819 .addReg(Idx) 3820 .addImm(SubReg); 3821 } else { 3822 setM0ToIndexFromSGPR(TII, MRI, MI, Offset); 3823 3824 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3825 TRI.getRegSizeInBits(*VecRC), 32, false); 3826 BuildMI(MBB, I, DL, MovRelDesc, Dst) 3827 .addReg(SrcVec->getReg()) 3828 .add(*Val) 3829 .addImm(SubReg); 3830 } 3831 MI.eraseFromParent(); 3832 return &MBB; 3833 } 3834 3835 // Control flow needs to be inserted if indexing with a VGPR. 3836 if (Val->isReg()) 3837 MRI.clearKillFlags(Val->getReg()); 3838 3839 const DebugLoc &DL = MI.getDebugLoc(); 3840 3841 Register PhiReg = MRI.createVirtualRegister(VecRC); 3842 3843 Register SGPRIdxReg; 3844 auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg, Offset, 3845 UseGPRIdxMode, SGPRIdxReg); 3846 MachineBasicBlock *LoopBB = InsPt->getParent(); 3847 3848 if (UseGPRIdxMode) { 3849 const MCInstrDesc &GPRIDXDesc = 3850 TII->getIndirectGPRIDXPseudo(TRI.getRegSizeInBits(*VecRC), false); 3851 3852 BuildMI(*LoopBB, InsPt, DL, GPRIDXDesc, Dst) 3853 .addReg(PhiReg) 3854 .add(*Val) 3855 .addReg(SGPRIdxReg) 3856 .addImm(AMDGPU::sub0); 3857 } else { 3858 const MCInstrDesc &MovRelDesc = TII->getIndirectRegWriteMovRelPseudo( 3859 TRI.getRegSizeInBits(*VecRC), 32, false); 3860 BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst) 3861 .addReg(PhiReg) 3862 .add(*Val) 3863 .addImm(AMDGPU::sub0); 3864 } 3865 3866 MI.eraseFromParent(); 3867 return LoopBB; 3868 } 3869 3870 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter( 3871 MachineInstr &MI, MachineBasicBlock *BB) const { 3872 3873 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 3874 MachineFunction *MF = BB->getParent(); 3875 SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 3876 3877 switch (MI.getOpcode()) { 3878 case AMDGPU::S_UADDO_PSEUDO: 3879 case AMDGPU::S_USUBO_PSEUDO: { 3880 const DebugLoc &DL = MI.getDebugLoc(); 3881 MachineOperand &Dest0 = MI.getOperand(0); 3882 MachineOperand &Dest1 = MI.getOperand(1); 3883 MachineOperand &Src0 = MI.getOperand(2); 3884 MachineOperand &Src1 = MI.getOperand(3); 3885 3886 unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO) 3887 ? AMDGPU::S_ADD_I32 3888 : AMDGPU::S_SUB_I32; 3889 BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1); 3890 3891 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg()) 3892 .addImm(1) 3893 .addImm(0); 3894 3895 MI.eraseFromParent(); 3896 return BB; 3897 } 3898 case AMDGPU::S_ADD_U64_PSEUDO: 3899 case AMDGPU::S_SUB_U64_PSEUDO: { 3900 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3901 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3902 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3903 const TargetRegisterClass *BoolRC = TRI->getBoolRC(); 3904 const DebugLoc &DL = MI.getDebugLoc(); 3905 3906 MachineOperand &Dest = MI.getOperand(0); 3907 MachineOperand &Src0 = MI.getOperand(1); 3908 MachineOperand &Src1 = MI.getOperand(2); 3909 3910 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3911 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 3912 3913 MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm( 3914 MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3915 MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm( 3916 MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3917 3918 MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm( 3919 MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass); 3920 MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm( 3921 MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass); 3922 3923 bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO); 3924 3925 unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32; 3926 unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32; 3927 BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0); 3928 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1); 3929 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3930 .addReg(DestSub0) 3931 .addImm(AMDGPU::sub0) 3932 .addReg(DestSub1) 3933 .addImm(AMDGPU::sub1); 3934 MI.eraseFromParent(); 3935 return BB; 3936 } 3937 case AMDGPU::V_ADD_U64_PSEUDO: 3938 case AMDGPU::V_SUB_U64_PSEUDO: { 3939 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 3940 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 3941 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 3942 const DebugLoc &DL = MI.getDebugLoc(); 3943 3944 bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO); 3945 3946 const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 3947 3948 Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3949 Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 3950 3951 Register CarryReg = MRI.createVirtualRegister(CarryRC); 3952 Register DeadCarryReg = MRI.createVirtualRegister(CarryRC); 3953 3954 MachineOperand &Dest = MI.getOperand(0); 3955 MachineOperand &Src0 = MI.getOperand(1); 3956 MachineOperand &Src1 = MI.getOperand(2); 3957 3958 const TargetRegisterClass *Src0RC = Src0.isReg() 3959 ? MRI.getRegClass(Src0.getReg()) 3960 : &AMDGPU::VReg_64RegClass; 3961 const TargetRegisterClass *Src1RC = Src1.isReg() 3962 ? MRI.getRegClass(Src1.getReg()) 3963 : &AMDGPU::VReg_64RegClass; 3964 3965 const TargetRegisterClass *Src0SubRC = 3966 TRI->getSubRegClass(Src0RC, AMDGPU::sub0); 3967 const TargetRegisterClass *Src1SubRC = 3968 TRI->getSubRegClass(Src1RC, AMDGPU::sub1); 3969 3970 MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm( 3971 MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC); 3972 MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm( 3973 MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC); 3974 3975 MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm( 3976 MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC); 3977 MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm( 3978 MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC); 3979 3980 unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64; 3981 MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0) 3982 .addReg(CarryReg, RegState::Define) 3983 .add(SrcReg0Sub0) 3984 .add(SrcReg1Sub0) 3985 .addImm(0); // clamp bit 3986 3987 unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64; 3988 MachineInstr *HiHalf = 3989 BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1) 3990 .addReg(DeadCarryReg, RegState::Define | RegState::Dead) 3991 .add(SrcReg0Sub1) 3992 .add(SrcReg1Sub1) 3993 .addReg(CarryReg, RegState::Kill) 3994 .addImm(0); // clamp bit 3995 3996 BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg()) 3997 .addReg(DestSub0) 3998 .addImm(AMDGPU::sub0) 3999 .addReg(DestSub1) 4000 .addImm(AMDGPU::sub1); 4001 TII->legalizeOperands(*LoHalf); 4002 TII->legalizeOperands(*HiHalf); 4003 MI.eraseFromParent(); 4004 return BB; 4005 } 4006 case AMDGPU::S_ADD_CO_PSEUDO: 4007 case AMDGPU::S_SUB_CO_PSEUDO: { 4008 // This pseudo has a chance to be selected 4009 // only from uniform add/subcarry node. All the VGPR operands 4010 // therefore assumed to be splat vectors. 4011 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4012 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4013 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4014 MachineBasicBlock::iterator MII = MI; 4015 const DebugLoc &DL = MI.getDebugLoc(); 4016 MachineOperand &Dest = MI.getOperand(0); 4017 MachineOperand &CarryDest = MI.getOperand(1); 4018 MachineOperand &Src0 = MI.getOperand(2); 4019 MachineOperand &Src1 = MI.getOperand(3); 4020 MachineOperand &Src2 = MI.getOperand(4); 4021 unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO) 4022 ? AMDGPU::S_ADDC_U32 4023 : AMDGPU::S_SUBB_U32; 4024 if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) { 4025 Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4026 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0) 4027 .addReg(Src0.getReg()); 4028 Src0.setReg(RegOp0); 4029 } 4030 if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) { 4031 Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4032 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1) 4033 .addReg(Src1.getReg()); 4034 Src1.setReg(RegOp1); 4035 } 4036 Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4037 if (TRI->isVectorRegister(MRI, Src2.getReg())) { 4038 BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2) 4039 .addReg(Src2.getReg()); 4040 Src2.setReg(RegOp2); 4041 } 4042 4043 const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg()); 4044 if (TRI->getRegSizeInBits(*Src2RC) == 64) { 4045 if (ST.hasScalarCompareEq64()) { 4046 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64)) 4047 .addReg(Src2.getReg()) 4048 .addImm(0); 4049 } else { 4050 const TargetRegisterClass *SubRC = 4051 TRI->getSubRegClass(Src2RC, AMDGPU::sub0); 4052 MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm( 4053 MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC); 4054 MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm( 4055 MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC); 4056 Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass); 4057 4058 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32) 4059 .add(Src2Sub0) 4060 .add(Src2Sub1); 4061 4062 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32)) 4063 .addReg(Src2_32, RegState::Kill) 4064 .addImm(0); 4065 } 4066 } else { 4067 BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32)) 4068 .addReg(Src2.getReg()) 4069 .addImm(0); 4070 } 4071 4072 BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1); 4073 4074 BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg()) 4075 .addReg(AMDGPU::SCC); 4076 MI.eraseFromParent(); 4077 return BB; 4078 } 4079 case AMDGPU::SI_INIT_M0: { 4080 BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(), 4081 TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0) 4082 .add(MI.getOperand(0)); 4083 MI.eraseFromParent(); 4084 return BB; 4085 } 4086 case AMDGPU::GET_GROUPSTATICSIZE: { 4087 assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA || 4088 getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL); 4089 DebugLoc DL = MI.getDebugLoc(); 4090 BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32)) 4091 .add(MI.getOperand(0)) 4092 .addImm(MFI->getLDSSize()); 4093 MI.eraseFromParent(); 4094 return BB; 4095 } 4096 case AMDGPU::SI_INDIRECT_SRC_V1: 4097 case AMDGPU::SI_INDIRECT_SRC_V2: 4098 case AMDGPU::SI_INDIRECT_SRC_V4: 4099 case AMDGPU::SI_INDIRECT_SRC_V8: 4100 case AMDGPU::SI_INDIRECT_SRC_V16: 4101 case AMDGPU::SI_INDIRECT_SRC_V32: 4102 return emitIndirectSrc(MI, *BB, *getSubtarget()); 4103 case AMDGPU::SI_INDIRECT_DST_V1: 4104 case AMDGPU::SI_INDIRECT_DST_V2: 4105 case AMDGPU::SI_INDIRECT_DST_V4: 4106 case AMDGPU::SI_INDIRECT_DST_V8: 4107 case AMDGPU::SI_INDIRECT_DST_V16: 4108 case AMDGPU::SI_INDIRECT_DST_V32: 4109 return emitIndirectDst(MI, *BB, *getSubtarget()); 4110 case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO: 4111 case AMDGPU::SI_KILL_I1_PSEUDO: 4112 return splitKillBlock(MI, BB); 4113 case AMDGPU::V_CNDMASK_B64_PSEUDO: { 4114 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4115 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4116 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4117 4118 Register Dst = MI.getOperand(0).getReg(); 4119 Register Src0 = MI.getOperand(1).getReg(); 4120 Register Src1 = MI.getOperand(2).getReg(); 4121 const DebugLoc &DL = MI.getDebugLoc(); 4122 Register SrcCond = MI.getOperand(3).getReg(); 4123 4124 Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4125 Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass); 4126 const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID); 4127 Register SrcCondCopy = MRI.createVirtualRegister(CondRC); 4128 4129 BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy) 4130 .addReg(SrcCond); 4131 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo) 4132 .addImm(0) 4133 .addReg(Src0, 0, AMDGPU::sub0) 4134 .addImm(0) 4135 .addReg(Src1, 0, AMDGPU::sub0) 4136 .addReg(SrcCondCopy); 4137 BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi) 4138 .addImm(0) 4139 .addReg(Src0, 0, AMDGPU::sub1) 4140 .addImm(0) 4141 .addReg(Src1, 0, AMDGPU::sub1) 4142 .addReg(SrcCondCopy); 4143 4144 BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst) 4145 .addReg(DstLo) 4146 .addImm(AMDGPU::sub0) 4147 .addReg(DstHi) 4148 .addImm(AMDGPU::sub1); 4149 MI.eraseFromParent(); 4150 return BB; 4151 } 4152 case AMDGPU::SI_BR_UNDEF: { 4153 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4154 const DebugLoc &DL = MI.getDebugLoc(); 4155 MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1)) 4156 .add(MI.getOperand(0)); 4157 Br->getOperand(1).setIsUndef(true); // read undef SCC 4158 MI.eraseFromParent(); 4159 return BB; 4160 } 4161 case AMDGPU::ADJCALLSTACKUP: 4162 case AMDGPU::ADJCALLSTACKDOWN: { 4163 const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>(); 4164 MachineInstrBuilder MIB(*MF, &MI); 4165 MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine) 4166 .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit); 4167 return BB; 4168 } 4169 case AMDGPU::SI_CALL_ISEL: { 4170 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 4171 const DebugLoc &DL = MI.getDebugLoc(); 4172 4173 unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF); 4174 4175 MachineInstrBuilder MIB; 4176 MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg); 4177 4178 for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I) 4179 MIB.add(MI.getOperand(I)); 4180 4181 MIB.cloneMemRefs(MI); 4182 MI.eraseFromParent(); 4183 return BB; 4184 } 4185 case AMDGPU::V_ADD_CO_U32_e32: 4186 case AMDGPU::V_SUB_CO_U32_e32: 4187 case AMDGPU::V_SUBREV_CO_U32_e32: { 4188 // TODO: Define distinct V_*_I32_Pseudo instructions instead. 4189 const DebugLoc &DL = MI.getDebugLoc(); 4190 unsigned Opc = MI.getOpcode(); 4191 4192 bool NeedClampOperand = false; 4193 if (TII->pseudoToMCOpcode(Opc) == -1) { 4194 Opc = AMDGPU::getVOPe64(Opc); 4195 NeedClampOperand = true; 4196 } 4197 4198 auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg()); 4199 if (TII->isVOP3(*I)) { 4200 const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>(); 4201 const SIRegisterInfo *TRI = ST.getRegisterInfo(); 4202 I.addReg(TRI->getVCC(), RegState::Define); 4203 } 4204 I.add(MI.getOperand(1)) 4205 .add(MI.getOperand(2)); 4206 if (NeedClampOperand) 4207 I.addImm(0); // clamp bit for e64 encoding 4208 4209 TII->legalizeOperands(*I); 4210 4211 MI.eraseFromParent(); 4212 return BB; 4213 } 4214 case AMDGPU::DS_GWS_INIT: 4215 case AMDGPU::DS_GWS_SEMA_V: 4216 case AMDGPU::DS_GWS_SEMA_BR: 4217 case AMDGPU::DS_GWS_SEMA_P: 4218 case AMDGPU::DS_GWS_SEMA_RELEASE_ALL: 4219 case AMDGPU::DS_GWS_BARRIER: 4220 // A s_waitcnt 0 is required to be the instruction immediately following. 4221 if (getSubtarget()->hasGWSAutoReplay()) { 4222 bundleInstWithWaitcnt(MI); 4223 return BB; 4224 } 4225 4226 return emitGWSMemViolTestLoop(MI, BB); 4227 case AMDGPU::S_SETREG_B32: { 4228 // Try to optimize cases that only set the denormal mode or rounding mode. 4229 // 4230 // If the s_setreg_b32 fully sets all of the bits in the rounding mode or 4231 // denormal mode to a constant, we can use s_round_mode or s_denorm_mode 4232 // instead. 4233 // 4234 // FIXME: This could be predicates on the immediate, but tablegen doesn't 4235 // allow you to have a no side effect instruction in the output of a 4236 // sideeffecting pattern. 4237 unsigned ID, Offset, Width; 4238 AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width); 4239 if (ID != AMDGPU::Hwreg::ID_MODE) 4240 return BB; 4241 4242 const unsigned WidthMask = maskTrailingOnes<unsigned>(Width); 4243 const unsigned SetMask = WidthMask << Offset; 4244 4245 if (getSubtarget()->hasDenormModeInst()) { 4246 unsigned SetDenormOp = 0; 4247 unsigned SetRoundOp = 0; 4248 4249 // The dedicated instructions can only set the whole denorm or round mode 4250 // at once, not a subset of bits in either. 4251 if (SetMask == 4252 (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) { 4253 // If this fully sets both the round and denorm mode, emit the two 4254 // dedicated instructions for these. 4255 SetRoundOp = AMDGPU::S_ROUND_MODE; 4256 SetDenormOp = AMDGPU::S_DENORM_MODE; 4257 } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) { 4258 SetRoundOp = AMDGPU::S_ROUND_MODE; 4259 } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) { 4260 SetDenormOp = AMDGPU::S_DENORM_MODE; 4261 } 4262 4263 if (SetRoundOp || SetDenormOp) { 4264 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 4265 MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg()); 4266 if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) { 4267 unsigned ImmVal = Def->getOperand(1).getImm(); 4268 if (SetRoundOp) { 4269 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp)) 4270 .addImm(ImmVal & 0xf); 4271 4272 // If we also have the denorm mode, get just the denorm mode bits. 4273 ImmVal >>= 4; 4274 } 4275 4276 if (SetDenormOp) { 4277 BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp)) 4278 .addImm(ImmVal & 0xf); 4279 } 4280 4281 MI.eraseFromParent(); 4282 return BB; 4283 } 4284 } 4285 } 4286 4287 // If only FP bits are touched, used the no side effects pseudo. 4288 if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK | 4289 AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) 4290 MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode)); 4291 4292 return BB; 4293 } 4294 default: 4295 return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB); 4296 } 4297 } 4298 4299 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const { 4300 return isTypeLegal(VT.getScalarType()); 4301 } 4302 4303 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const { 4304 // This currently forces unfolding various combinations of fsub into fma with 4305 // free fneg'd operands. As long as we have fast FMA (controlled by 4306 // isFMAFasterThanFMulAndFAdd), we should perform these. 4307 4308 // When fma is quarter rate, for f64 where add / sub are at best half rate, 4309 // most of these combines appear to be cycle neutral but save on instruction 4310 // count / code size. 4311 return true; 4312 } 4313 4314 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx, 4315 EVT VT) const { 4316 if (!VT.isVector()) { 4317 return MVT::i1; 4318 } 4319 return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements()); 4320 } 4321 4322 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const { 4323 // TODO: Should i16 be used always if legal? For now it would force VALU 4324 // shifts. 4325 return (VT == MVT::i16) ? MVT::i16 : MVT::i32; 4326 } 4327 4328 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const { 4329 return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts()) 4330 ? Ty.changeElementSize(16) 4331 : Ty.changeElementSize(32); 4332 } 4333 4334 // Answering this is somewhat tricky and depends on the specific device which 4335 // have different rates for fma or all f64 operations. 4336 // 4337 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other 4338 // regardless of which device (although the number of cycles differs between 4339 // devices), so it is always profitable for f64. 4340 // 4341 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable 4342 // only on full rate devices. Normally, we should prefer selecting v_mad_f32 4343 // which we can always do even without fused FP ops since it returns the same 4344 // result as the separate operations and since it is always full 4345 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32 4346 // however does not support denormals, so we do report fma as faster if we have 4347 // a fast fma device and require denormals. 4348 // 4349 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 4350 EVT VT) const { 4351 VT = VT.getScalarType(); 4352 4353 switch (VT.getSimpleVT().SimpleTy) { 4354 case MVT::f32: { 4355 // If mad is not available this depends only on if f32 fma is full rate. 4356 if (!Subtarget->hasMadMacF32Insts()) 4357 return Subtarget->hasFastFMAF32(); 4358 4359 // Otherwise f32 mad is always full rate and returns the same result as 4360 // the separate operations so should be preferred over fma. 4361 // However does not support denomals. 4362 if (hasFP32Denormals(MF)) 4363 return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts(); 4364 4365 // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32. 4366 return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts(); 4367 } 4368 case MVT::f64: 4369 return true; 4370 case MVT::f16: 4371 return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF); 4372 default: 4373 break; 4374 } 4375 4376 return false; 4377 } 4378 4379 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG, 4380 const SDNode *N) const { 4381 // TODO: Check future ftz flag 4382 // v_mad_f32/v_mac_f32 do not support denormals. 4383 EVT VT = N->getValueType(0); 4384 if (VT == MVT::f32) 4385 return Subtarget->hasMadMacF32Insts() && 4386 !hasFP32Denormals(DAG.getMachineFunction()); 4387 if (VT == MVT::f16) { 4388 return Subtarget->hasMadF16() && 4389 !hasFP64FP16Denormals(DAG.getMachineFunction()); 4390 } 4391 4392 return false; 4393 } 4394 4395 //===----------------------------------------------------------------------===// 4396 // Custom DAG Lowering Operations 4397 //===----------------------------------------------------------------------===// 4398 4399 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4400 // wider vector type is legal. 4401 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op, 4402 SelectionDAG &DAG) const { 4403 unsigned Opc = Op.getOpcode(); 4404 EVT VT = Op.getValueType(); 4405 assert(VT == MVT::v4f16 || VT == MVT::v4i16); 4406 4407 SDValue Lo, Hi; 4408 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 4409 4410 SDLoc SL(Op); 4411 SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo, 4412 Op->getFlags()); 4413 SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi, 4414 Op->getFlags()); 4415 4416 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4417 } 4418 4419 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the 4420 // wider vector type is legal. 4421 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op, 4422 SelectionDAG &DAG) const { 4423 unsigned Opc = Op.getOpcode(); 4424 EVT VT = Op.getValueType(); 4425 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4426 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4427 4428 SDValue Lo0, Hi0; 4429 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4430 SDValue Lo1, Hi1; 4431 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4432 4433 SDLoc SL(Op); 4434 4435 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, 4436 Op->getFlags()); 4437 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, 4438 Op->getFlags()); 4439 4440 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4441 } 4442 4443 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op, 4444 SelectionDAG &DAG) const { 4445 unsigned Opc = Op.getOpcode(); 4446 EVT VT = Op.getValueType(); 4447 assert(VT == MVT::v4i16 || VT == MVT::v4f16 || VT == MVT::v4f32 || 4448 VT == MVT::v8f32 || VT == MVT::v16f32 || VT == MVT::v32f32); 4449 4450 SDValue Lo0, Hi0; 4451 std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0); 4452 SDValue Lo1, Hi1; 4453 std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1); 4454 SDValue Lo2, Hi2; 4455 std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2); 4456 4457 SDLoc SL(Op); 4458 4459 SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2, 4460 Op->getFlags()); 4461 SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2, 4462 Op->getFlags()); 4463 4464 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi); 4465 } 4466 4467 4468 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const { 4469 switch (Op.getOpcode()) { 4470 default: return AMDGPUTargetLowering::LowerOperation(Op, DAG); 4471 case ISD::BRCOND: return LowerBRCOND(Op, DAG); 4472 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG); 4473 case ISD::LOAD: { 4474 SDValue Result = LowerLOAD(Op, DAG); 4475 assert((!Result.getNode() || 4476 Result.getNode()->getNumValues() == 2) && 4477 "Load should return a value and a chain"); 4478 return Result; 4479 } 4480 4481 case ISD::FSIN: 4482 case ISD::FCOS: 4483 return LowerTrig(Op, DAG); 4484 case ISD::SELECT: return LowerSELECT(Op, DAG); 4485 case ISD::FDIV: return LowerFDIV(Op, DAG); 4486 case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG); 4487 case ISD::STORE: return LowerSTORE(Op, DAG); 4488 case ISD::GlobalAddress: { 4489 MachineFunction &MF = DAG.getMachineFunction(); 4490 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 4491 return LowerGlobalAddress(MFI, Op, DAG); 4492 } 4493 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG); 4494 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG); 4495 case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG); 4496 case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG); 4497 case ISD::INSERT_SUBVECTOR: 4498 return lowerINSERT_SUBVECTOR(Op, DAG); 4499 case ISD::INSERT_VECTOR_ELT: 4500 return lowerINSERT_VECTOR_ELT(Op, DAG); 4501 case ISD::EXTRACT_VECTOR_ELT: 4502 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 4503 case ISD::VECTOR_SHUFFLE: 4504 return lowerVECTOR_SHUFFLE(Op, DAG); 4505 case ISD::BUILD_VECTOR: 4506 return lowerBUILD_VECTOR(Op, DAG); 4507 case ISD::FP_ROUND: 4508 return lowerFP_ROUND(Op, DAG); 4509 case ISD::TRAP: 4510 return lowerTRAP(Op, DAG); 4511 case ISD::DEBUGTRAP: 4512 return lowerDEBUGTRAP(Op, DAG); 4513 case ISD::FABS: 4514 case ISD::FNEG: 4515 case ISD::FCANONICALIZE: 4516 case ISD::BSWAP: 4517 return splitUnaryVectorOp(Op, DAG); 4518 case ISD::FMINNUM: 4519 case ISD::FMAXNUM: 4520 return lowerFMINNUM_FMAXNUM(Op, DAG); 4521 case ISD::FMA: 4522 return splitTernaryVectorOp(Op, DAG); 4523 case ISD::SHL: 4524 case ISD::SRA: 4525 case ISD::SRL: 4526 case ISD::ADD: 4527 case ISD::SUB: 4528 case ISD::MUL: 4529 case ISD::SMIN: 4530 case ISD::SMAX: 4531 case ISD::UMIN: 4532 case ISD::UMAX: 4533 case ISD::FADD: 4534 case ISD::FMUL: 4535 case ISD::FMINNUM_IEEE: 4536 case ISD::FMAXNUM_IEEE: 4537 case ISD::UADDSAT: 4538 case ISD::USUBSAT: 4539 case ISD::SADDSAT: 4540 case ISD::SSUBSAT: 4541 return splitBinaryVectorOp(Op, DAG); 4542 case ISD::SMULO: 4543 case ISD::UMULO: 4544 return lowerXMULO(Op, DAG); 4545 case ISD::DYNAMIC_STACKALLOC: 4546 return LowerDYNAMIC_STACKALLOC(Op, DAG); 4547 } 4548 return SDValue(); 4549 } 4550 4551 // Used for D16: Casts the result of an instruction into the right vector, 4552 // packs values if loads return unpacked values. 4553 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT, 4554 const SDLoc &DL, 4555 SelectionDAG &DAG, bool Unpacked) { 4556 if (!LoadVT.isVector()) 4557 return Result; 4558 4559 // Cast back to the original packed type or to a larger type that is a 4560 // multiple of 32 bit for D16. Widening the return type is a required for 4561 // legalization. 4562 EVT FittingLoadVT = LoadVT; 4563 if ((LoadVT.getVectorNumElements() % 2) == 1) { 4564 FittingLoadVT = 4565 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4566 LoadVT.getVectorNumElements() + 1); 4567 } 4568 4569 if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16. 4570 // Truncate to v2i16/v4i16. 4571 EVT IntLoadVT = FittingLoadVT.changeTypeToInteger(); 4572 4573 // Workaround legalizer not scalarizing truncate after vector op 4574 // legalization but not creating intermediate vector trunc. 4575 SmallVector<SDValue, 4> Elts; 4576 DAG.ExtractVectorElements(Result, Elts); 4577 for (SDValue &Elt : Elts) 4578 Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt); 4579 4580 // Pad illegal v1i16/v3fi6 to v4i16 4581 if ((LoadVT.getVectorNumElements() % 2) == 1) 4582 Elts.push_back(DAG.getUNDEF(MVT::i16)); 4583 4584 Result = DAG.getBuildVector(IntLoadVT, DL, Elts); 4585 4586 // Bitcast to original type (v2f16/v4f16). 4587 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4588 } 4589 4590 // Cast back to the original packed type. 4591 return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result); 4592 } 4593 4594 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode, 4595 MemSDNode *M, 4596 SelectionDAG &DAG, 4597 ArrayRef<SDValue> Ops, 4598 bool IsIntrinsic) const { 4599 SDLoc DL(M); 4600 4601 bool Unpacked = Subtarget->hasUnpackedD16VMem(); 4602 EVT LoadVT = M->getValueType(0); 4603 4604 EVT EquivLoadVT = LoadVT; 4605 if (LoadVT.isVector()) { 4606 if (Unpacked) { 4607 EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, 4608 LoadVT.getVectorNumElements()); 4609 } else if ((LoadVT.getVectorNumElements() % 2) == 1) { 4610 // Widen v3f16 to legal type 4611 EquivLoadVT = 4612 EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(), 4613 LoadVT.getVectorNumElements() + 1); 4614 } 4615 } 4616 4617 // Change from v4f16/v2f16 to EquivLoadVT. 4618 SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other); 4619 4620 SDValue Load 4621 = DAG.getMemIntrinsicNode( 4622 IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL, 4623 VTList, Ops, M->getMemoryVT(), 4624 M->getMemOperand()); 4625 4626 SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked); 4627 4628 return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL); 4629 } 4630 4631 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat, 4632 SelectionDAG &DAG, 4633 ArrayRef<SDValue> Ops) const { 4634 SDLoc DL(M); 4635 EVT LoadVT = M->getValueType(0); 4636 EVT EltType = LoadVT.getScalarType(); 4637 EVT IntVT = LoadVT.changeTypeToInteger(); 4638 4639 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 4640 4641 unsigned Opc = 4642 IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD; 4643 4644 if (IsD16) { 4645 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops); 4646 } 4647 4648 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 4649 if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32) 4650 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 4651 4652 if (isTypeLegal(LoadVT)) { 4653 return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT, 4654 M->getMemOperand(), DAG); 4655 } 4656 4657 EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT); 4658 SDVTList VTList = DAG.getVTList(CastVT, MVT::Other); 4659 SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT, 4660 M->getMemOperand(), DAG); 4661 return DAG.getMergeValues( 4662 {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)}, 4663 DL); 4664 } 4665 4666 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI, 4667 SDNode *N, SelectionDAG &DAG) { 4668 EVT VT = N->getValueType(0); 4669 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4670 unsigned CondCode = CD->getZExtValue(); 4671 if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode))) 4672 return DAG.getUNDEF(VT); 4673 4674 ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode); 4675 4676 SDValue LHS = N->getOperand(1); 4677 SDValue RHS = N->getOperand(2); 4678 4679 SDLoc DL(N); 4680 4681 EVT CmpVT = LHS.getValueType(); 4682 if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) { 4683 unsigned PromoteOp = ICmpInst::isSigned(IcInput) ? 4684 ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 4685 LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS); 4686 RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS); 4687 } 4688 4689 ISD::CondCode CCOpcode = getICmpCondCode(IcInput); 4690 4691 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4692 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4693 4694 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS, 4695 DAG.getCondCode(CCOpcode)); 4696 if (VT.bitsEq(CCVT)) 4697 return SetCC; 4698 return DAG.getZExtOrTrunc(SetCC, DL, VT); 4699 } 4700 4701 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI, 4702 SDNode *N, SelectionDAG &DAG) { 4703 EVT VT = N->getValueType(0); 4704 const auto *CD = cast<ConstantSDNode>(N->getOperand(3)); 4705 4706 unsigned CondCode = CD->getZExtValue(); 4707 if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode))) 4708 return DAG.getUNDEF(VT); 4709 4710 SDValue Src0 = N->getOperand(1); 4711 SDValue Src1 = N->getOperand(2); 4712 EVT CmpVT = Src0.getValueType(); 4713 SDLoc SL(N); 4714 4715 if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) { 4716 Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 4717 Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 4718 } 4719 4720 FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode); 4721 ISD::CondCode CCOpcode = getFCmpCondCode(IcInput); 4722 unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize(); 4723 EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize); 4724 SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0, 4725 Src1, DAG.getCondCode(CCOpcode)); 4726 if (VT.bitsEq(CCVT)) 4727 return SetCC; 4728 return DAG.getZExtOrTrunc(SetCC, SL, VT); 4729 } 4730 4731 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N, 4732 SelectionDAG &DAG) { 4733 EVT VT = N->getValueType(0); 4734 SDValue Src = N->getOperand(1); 4735 SDLoc SL(N); 4736 4737 if (Src.getOpcode() == ISD::SETCC) { 4738 // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...) 4739 return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0), 4740 Src.getOperand(1), Src.getOperand(2)); 4741 } 4742 if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) { 4743 // (ballot 0) -> 0 4744 if (Arg->isNullValue()) 4745 return DAG.getConstant(0, SL, VT); 4746 4747 // (ballot 1) -> EXEC/EXEC_LO 4748 if (Arg->isOne()) { 4749 Register Exec; 4750 if (VT.getScalarSizeInBits() == 32) 4751 Exec = AMDGPU::EXEC_LO; 4752 else if (VT.getScalarSizeInBits() == 64) 4753 Exec = AMDGPU::EXEC; 4754 else 4755 return SDValue(); 4756 4757 return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT); 4758 } 4759 } 4760 4761 // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0) 4762 // ISD::SETNE) 4763 return DAG.getNode( 4764 AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32), 4765 DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE)); 4766 } 4767 4768 void SITargetLowering::ReplaceNodeResults(SDNode *N, 4769 SmallVectorImpl<SDValue> &Results, 4770 SelectionDAG &DAG) const { 4771 switch (N->getOpcode()) { 4772 case ISD::INSERT_VECTOR_ELT: { 4773 if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG)) 4774 Results.push_back(Res); 4775 return; 4776 } 4777 case ISD::EXTRACT_VECTOR_ELT: { 4778 if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG)) 4779 Results.push_back(Res); 4780 return; 4781 } 4782 case ISD::INTRINSIC_WO_CHAIN: { 4783 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 4784 switch (IID) { 4785 case Intrinsic::amdgcn_cvt_pkrtz: { 4786 SDValue Src0 = N->getOperand(1); 4787 SDValue Src1 = N->getOperand(2); 4788 SDLoc SL(N); 4789 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32, 4790 Src0, Src1); 4791 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt)); 4792 return; 4793 } 4794 case Intrinsic::amdgcn_cvt_pknorm_i16: 4795 case Intrinsic::amdgcn_cvt_pknorm_u16: 4796 case Intrinsic::amdgcn_cvt_pk_i16: 4797 case Intrinsic::amdgcn_cvt_pk_u16: { 4798 SDValue Src0 = N->getOperand(1); 4799 SDValue Src1 = N->getOperand(2); 4800 SDLoc SL(N); 4801 unsigned Opcode; 4802 4803 if (IID == Intrinsic::amdgcn_cvt_pknorm_i16) 4804 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 4805 else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16) 4806 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 4807 else if (IID == Intrinsic::amdgcn_cvt_pk_i16) 4808 Opcode = AMDGPUISD::CVT_PK_I16_I32; 4809 else 4810 Opcode = AMDGPUISD::CVT_PK_U16_U32; 4811 4812 EVT VT = N->getValueType(0); 4813 if (isTypeLegal(VT)) 4814 Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1)); 4815 else { 4816 SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1); 4817 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt)); 4818 } 4819 return; 4820 } 4821 } 4822 break; 4823 } 4824 case ISD::INTRINSIC_W_CHAIN: { 4825 if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) { 4826 if (Res.getOpcode() == ISD::MERGE_VALUES) { 4827 // FIXME: Hacky 4828 for (unsigned I = 0; I < Res.getNumOperands(); I++) { 4829 Results.push_back(Res.getOperand(I)); 4830 } 4831 } else { 4832 Results.push_back(Res); 4833 Results.push_back(Res.getValue(1)); 4834 } 4835 return; 4836 } 4837 4838 break; 4839 } 4840 case ISD::SELECT: { 4841 SDLoc SL(N); 4842 EVT VT = N->getValueType(0); 4843 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT); 4844 SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1)); 4845 SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2)); 4846 4847 EVT SelectVT = NewVT; 4848 if (NewVT.bitsLT(MVT::i32)) { 4849 LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS); 4850 RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS); 4851 SelectVT = MVT::i32; 4852 } 4853 4854 SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT, 4855 N->getOperand(0), LHS, RHS); 4856 4857 if (NewVT != SelectVT) 4858 NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect); 4859 Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect)); 4860 return; 4861 } 4862 case ISD::FNEG: { 4863 if (N->getValueType(0) != MVT::v2f16) 4864 break; 4865 4866 SDLoc SL(N); 4867 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4868 4869 SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32, 4870 BC, 4871 DAG.getConstant(0x80008000, SL, MVT::i32)); 4872 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4873 return; 4874 } 4875 case ISD::FABS: { 4876 if (N->getValueType(0) != MVT::v2f16) 4877 break; 4878 4879 SDLoc SL(N); 4880 SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0)); 4881 4882 SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32, 4883 BC, 4884 DAG.getConstant(0x7fff7fff, SL, MVT::i32)); 4885 Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op)); 4886 return; 4887 } 4888 default: 4889 break; 4890 } 4891 } 4892 4893 /// Helper function for LowerBRCOND 4894 static SDNode *findUser(SDValue Value, unsigned Opcode) { 4895 4896 SDNode *Parent = Value.getNode(); 4897 for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end(); 4898 I != E; ++I) { 4899 4900 if (I.getUse().get() != Value) 4901 continue; 4902 4903 if (I->getOpcode() == Opcode) 4904 return *I; 4905 } 4906 return nullptr; 4907 } 4908 4909 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const { 4910 if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) { 4911 switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) { 4912 case Intrinsic::amdgcn_if: 4913 return AMDGPUISD::IF; 4914 case Intrinsic::amdgcn_else: 4915 return AMDGPUISD::ELSE; 4916 case Intrinsic::amdgcn_loop: 4917 return AMDGPUISD::LOOP; 4918 case Intrinsic::amdgcn_end_cf: 4919 llvm_unreachable("should not occur"); 4920 default: 4921 return 0; 4922 } 4923 } 4924 4925 // break, if_break, else_break are all only used as inputs to loop, not 4926 // directly as branch conditions. 4927 return 0; 4928 } 4929 4930 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const { 4931 const Triple &TT = getTargetMachine().getTargetTriple(); 4932 return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 4933 GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 4934 AMDGPU::shouldEmitConstantsToTextSection(TT); 4935 } 4936 4937 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const { 4938 // FIXME: Either avoid relying on address space here or change the default 4939 // address space for functions to avoid the explicit check. 4940 return (GV->getValueType()->isFunctionTy() || 4941 !isNonGlobalAddrSpace(GV->getAddressSpace())) && 4942 !shouldEmitFixup(GV) && 4943 !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 4944 } 4945 4946 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const { 4947 return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV); 4948 } 4949 4950 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const { 4951 if (!GV->hasExternalLinkage()) 4952 return true; 4953 4954 const auto OS = getTargetMachine().getTargetTriple().getOS(); 4955 return OS == Triple::AMDHSA || OS == Triple::AMDPAL; 4956 } 4957 4958 /// This transforms the control flow intrinsics to get the branch destination as 4959 /// last parameter, also switches branch target with BR if the need arise 4960 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND, 4961 SelectionDAG &DAG) const { 4962 SDLoc DL(BRCOND); 4963 4964 SDNode *Intr = BRCOND.getOperand(1).getNode(); 4965 SDValue Target = BRCOND.getOperand(2); 4966 SDNode *BR = nullptr; 4967 SDNode *SetCC = nullptr; 4968 4969 if (Intr->getOpcode() == ISD::SETCC) { 4970 // As long as we negate the condition everything is fine 4971 SetCC = Intr; 4972 Intr = SetCC->getOperand(0).getNode(); 4973 4974 } else { 4975 // Get the target from BR if we don't negate the condition 4976 BR = findUser(BRCOND, ISD::BR); 4977 assert(BR && "brcond missing unconditional branch user"); 4978 Target = BR->getOperand(1); 4979 } 4980 4981 unsigned CFNode = isCFIntrinsic(Intr); 4982 if (CFNode == 0) { 4983 // This is a uniform branch so we don't need to legalize. 4984 return BRCOND; 4985 } 4986 4987 bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID || 4988 Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN; 4989 4990 assert(!SetCC || 4991 (SetCC->getConstantOperandVal(1) == 1 && 4992 cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() == 4993 ISD::SETNE)); 4994 4995 // operands of the new intrinsic call 4996 SmallVector<SDValue, 4> Ops; 4997 if (HaveChain) 4998 Ops.push_back(BRCOND.getOperand(0)); 4999 5000 Ops.append(Intr->op_begin() + (HaveChain ? 2 : 1), Intr->op_end()); 5001 Ops.push_back(Target); 5002 5003 ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end()); 5004 5005 // build the new intrinsic call 5006 SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode(); 5007 5008 if (!HaveChain) { 5009 SDValue Ops[] = { 5010 SDValue(Result, 0), 5011 BRCOND.getOperand(0) 5012 }; 5013 5014 Result = DAG.getMergeValues(Ops, DL).getNode(); 5015 } 5016 5017 if (BR) { 5018 // Give the branch instruction our target 5019 SDValue Ops[] = { 5020 BR->getOperand(0), 5021 BRCOND.getOperand(2) 5022 }; 5023 SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops); 5024 DAG.ReplaceAllUsesWith(BR, NewBR.getNode()); 5025 } 5026 5027 SDValue Chain = SDValue(Result, Result->getNumValues() - 1); 5028 5029 // Copy the intrinsic results to registers 5030 for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) { 5031 SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg); 5032 if (!CopyToReg) 5033 continue; 5034 5035 Chain = DAG.getCopyToReg( 5036 Chain, DL, 5037 CopyToReg->getOperand(1), 5038 SDValue(Result, i - 1), 5039 SDValue()); 5040 5041 DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0)); 5042 } 5043 5044 // Remove the old intrinsic from the chain 5045 DAG.ReplaceAllUsesOfValueWith( 5046 SDValue(Intr, Intr->getNumValues() - 1), 5047 Intr->getOperand(0)); 5048 5049 return Chain; 5050 } 5051 5052 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op, 5053 SelectionDAG &DAG) const { 5054 MVT VT = Op.getSimpleValueType(); 5055 SDLoc DL(Op); 5056 // Checking the depth 5057 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) 5058 return DAG.getConstant(0, DL, VT); 5059 5060 MachineFunction &MF = DAG.getMachineFunction(); 5061 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5062 // Check for kernel and shader functions 5063 if (Info->isEntryFunction()) 5064 return DAG.getConstant(0, DL, VT); 5065 5066 MachineFrameInfo &MFI = MF.getFrameInfo(); 5067 // There is a call to @llvm.returnaddress in this function 5068 MFI.setReturnAddressIsTaken(true); 5069 5070 const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo(); 5071 // Get the return address reg and mark it as an implicit live-in 5072 Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent())); 5073 5074 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5075 } 5076 5077 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG, 5078 SDValue Op, 5079 const SDLoc &DL, 5080 EVT VT) const { 5081 return Op.getValueType().bitsLE(VT) ? 5082 DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) : 5083 DAG.getNode(ISD::FP_ROUND, DL, VT, Op, 5084 DAG.getTargetConstant(0, DL, MVT::i32)); 5085 } 5086 5087 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const { 5088 assert(Op.getValueType() == MVT::f16 && 5089 "Do not know how to custom lower FP_ROUND for non-f16 type"); 5090 5091 SDValue Src = Op.getOperand(0); 5092 EVT SrcVT = Src.getValueType(); 5093 if (SrcVT != MVT::f64) 5094 return Op; 5095 5096 SDLoc DL(Op); 5097 5098 SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src); 5099 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16); 5100 return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc); 5101 } 5102 5103 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op, 5104 SelectionDAG &DAG) const { 5105 EVT VT = Op.getValueType(); 5106 const MachineFunction &MF = DAG.getMachineFunction(); 5107 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5108 bool IsIEEEMode = Info->getMode().IEEE; 5109 5110 // FIXME: Assert during selection that this is only selected for 5111 // ieee_mode. Currently a combine can produce the ieee version for non-ieee 5112 // mode functions, but this happens to be OK since it's only done in cases 5113 // where there is known no sNaN. 5114 if (IsIEEEMode) 5115 return expandFMINNUM_FMAXNUM(Op.getNode(), DAG); 5116 5117 if (VT == MVT::v4f16) 5118 return splitBinaryVectorOp(Op, DAG); 5119 return Op; 5120 } 5121 5122 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const { 5123 EVT VT = Op.getValueType(); 5124 SDLoc SL(Op); 5125 SDValue LHS = Op.getOperand(0); 5126 SDValue RHS = Op.getOperand(1); 5127 bool isSigned = Op.getOpcode() == ISD::SMULO; 5128 5129 if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) { 5130 const APInt &C = RHSC->getAPIntValue(); 5131 // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X } 5132 if (C.isPowerOf2()) { 5133 // smulo(x, signed_min) is same as umulo(x, signed_min). 5134 bool UseArithShift = isSigned && !C.isMinSignedValue(); 5135 SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32); 5136 SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt); 5137 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, 5138 DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL, 5139 SL, VT, Result, ShiftAmt), 5140 LHS, ISD::SETNE); 5141 return DAG.getMergeValues({ Result, Overflow }, SL); 5142 } 5143 } 5144 5145 SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS); 5146 SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU, 5147 SL, VT, LHS, RHS); 5148 5149 SDValue Sign = isSigned 5150 ? DAG.getNode(ISD::SRA, SL, VT, Result, 5151 DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32)) 5152 : DAG.getConstant(0, SL, VT); 5153 SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE); 5154 5155 return DAG.getMergeValues({ Result, Overflow }, SL); 5156 } 5157 5158 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const { 5159 SDLoc SL(Op); 5160 SDValue Chain = Op.getOperand(0); 5161 5162 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5163 !Subtarget->isTrapHandlerEnabled()) 5164 return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain); 5165 5166 MachineFunction &MF = DAG.getMachineFunction(); 5167 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5168 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5169 assert(UserSGPR != AMDGPU::NoRegister); 5170 SDValue QueuePtr = CreateLiveInRegister( 5171 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5172 SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64); 5173 SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01, 5174 QueuePtr, SDValue()); 5175 SDValue Ops[] = { 5176 ToReg, 5177 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16), 5178 SGPR01, 5179 ToReg.getValue(1) 5180 }; 5181 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5182 } 5183 5184 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const { 5185 SDLoc SL(Op); 5186 SDValue Chain = Op.getOperand(0); 5187 MachineFunction &MF = DAG.getMachineFunction(); 5188 5189 if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa || 5190 !Subtarget->isTrapHandlerEnabled()) { 5191 DiagnosticInfoUnsupported NoTrap(MF.getFunction(), 5192 "debugtrap handler not supported", 5193 Op.getDebugLoc(), 5194 DS_Warning); 5195 LLVMContext &Ctx = MF.getFunction().getContext(); 5196 Ctx.diagnose(NoTrap); 5197 return Chain; 5198 } 5199 5200 SDValue Ops[] = { 5201 Chain, 5202 DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16) 5203 }; 5204 return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops); 5205 } 5206 5207 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL, 5208 SelectionDAG &DAG) const { 5209 // FIXME: Use inline constants (src_{shared, private}_base) instead. 5210 if (Subtarget->hasApertureRegs()) { 5211 unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ? 5212 AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE : 5213 AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE; 5214 unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ? 5215 AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE : 5216 AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE; 5217 unsigned Encoding = 5218 AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ | 5219 Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ | 5220 WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_; 5221 5222 SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16); 5223 SDValue ApertureReg = SDValue( 5224 DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0); 5225 SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32); 5226 return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount); 5227 } 5228 5229 MachineFunction &MF = DAG.getMachineFunction(); 5230 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 5231 Register UserSGPR = Info->getQueuePtrUserSGPR(); 5232 assert(UserSGPR != AMDGPU::NoRegister); 5233 5234 SDValue QueuePtr = CreateLiveInRegister( 5235 DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64); 5236 5237 // Offset into amd_queue_t for group_segment_aperture_base_hi / 5238 // private_segment_aperture_base_hi. 5239 uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44; 5240 5241 SDValue Ptr = 5242 DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset)); 5243 5244 // TODO: Use custom target PseudoSourceValue. 5245 // TODO: We should use the value from the IR intrinsic call, but it might not 5246 // be available and how do we get it? 5247 MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS); 5248 return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo, 5249 commonAlignment(Align(64), StructOffset), 5250 MachineMemOperand::MODereferenceable | 5251 MachineMemOperand::MOInvariant); 5252 } 5253 5254 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op, 5255 SelectionDAG &DAG) const { 5256 SDLoc SL(Op); 5257 const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op); 5258 5259 SDValue Src = ASC->getOperand(0); 5260 SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64); 5261 5262 const AMDGPUTargetMachine &TM = 5263 static_cast<const AMDGPUTargetMachine &>(getTargetMachine()); 5264 5265 // flat -> local/private 5266 if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5267 unsigned DestAS = ASC->getDestAddressSpace(); 5268 5269 if (DestAS == AMDGPUAS::LOCAL_ADDRESS || 5270 DestAS == AMDGPUAS::PRIVATE_ADDRESS) { 5271 unsigned NullVal = TM.getNullPointerValue(DestAS); 5272 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5273 SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE); 5274 SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5275 5276 return DAG.getNode(ISD::SELECT, SL, MVT::i32, 5277 NonNull, Ptr, SegmentNullPtr); 5278 } 5279 } 5280 5281 // local/private -> flat 5282 if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) { 5283 unsigned SrcAS = ASC->getSrcAddressSpace(); 5284 5285 if (SrcAS == AMDGPUAS::LOCAL_ADDRESS || 5286 SrcAS == AMDGPUAS::PRIVATE_ADDRESS) { 5287 unsigned NullVal = TM.getNullPointerValue(SrcAS); 5288 SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32); 5289 5290 SDValue NonNull 5291 = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE); 5292 5293 SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG); 5294 SDValue CvtPtr 5295 = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture); 5296 5297 return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull, 5298 DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr), 5299 FlatNullPtr); 5300 } 5301 } 5302 5303 if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT && 5304 Src.getValueType() == MVT::i64) 5305 return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src); 5306 5307 // global <-> flat are no-ops and never emitted. 5308 5309 const MachineFunction &MF = DAG.getMachineFunction(); 5310 DiagnosticInfoUnsupported InvalidAddrSpaceCast( 5311 MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc()); 5312 DAG.getContext()->diagnose(InvalidAddrSpaceCast); 5313 5314 return DAG.getUNDEF(ASC->getValueType(0)); 5315 } 5316 5317 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from 5318 // the small vector and inserting them into the big vector. That is better than 5319 // the default expansion of doing it via a stack slot. Even though the use of 5320 // the stack slot would be optimized away afterwards, the stack slot itself 5321 // remains. 5322 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5323 SelectionDAG &DAG) const { 5324 SDValue Vec = Op.getOperand(0); 5325 SDValue Ins = Op.getOperand(1); 5326 SDValue Idx = Op.getOperand(2); 5327 EVT VecVT = Vec.getValueType(); 5328 EVT InsVT = Ins.getValueType(); 5329 EVT EltVT = VecVT.getVectorElementType(); 5330 unsigned InsNumElts = InsVT.getVectorNumElements(); 5331 unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue(); 5332 SDLoc SL(Op); 5333 5334 for (unsigned I = 0; I != InsNumElts; ++I) { 5335 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins, 5336 DAG.getConstant(I, SL, MVT::i32)); 5337 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt, 5338 DAG.getConstant(IdxVal + I, SL, MVT::i32)); 5339 } 5340 return Vec; 5341 } 5342 5343 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 5344 SelectionDAG &DAG) const { 5345 SDValue Vec = Op.getOperand(0); 5346 SDValue InsVal = Op.getOperand(1); 5347 SDValue Idx = Op.getOperand(2); 5348 EVT VecVT = Vec.getValueType(); 5349 EVT EltVT = VecVT.getVectorElementType(); 5350 unsigned VecSize = VecVT.getSizeInBits(); 5351 unsigned EltSize = EltVT.getSizeInBits(); 5352 5353 5354 assert(VecSize <= 64); 5355 5356 unsigned NumElts = VecVT.getVectorNumElements(); 5357 SDLoc SL(Op); 5358 auto KIdx = dyn_cast<ConstantSDNode>(Idx); 5359 5360 if (NumElts == 4 && EltSize == 16 && KIdx) { 5361 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec); 5362 5363 SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5364 DAG.getConstant(0, SL, MVT::i32)); 5365 SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec, 5366 DAG.getConstant(1, SL, MVT::i32)); 5367 5368 SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf); 5369 SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf); 5370 5371 unsigned Idx = KIdx->getZExtValue(); 5372 bool InsertLo = Idx < 2; 5373 SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16, 5374 InsertLo ? LoVec : HiVec, 5375 DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal), 5376 DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32)); 5377 5378 InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf); 5379 5380 SDValue Concat = InsertLo ? 5381 DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) : 5382 DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf }); 5383 5384 return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat); 5385 } 5386 5387 if (isa<ConstantSDNode>(Idx)) 5388 return SDValue(); 5389 5390 MVT IntVT = MVT::getIntegerVT(VecSize); 5391 5392 // Avoid stack access for dynamic indexing. 5393 // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec 5394 5395 // Create a congruent vector with the target value in each element so that 5396 // the required element can be masked and ORed into the target vector. 5397 SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT, 5398 DAG.getSplatBuildVector(VecVT, SL, InsVal)); 5399 5400 assert(isPowerOf2_32(EltSize)); 5401 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5402 5403 // Convert vector index to bit-index. 5404 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5405 5406 SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5407 SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT, 5408 DAG.getConstant(0xffff, SL, IntVT), 5409 ScaledIdx); 5410 5411 SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal); 5412 SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT, 5413 DAG.getNOT(SL, BFM, IntVT), BCVec); 5414 5415 SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS); 5416 return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI); 5417 } 5418 5419 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 5420 SelectionDAG &DAG) const { 5421 SDLoc SL(Op); 5422 5423 EVT ResultVT = Op.getValueType(); 5424 SDValue Vec = Op.getOperand(0); 5425 SDValue Idx = Op.getOperand(1); 5426 EVT VecVT = Vec.getValueType(); 5427 unsigned VecSize = VecVT.getSizeInBits(); 5428 EVT EltVT = VecVT.getVectorElementType(); 5429 assert(VecSize <= 64); 5430 5431 DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr); 5432 5433 // Make sure we do any optimizations that will make it easier to fold 5434 // source modifiers before obscuring it with bit operations. 5435 5436 // XXX - Why doesn't this get called when vector_shuffle is expanded? 5437 if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI)) 5438 return Combined; 5439 5440 unsigned EltSize = EltVT.getSizeInBits(); 5441 assert(isPowerOf2_32(EltSize)); 5442 5443 MVT IntVT = MVT::getIntegerVT(VecSize); 5444 SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32); 5445 5446 // Convert vector index to bit-index (* EltSize) 5447 SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor); 5448 5449 SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec); 5450 SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx); 5451 5452 if (ResultVT == MVT::f16) { 5453 SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt); 5454 return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result); 5455 } 5456 5457 return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT); 5458 } 5459 5460 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) { 5461 assert(Elt % 2 == 0); 5462 return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0); 5463 } 5464 5465 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op, 5466 SelectionDAG &DAG) const { 5467 SDLoc SL(Op); 5468 EVT ResultVT = Op.getValueType(); 5469 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op); 5470 5471 EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16; 5472 EVT EltVT = PackVT.getVectorElementType(); 5473 int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements(); 5474 5475 // vector_shuffle <0,1,6,7> lhs, rhs 5476 // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2) 5477 // 5478 // vector_shuffle <6,7,2,3> lhs, rhs 5479 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2) 5480 // 5481 // vector_shuffle <6,7,0,1> lhs, rhs 5482 // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0) 5483 5484 // Avoid scalarizing when both halves are reading from consecutive elements. 5485 SmallVector<SDValue, 4> Pieces; 5486 for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) { 5487 if (elementPairIsContiguous(SVN->getMask(), I)) { 5488 const int Idx = SVN->getMaskElt(I); 5489 int VecIdx = Idx < SrcNumElts ? 0 : 1; 5490 int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts; 5491 SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, 5492 PackVT, SVN->getOperand(VecIdx), 5493 DAG.getConstant(EltIdx, SL, MVT::i32)); 5494 Pieces.push_back(SubVec); 5495 } else { 5496 const int Idx0 = SVN->getMaskElt(I); 5497 const int Idx1 = SVN->getMaskElt(I + 1); 5498 int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1; 5499 int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1; 5500 int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts; 5501 int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts; 5502 5503 SDValue Vec0 = SVN->getOperand(VecIdx0); 5504 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5505 Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32)); 5506 5507 SDValue Vec1 = SVN->getOperand(VecIdx1); 5508 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 5509 Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32)); 5510 Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 })); 5511 } 5512 } 5513 5514 return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces); 5515 } 5516 5517 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op, 5518 SelectionDAG &DAG) const { 5519 SDLoc SL(Op); 5520 EVT VT = Op.getValueType(); 5521 5522 if (VT == MVT::v4i16 || VT == MVT::v4f16) { 5523 EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2); 5524 5525 // Turn into pair of packed build_vectors. 5526 // TODO: Special case for constants that can be materialized with s_mov_b64. 5527 SDValue Lo = DAG.getBuildVector(HalfVT, SL, 5528 { Op.getOperand(0), Op.getOperand(1) }); 5529 SDValue Hi = DAG.getBuildVector(HalfVT, SL, 5530 { Op.getOperand(2), Op.getOperand(3) }); 5531 5532 SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo); 5533 SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi); 5534 5535 SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi }); 5536 return DAG.getNode(ISD::BITCAST, SL, VT, Blend); 5537 } 5538 5539 assert(VT == MVT::v2f16 || VT == MVT::v2i16); 5540 assert(!Subtarget->hasVOP3PInsts() && "this should be legal"); 5541 5542 SDValue Lo = Op.getOperand(0); 5543 SDValue Hi = Op.getOperand(1); 5544 5545 // Avoid adding defined bits with the zero_extend. 5546 if (Hi.isUndef()) { 5547 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5548 SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo); 5549 return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo); 5550 } 5551 5552 Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi); 5553 Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi); 5554 5555 SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi, 5556 DAG.getConstant(16, SL, MVT::i32)); 5557 if (Lo.isUndef()) 5558 return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi); 5559 5560 Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo); 5561 Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo); 5562 5563 SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi); 5564 return DAG.getNode(ISD::BITCAST, SL, VT, Or); 5565 } 5566 5567 bool 5568 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const { 5569 // We can fold offsets for anything that doesn't require a GOT relocation. 5570 return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS || 5571 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS || 5572 GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) && 5573 !shouldEmitGOTReloc(GA->getGlobal()); 5574 } 5575 5576 static SDValue 5577 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV, 5578 const SDLoc &DL, int64_t Offset, EVT PtrVT, 5579 unsigned GAFlags = SIInstrInfo::MO_NONE) { 5580 assert(isInt<32>(Offset + 4) && "32-bit offset is expected!"); 5581 // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is 5582 // lowered to the following code sequence: 5583 // 5584 // For constant address space: 5585 // s_getpc_b64 s[0:1] 5586 // s_add_u32 s0, s0, $symbol 5587 // s_addc_u32 s1, s1, 0 5588 // 5589 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5590 // a fixup or relocation is emitted to replace $symbol with a literal 5591 // constant, which is a pc-relative offset from the encoding of the $symbol 5592 // operand to the global variable. 5593 // 5594 // For global address space: 5595 // s_getpc_b64 s[0:1] 5596 // s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo 5597 // s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi 5598 // 5599 // s_getpc_b64 returns the address of the s_add_u32 instruction and then 5600 // fixups or relocations are emitted to replace $symbol@*@lo and 5601 // $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant, 5602 // which is a 64-bit pc-relative offset from the encoding of the $symbol 5603 // operand to the global variable. 5604 // 5605 // What we want here is an offset from the value returned by s_getpc 5606 // (which is the address of the s_add_u32 instruction) to the global 5607 // variable, but since the encoding of $symbol starts 4 bytes after the start 5608 // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too 5609 // small. This requires us to add 4 to the global variable offset in order to 5610 // compute the correct address. Similarly for the s_addc_u32 instruction, the 5611 // encoding of $symbol starts 12 bytes after the start of the s_add_u32 5612 // instruction. 5613 SDValue PtrLo = 5614 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags); 5615 SDValue PtrHi; 5616 if (GAFlags == SIInstrInfo::MO_NONE) { 5617 PtrHi = DAG.getTargetConstant(0, DL, MVT::i32); 5618 } else { 5619 PtrHi = 5620 DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1); 5621 } 5622 return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi); 5623 } 5624 5625 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI, 5626 SDValue Op, 5627 SelectionDAG &DAG) const { 5628 GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op); 5629 SDLoc DL(GSD); 5630 EVT PtrVT = Op.getValueType(); 5631 5632 const GlobalValue *GV = GSD->getGlobal(); 5633 if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5634 shouldUseLDSConstAddress(GV)) || 5635 GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS || 5636 GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) { 5637 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS && 5638 GV->hasExternalLinkage()) { 5639 Type *Ty = GV->getValueType(); 5640 // HIP uses an unsized array `extern __shared__ T s[]` or similar 5641 // zero-sized type in other languages to declare the dynamic shared 5642 // memory which size is not known at the compile time. They will be 5643 // allocated by the runtime and placed directly after the static 5644 // allocated ones. They all share the same offset. 5645 if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) { 5646 assert(PtrVT == MVT::i32 && "32-bit pointer is expected."); 5647 // Adjust alignment for that dynamic shared memory array. 5648 MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV)); 5649 return SDValue( 5650 DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0); 5651 } 5652 } 5653 return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG); 5654 } 5655 5656 if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) { 5657 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(), 5658 SIInstrInfo::MO_ABS32_LO); 5659 return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA); 5660 } 5661 5662 if (shouldEmitFixup(GV)) 5663 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT); 5664 else if (shouldEmitPCReloc(GV)) 5665 return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT, 5666 SIInstrInfo::MO_REL32); 5667 5668 SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT, 5669 SIInstrInfo::MO_GOTPCREL32); 5670 5671 Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext()); 5672 PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS); 5673 const DataLayout &DataLayout = DAG.getDataLayout(); 5674 Align Alignment = DataLayout.getABITypeAlign(PtrTy); 5675 MachinePointerInfo PtrInfo 5676 = MachinePointerInfo::getGOT(DAG.getMachineFunction()); 5677 5678 return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment, 5679 MachineMemOperand::MODereferenceable | 5680 MachineMemOperand::MOInvariant); 5681 } 5682 5683 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain, 5684 const SDLoc &DL, SDValue V) const { 5685 // We can't use S_MOV_B32 directly, because there is no way to specify m0 as 5686 // the destination register. 5687 // 5688 // We can't use CopyToReg, because MachineCSE won't combine COPY instructions, 5689 // so we will end up with redundant moves to m0. 5690 // 5691 // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result. 5692 5693 // A Null SDValue creates a glue result. 5694 SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue, 5695 V, Chain); 5696 return SDValue(M0, 0); 5697 } 5698 5699 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG, 5700 SDValue Op, 5701 MVT VT, 5702 unsigned Offset) const { 5703 SDLoc SL(Op); 5704 SDValue Param = lowerKernargMemParameter( 5705 DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false); 5706 // The local size values will have the hi 16-bits as zero. 5707 return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param, 5708 DAG.getValueType(VT)); 5709 } 5710 5711 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5712 EVT VT) { 5713 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5714 "non-hsa intrinsic with hsa target", 5715 DL.getDebugLoc()); 5716 DAG.getContext()->diagnose(BadIntrin); 5717 return DAG.getUNDEF(VT); 5718 } 5719 5720 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL, 5721 EVT VT) { 5722 DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(), 5723 "intrinsic not supported on subtarget", 5724 DL.getDebugLoc()); 5725 DAG.getContext()->diagnose(BadIntrin); 5726 return DAG.getUNDEF(VT); 5727 } 5728 5729 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL, 5730 ArrayRef<SDValue> Elts) { 5731 assert(!Elts.empty()); 5732 MVT Type; 5733 unsigned NumElts; 5734 5735 if (Elts.size() == 1) { 5736 Type = MVT::f32; 5737 NumElts = 1; 5738 } else if (Elts.size() == 2) { 5739 Type = MVT::v2f32; 5740 NumElts = 2; 5741 } else if (Elts.size() == 3) { 5742 Type = MVT::v3f32; 5743 NumElts = 3; 5744 } else if (Elts.size() <= 4) { 5745 Type = MVT::v4f32; 5746 NumElts = 4; 5747 } else if (Elts.size() <= 8) { 5748 Type = MVT::v8f32; 5749 NumElts = 8; 5750 } else { 5751 assert(Elts.size() <= 16); 5752 Type = MVT::v16f32; 5753 NumElts = 16; 5754 } 5755 5756 SmallVector<SDValue, 16> VecElts(NumElts); 5757 for (unsigned i = 0; i < Elts.size(); ++i) { 5758 SDValue Elt = Elts[i]; 5759 if (Elt.getValueType() != MVT::f32) 5760 Elt = DAG.getBitcast(MVT::f32, Elt); 5761 VecElts[i] = Elt; 5762 } 5763 for (unsigned i = Elts.size(); i < NumElts; ++i) 5764 VecElts[i] = DAG.getUNDEF(MVT::f32); 5765 5766 if (NumElts == 1) 5767 return VecElts[0]; 5768 return DAG.getBuildVector(Type, DL, VecElts); 5769 } 5770 5771 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT, 5772 SDValue Src, int ExtraElts) { 5773 EVT SrcVT = Src.getValueType(); 5774 5775 SmallVector<SDValue, 8> Elts; 5776 5777 if (SrcVT.isVector()) 5778 DAG.ExtractVectorElements(Src, Elts); 5779 else 5780 Elts.push_back(Src); 5781 5782 SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType()); 5783 while (ExtraElts--) 5784 Elts.push_back(Undef); 5785 5786 return DAG.getBuildVector(CastVT, DL, Elts); 5787 } 5788 5789 // Re-construct the required return value for a image load intrinsic. 5790 // This is more complicated due to the optional use TexFailCtrl which means the required 5791 // return type is an aggregate 5792 static SDValue constructRetValue(SelectionDAG &DAG, 5793 MachineSDNode *Result, 5794 ArrayRef<EVT> ResultTypes, 5795 bool IsTexFail, bool Unpacked, bool IsD16, 5796 int DMaskPop, int NumVDataDwords, 5797 const SDLoc &DL, LLVMContext &Context) { 5798 // Determine the required return type. This is the same regardless of IsTexFail flag 5799 EVT ReqRetVT = ResultTypes[0]; 5800 int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1; 5801 int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5802 ReqRetNumElts : (ReqRetNumElts + 1) / 2; 5803 5804 int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ? 5805 DMaskPop : (DMaskPop + 1) / 2; 5806 5807 MVT DataDwordVT = NumDataDwords == 1 ? 5808 MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords); 5809 5810 MVT MaskPopVT = MaskPopDwords == 1 ? 5811 MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords); 5812 5813 SDValue Data(Result, 0); 5814 SDValue TexFail; 5815 5816 if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) { 5817 SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32); 5818 if (MaskPopVT.isVector()) { 5819 Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT, 5820 SDValue(Result, 0), ZeroIdx); 5821 } else { 5822 Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT, 5823 SDValue(Result, 0), ZeroIdx); 5824 } 5825 } 5826 5827 if (DataDwordVT.isVector()) 5828 Data = padEltsToUndef(DAG, DL, DataDwordVT, Data, 5829 NumDataDwords - MaskPopDwords); 5830 5831 if (IsD16) 5832 Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked); 5833 5834 EVT LegalReqRetVT = ReqRetVT; 5835 if (!ReqRetVT.isVector()) { 5836 Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data); 5837 } else { 5838 // We need to widen the return vector to a legal type 5839 if ((ReqRetVT.getVectorNumElements() % 2) == 1 && 5840 ReqRetVT.getVectorElementType().getSizeInBits() == 16) { 5841 LegalReqRetVT = 5842 EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(), 5843 ReqRetVT.getVectorNumElements() + 1); 5844 } 5845 } 5846 Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data); 5847 5848 if (IsTexFail) { 5849 TexFail = 5850 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0), 5851 DAG.getConstant(MaskPopDwords, DL, MVT::i32)); 5852 5853 return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL); 5854 } 5855 5856 if (Result->getNumValues() == 1) 5857 return Data; 5858 5859 return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL); 5860 } 5861 5862 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE, 5863 SDValue *LWE, bool &IsTexFail) { 5864 auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode()); 5865 5866 uint64_t Value = TexFailCtrlConst->getZExtValue(); 5867 if (Value) { 5868 IsTexFail = true; 5869 } 5870 5871 SDLoc DL(TexFailCtrlConst); 5872 *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32); 5873 Value &= ~(uint64_t)0x1; 5874 *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32); 5875 Value &= ~(uint64_t)0x2; 5876 5877 return Value == 0; 5878 } 5879 5880 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op, 5881 MVT PackVectorVT, 5882 SmallVectorImpl<SDValue> &PackedAddrs, 5883 unsigned DimIdx, unsigned EndIdx, 5884 unsigned NumGradients) { 5885 SDLoc DL(Op); 5886 for (unsigned I = DimIdx; I < EndIdx; I++) { 5887 SDValue Addr = Op.getOperand(I); 5888 5889 // Gradients are packed with undef for each coordinate. 5890 // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this: 5891 // 1D: undef,dx/dh; undef,dx/dv 5892 // 2D: dy/dh,dx/dh; dy/dv,dx/dv 5893 // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv 5894 if (((I + 1) >= EndIdx) || 5895 ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 || 5896 I == DimIdx + NumGradients - 1))) { 5897 if (Addr.getValueType() != MVT::i16) 5898 Addr = DAG.getBitcast(MVT::i16, Addr); 5899 Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr); 5900 } else { 5901 Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)}); 5902 I++; 5903 } 5904 Addr = DAG.getBitcast(MVT::f32, Addr); 5905 PackedAddrs.push_back(Addr); 5906 } 5907 } 5908 5909 SDValue SITargetLowering::lowerImage(SDValue Op, 5910 const AMDGPU::ImageDimIntrinsicInfo *Intr, 5911 SelectionDAG &DAG, bool WithChain) const { 5912 SDLoc DL(Op); 5913 MachineFunction &MF = DAG.getMachineFunction(); 5914 const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>(); 5915 const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode = 5916 AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode); 5917 const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim); 5918 const AMDGPU::MIMGLZMappingInfo *LZMappingInfo = 5919 AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode); 5920 const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo = 5921 AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode); 5922 unsigned IntrOpcode = Intr->BaseOpcode; 5923 bool IsGFX10Plus = AMDGPU::isGFX10Plus(*Subtarget); 5924 5925 SmallVector<EVT, 3> ResultTypes(Op->values()); 5926 SmallVector<EVT, 3> OrigResultTypes(Op->values()); 5927 bool IsD16 = false; 5928 bool IsG16 = false; 5929 bool IsA16 = false; 5930 SDValue VData; 5931 int NumVDataDwords; 5932 bool AdjustRetType = false; 5933 5934 // Offset of intrinsic arguments 5935 const unsigned ArgOffset = WithChain ? 2 : 1; 5936 5937 unsigned DMask; 5938 unsigned DMaskLanes = 0; 5939 5940 if (BaseOpcode->Atomic) { 5941 VData = Op.getOperand(2); 5942 5943 bool Is64Bit = VData.getValueType() == MVT::i64; 5944 if (BaseOpcode->AtomicX2) { 5945 SDValue VData2 = Op.getOperand(3); 5946 VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL, 5947 {VData, VData2}); 5948 if (Is64Bit) 5949 VData = DAG.getBitcast(MVT::v4i32, VData); 5950 5951 ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32; 5952 DMask = Is64Bit ? 0xf : 0x3; 5953 NumVDataDwords = Is64Bit ? 4 : 2; 5954 } else { 5955 DMask = Is64Bit ? 0x3 : 0x1; 5956 NumVDataDwords = Is64Bit ? 2 : 1; 5957 } 5958 } else { 5959 auto *DMaskConst = 5960 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex)); 5961 DMask = DMaskConst->getZExtValue(); 5962 DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask); 5963 5964 if (BaseOpcode->Store) { 5965 VData = Op.getOperand(2); 5966 5967 MVT StoreVT = VData.getSimpleValueType(); 5968 if (StoreVT.getScalarType() == MVT::f16) { 5969 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5970 return Op; // D16 is unsupported for this instruction 5971 5972 IsD16 = true; 5973 VData = handleD16VData(VData, DAG, true); 5974 } 5975 5976 NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32; 5977 } else { 5978 // Work out the num dwords based on the dmask popcount and underlying type 5979 // and whether packing is supported. 5980 MVT LoadVT = ResultTypes[0].getSimpleVT(); 5981 if (LoadVT.getScalarType() == MVT::f16) { 5982 if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16) 5983 return Op; // D16 is unsupported for this instruction 5984 5985 IsD16 = true; 5986 } 5987 5988 // Confirm that the return type is large enough for the dmask specified 5989 if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) || 5990 (!LoadVT.isVector() && DMaskLanes > 1)) 5991 return Op; 5992 5993 // The sq block of gfx8 and gfx9 do not estimate register use correctly 5994 // for d16 image_gather4, image_gather4_l, and image_gather4_lz 5995 // instructions. 5996 if (IsD16 && !Subtarget->hasUnpackedD16VMem() && 5997 !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug())) 5998 NumVDataDwords = (DMaskLanes + 1) / 2; 5999 else 6000 NumVDataDwords = DMaskLanes; 6001 6002 AdjustRetType = true; 6003 } 6004 } 6005 6006 unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd; 6007 SmallVector<SDValue, 4> VAddrs; 6008 6009 // Optimize _L to _LZ when _L is zero 6010 if (LZMappingInfo) { 6011 if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>( 6012 Op.getOperand(ArgOffset + Intr->LodIndex))) { 6013 if (ConstantLod->isZero() || ConstantLod->isNegative()) { 6014 IntrOpcode = LZMappingInfo->LZ; // set new opcode to _lz variant of _l 6015 VAddrEnd--; // remove 'lod' 6016 } 6017 } 6018 } 6019 6020 // Optimize _mip away, when 'lod' is zero 6021 if (MIPMappingInfo) { 6022 if (auto *ConstantLod = dyn_cast<ConstantSDNode>( 6023 Op.getOperand(ArgOffset + Intr->MipIndex))) { 6024 if (ConstantLod->isNullValue()) { 6025 IntrOpcode = MIPMappingInfo->NONMIP; // set new opcode to variant without _mip 6026 VAddrEnd--; // remove 'mip' 6027 } 6028 } 6029 } 6030 6031 // Push back extra arguments. 6032 for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++) 6033 VAddrs.push_back(Op.getOperand(ArgOffset + I)); 6034 6035 // Check for 16 bit addresses or derivatives and pack if true. 6036 MVT VAddrVT = 6037 Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType(); 6038 MVT VAddrScalarVT = VAddrVT.getScalarType(); 6039 MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16; 6040 IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6041 6042 VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType(); 6043 VAddrScalarVT = VAddrVT.getScalarType(); 6044 IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16; 6045 if (IsA16 || IsG16) { 6046 if (IsA16) { 6047 if (!ST->hasA16()) { 6048 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6049 "support 16 bit addresses\n"); 6050 return Op; 6051 } 6052 if (!IsG16) { 6053 LLVM_DEBUG( 6054 dbgs() << "Failed to lower image intrinsic: 16 bit addresses " 6055 "need 16 bit derivatives but got 32 bit derivatives\n"); 6056 return Op; 6057 } 6058 } else if (!ST->hasG16()) { 6059 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6060 "support 16 bit derivatives\n"); 6061 return Op; 6062 } 6063 6064 if (BaseOpcode->Gradients && !IsA16) { 6065 if (!ST->hasG16()) { 6066 LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not " 6067 "support 16 bit derivatives\n"); 6068 return Op; 6069 } 6070 // Activate g16 6071 const AMDGPU::MIMGG16MappingInfo *G16MappingInfo = 6072 AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode); 6073 IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16 6074 } 6075 6076 // Don't compress addresses for G16 6077 const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart); 6078 packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, 6079 ArgOffset + Intr->GradientStart, PackEndIdx, 6080 Intr->NumGradients); 6081 6082 if (!IsA16) { 6083 // Add uncompressed address 6084 for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++) 6085 VAddrs.push_back(Op.getOperand(I)); 6086 } 6087 } else { 6088 for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++) 6089 VAddrs.push_back(Op.getOperand(I)); 6090 } 6091 6092 // If the register allocator cannot place the address registers contiguously 6093 // without introducing moves, then using the non-sequential address encoding 6094 // is always preferable, since it saves VALU instructions and is usually a 6095 // wash in terms of code size or even better. 6096 // 6097 // However, we currently have no way of hinting to the register allocator that 6098 // MIMG addresses should be placed contiguously when it is possible to do so, 6099 // so force non-NSA for the common 2-address case as a heuristic. 6100 // 6101 // SIShrinkInstructions will convert NSA encodings to non-NSA after register 6102 // allocation when possible. 6103 bool UseNSA = 6104 ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3; 6105 SDValue VAddr; 6106 if (!UseNSA) 6107 VAddr = getBuildDwordsVector(DAG, DL, VAddrs); 6108 6109 SDValue True = DAG.getTargetConstant(1, DL, MVT::i1); 6110 SDValue False = DAG.getTargetConstant(0, DL, MVT::i1); 6111 SDValue Unorm; 6112 if (!BaseOpcode->Sampler) { 6113 Unorm = True; 6114 } else { 6115 auto UnormConst = 6116 cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex)); 6117 6118 Unorm = UnormConst->getZExtValue() ? True : False; 6119 } 6120 6121 SDValue TFE; 6122 SDValue LWE; 6123 SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex); 6124 bool IsTexFail = false; 6125 if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail)) 6126 return Op; 6127 6128 if (IsTexFail) { 6129 if (!DMaskLanes) { 6130 // Expecting to get an error flag since TFC is on - and dmask is 0 6131 // Force dmask to be at least 1 otherwise the instruction will fail 6132 DMask = 0x1; 6133 DMaskLanes = 1; 6134 NumVDataDwords = 1; 6135 } 6136 NumVDataDwords += 1; 6137 AdjustRetType = true; 6138 } 6139 6140 // Has something earlier tagged that the return type needs adjusting 6141 // This happens if the instruction is a load or has set TexFailCtrl flags 6142 if (AdjustRetType) { 6143 // NumVDataDwords reflects the true number of dwords required in the return type 6144 if (DMaskLanes == 0 && !BaseOpcode->Store) { 6145 // This is a no-op load. This can be eliminated 6146 SDValue Undef = DAG.getUNDEF(Op.getValueType()); 6147 if (isa<MemSDNode>(Op)) 6148 return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL); 6149 return Undef; 6150 } 6151 6152 EVT NewVT = NumVDataDwords > 1 ? 6153 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords) 6154 : MVT::i32; 6155 6156 ResultTypes[0] = NewVT; 6157 if (ResultTypes.size() == 3) { 6158 // Original result was aggregate type used for TexFailCtrl results 6159 // The actual instruction returns as a vector type which has now been 6160 // created. Remove the aggregate result. 6161 ResultTypes.erase(&ResultTypes[1]); 6162 } 6163 } 6164 6165 unsigned CPol = cast<ConstantSDNode>( 6166 Op.getOperand(ArgOffset + Intr->CachePolicyIndex))->getZExtValue(); 6167 if (BaseOpcode->Atomic) 6168 CPol |= AMDGPU::CPol::GLC; // TODO no-return optimization 6169 if (CPol & ~AMDGPU::CPol::ALL) 6170 return Op; 6171 6172 SmallVector<SDValue, 26> Ops; 6173 if (BaseOpcode->Store || BaseOpcode->Atomic) 6174 Ops.push_back(VData); // vdata 6175 if (UseNSA) 6176 append_range(Ops, VAddrs); 6177 else 6178 Ops.push_back(VAddr); 6179 Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex)); 6180 if (BaseOpcode->Sampler) 6181 Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex)); 6182 Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32)); 6183 if (IsGFX10Plus) 6184 Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32)); 6185 Ops.push_back(Unorm); 6186 Ops.push_back(DAG.getTargetConstant(CPol, DL, MVT::i32)); 6187 Ops.push_back(IsA16 && // r128, a16 for gfx9 6188 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False); 6189 if (IsGFX10Plus) 6190 Ops.push_back(IsA16 ? True : False); 6191 if (!Subtarget->hasGFX90AInsts()) { 6192 Ops.push_back(TFE); //tfe 6193 } else if (cast<ConstantSDNode>(TFE)->getZExtValue()) { 6194 report_fatal_error("TFE is not supported on this GPU"); 6195 } 6196 Ops.push_back(LWE); // lwe 6197 if (!IsGFX10Plus) 6198 Ops.push_back(DimInfo->DA ? True : False); 6199 if (BaseOpcode->HasD16) 6200 Ops.push_back(IsD16 ? True : False); 6201 if (isa<MemSDNode>(Op)) 6202 Ops.push_back(Op.getOperand(0)); // chain 6203 6204 int NumVAddrDwords = 6205 UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32; 6206 int Opcode = -1; 6207 6208 if (IsGFX10Plus) { 6209 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, 6210 UseNSA ? AMDGPU::MIMGEncGfx10NSA 6211 : AMDGPU::MIMGEncGfx10Default, 6212 NumVDataDwords, NumVAddrDwords); 6213 } else { 6214 if (Subtarget->hasGFX90AInsts()) { 6215 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx90a, 6216 NumVDataDwords, NumVAddrDwords); 6217 if (Opcode == -1) 6218 report_fatal_error( 6219 "requested image instruction is not supported on this GPU"); 6220 } 6221 if (Opcode == -1 && 6222 Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6223 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8, 6224 NumVDataDwords, NumVAddrDwords); 6225 if (Opcode == -1) 6226 Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6, 6227 NumVDataDwords, NumVAddrDwords); 6228 } 6229 assert(Opcode != -1); 6230 6231 MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops); 6232 if (auto MemOp = dyn_cast<MemSDNode>(Op)) { 6233 MachineMemOperand *MemRef = MemOp->getMemOperand(); 6234 DAG.setNodeMemRefs(NewNode, {MemRef}); 6235 } 6236 6237 if (BaseOpcode->AtomicX2) { 6238 SmallVector<SDValue, 1> Elt; 6239 DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1); 6240 return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL); 6241 } else if (!BaseOpcode->Store) { 6242 return constructRetValue(DAG, NewNode, 6243 OrigResultTypes, IsTexFail, 6244 Subtarget->hasUnpackedD16VMem(), IsD16, 6245 DMaskLanes, NumVDataDwords, DL, 6246 *DAG.getContext()); 6247 } 6248 6249 return SDValue(NewNode, 0); 6250 } 6251 6252 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc, 6253 SDValue Offset, SDValue CachePolicy, 6254 SelectionDAG &DAG) const { 6255 MachineFunction &MF = DAG.getMachineFunction(); 6256 6257 const DataLayout &DataLayout = DAG.getDataLayout(); 6258 Align Alignment = 6259 DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext())); 6260 6261 MachineMemOperand *MMO = MF.getMachineMemOperand( 6262 MachinePointerInfo(), 6263 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 6264 MachineMemOperand::MOInvariant, 6265 VT.getStoreSize(), Alignment); 6266 6267 if (!Offset->isDivergent()) { 6268 SDValue Ops[] = { 6269 Rsrc, 6270 Offset, // Offset 6271 CachePolicy 6272 }; 6273 6274 // Widen vec3 load to vec4. 6275 if (VT.isVector() && VT.getVectorNumElements() == 3) { 6276 EVT WidenedVT = 6277 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4); 6278 auto WidenedOp = DAG.getMemIntrinsicNode( 6279 AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT, 6280 MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize())); 6281 auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp, 6282 DAG.getVectorIdxConstant(0, DL)); 6283 return Subvector; 6284 } 6285 6286 return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL, 6287 DAG.getVTList(VT), Ops, VT, MMO); 6288 } 6289 6290 // We have a divergent offset. Emit a MUBUF buffer load instead. We can 6291 // assume that the buffer is unswizzled. 6292 SmallVector<SDValue, 4> Loads; 6293 unsigned NumLoads = 1; 6294 MVT LoadVT = VT.getSimpleVT(); 6295 unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1; 6296 assert((LoadVT.getScalarType() == MVT::i32 || 6297 LoadVT.getScalarType() == MVT::f32)); 6298 6299 if (NumElts == 8 || NumElts == 16) { 6300 NumLoads = NumElts / 4; 6301 LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4); 6302 } 6303 6304 SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue}); 6305 SDValue Ops[] = { 6306 DAG.getEntryNode(), // Chain 6307 Rsrc, // rsrc 6308 DAG.getConstant(0, DL, MVT::i32), // vindex 6309 {}, // voffset 6310 {}, // soffset 6311 {}, // offset 6312 CachePolicy, // cachepolicy 6313 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6314 }; 6315 6316 // Use the alignment to ensure that the required offsets will fit into the 6317 // immediate offsets. 6318 setBufferOffsets(Offset, DAG, &Ops[3], 6319 NumLoads > 1 ? Align(16 * NumLoads) : Align(4)); 6320 6321 uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue(); 6322 for (unsigned i = 0; i < NumLoads; ++i) { 6323 Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32); 6324 Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops, 6325 LoadVT, MMO, DAG)); 6326 } 6327 6328 if (NumElts == 8 || NumElts == 16) 6329 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads); 6330 6331 return Loads[0]; 6332 } 6333 6334 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 6335 SelectionDAG &DAG) const { 6336 MachineFunction &MF = DAG.getMachineFunction(); 6337 auto MFI = MF.getInfo<SIMachineFunctionInfo>(); 6338 6339 EVT VT = Op.getValueType(); 6340 SDLoc DL(Op); 6341 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6342 6343 // TODO: Should this propagate fast-math-flags? 6344 6345 switch (IntrinsicID) { 6346 case Intrinsic::amdgcn_implicit_buffer_ptr: { 6347 if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction())) 6348 return emitNonHSAIntrinsicError(DAG, DL, VT); 6349 return getPreloadedValue(DAG, *MFI, VT, 6350 AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR); 6351 } 6352 case Intrinsic::amdgcn_dispatch_ptr: 6353 case Intrinsic::amdgcn_queue_ptr: { 6354 if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) { 6355 DiagnosticInfoUnsupported BadIntrin( 6356 MF.getFunction(), "unsupported hsa intrinsic without hsa target", 6357 DL.getDebugLoc()); 6358 DAG.getContext()->diagnose(BadIntrin); 6359 return DAG.getUNDEF(VT); 6360 } 6361 6362 auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ? 6363 AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR; 6364 return getPreloadedValue(DAG, *MFI, VT, RegID); 6365 } 6366 case Intrinsic::amdgcn_implicitarg_ptr: { 6367 if (MFI->isEntryFunction()) 6368 return getImplicitArgPtr(DAG, DL); 6369 return getPreloadedValue(DAG, *MFI, VT, 6370 AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR); 6371 } 6372 case Intrinsic::amdgcn_kernarg_segment_ptr: { 6373 if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) { 6374 // This only makes sense to call in a kernel, so just lower to null. 6375 return DAG.getConstant(0, DL, VT); 6376 } 6377 6378 return getPreloadedValue(DAG, *MFI, VT, 6379 AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR); 6380 } 6381 case Intrinsic::amdgcn_dispatch_id: { 6382 return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID); 6383 } 6384 case Intrinsic::amdgcn_rcp: 6385 return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1)); 6386 case Intrinsic::amdgcn_rsq: 6387 return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6388 case Intrinsic::amdgcn_rsq_legacy: 6389 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6390 return emitRemovedIntrinsicError(DAG, DL, VT); 6391 return SDValue(); 6392 case Intrinsic::amdgcn_rcp_legacy: 6393 if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) 6394 return emitRemovedIntrinsicError(DAG, DL, VT); 6395 return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1)); 6396 case Intrinsic::amdgcn_rsq_clamp: { 6397 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6398 return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1)); 6399 6400 Type *Type = VT.getTypeForEVT(*DAG.getContext()); 6401 APFloat Max = APFloat::getLargest(Type->getFltSemantics()); 6402 APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true); 6403 6404 SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1)); 6405 SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq, 6406 DAG.getConstantFP(Max, DL, VT)); 6407 return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp, 6408 DAG.getConstantFP(Min, DL, VT)); 6409 } 6410 case Intrinsic::r600_read_ngroups_x: 6411 if (Subtarget->isAmdHsaOS()) 6412 return emitNonHSAIntrinsicError(DAG, DL, VT); 6413 6414 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6415 SI::KernelInputOffsets::NGROUPS_X, Align(4), 6416 false); 6417 case Intrinsic::r600_read_ngroups_y: 6418 if (Subtarget->isAmdHsaOS()) 6419 return emitNonHSAIntrinsicError(DAG, DL, VT); 6420 6421 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6422 SI::KernelInputOffsets::NGROUPS_Y, Align(4), 6423 false); 6424 case Intrinsic::r600_read_ngroups_z: 6425 if (Subtarget->isAmdHsaOS()) 6426 return emitNonHSAIntrinsicError(DAG, DL, VT); 6427 6428 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6429 SI::KernelInputOffsets::NGROUPS_Z, Align(4), 6430 false); 6431 case Intrinsic::r600_read_global_size_x: 6432 if (Subtarget->isAmdHsaOS()) 6433 return emitNonHSAIntrinsicError(DAG, DL, VT); 6434 6435 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6436 SI::KernelInputOffsets::GLOBAL_SIZE_X, 6437 Align(4), false); 6438 case Intrinsic::r600_read_global_size_y: 6439 if (Subtarget->isAmdHsaOS()) 6440 return emitNonHSAIntrinsicError(DAG, DL, VT); 6441 6442 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6443 SI::KernelInputOffsets::GLOBAL_SIZE_Y, 6444 Align(4), false); 6445 case Intrinsic::r600_read_global_size_z: 6446 if (Subtarget->isAmdHsaOS()) 6447 return emitNonHSAIntrinsicError(DAG, DL, VT); 6448 6449 return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(), 6450 SI::KernelInputOffsets::GLOBAL_SIZE_Z, 6451 Align(4), false); 6452 case Intrinsic::r600_read_local_size_x: 6453 if (Subtarget->isAmdHsaOS()) 6454 return emitNonHSAIntrinsicError(DAG, DL, VT); 6455 6456 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6457 SI::KernelInputOffsets::LOCAL_SIZE_X); 6458 case Intrinsic::r600_read_local_size_y: 6459 if (Subtarget->isAmdHsaOS()) 6460 return emitNonHSAIntrinsicError(DAG, DL, VT); 6461 6462 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6463 SI::KernelInputOffsets::LOCAL_SIZE_Y); 6464 case Intrinsic::r600_read_local_size_z: 6465 if (Subtarget->isAmdHsaOS()) 6466 return emitNonHSAIntrinsicError(DAG, DL, VT); 6467 6468 return lowerImplicitZextParam(DAG, Op, MVT::i16, 6469 SI::KernelInputOffsets::LOCAL_SIZE_Z); 6470 case Intrinsic::amdgcn_workgroup_id_x: 6471 return getPreloadedValue(DAG, *MFI, VT, 6472 AMDGPUFunctionArgInfo::WORKGROUP_ID_X); 6473 case Intrinsic::amdgcn_workgroup_id_y: 6474 return getPreloadedValue(DAG, *MFI, VT, 6475 AMDGPUFunctionArgInfo::WORKGROUP_ID_Y); 6476 case Intrinsic::amdgcn_workgroup_id_z: 6477 return getPreloadedValue(DAG, *MFI, VT, 6478 AMDGPUFunctionArgInfo::WORKGROUP_ID_Z); 6479 case Intrinsic::amdgcn_workitem_id_x: 6480 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6481 SDLoc(DAG.getEntryNode()), 6482 MFI->getArgInfo().WorkItemIDX); 6483 case Intrinsic::amdgcn_workitem_id_y: 6484 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6485 SDLoc(DAG.getEntryNode()), 6486 MFI->getArgInfo().WorkItemIDY); 6487 case Intrinsic::amdgcn_workitem_id_z: 6488 return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32, 6489 SDLoc(DAG.getEntryNode()), 6490 MFI->getArgInfo().WorkItemIDZ); 6491 case Intrinsic::amdgcn_wavefrontsize: 6492 return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(), 6493 SDLoc(Op), MVT::i32); 6494 case Intrinsic::amdgcn_s_buffer_load: { 6495 unsigned CPol = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 6496 if (CPol & ~AMDGPU::CPol::ALL) 6497 return Op; 6498 return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6499 DAG); 6500 } 6501 case Intrinsic::amdgcn_fdiv_fast: 6502 return lowerFDIV_FAST(Op, DAG); 6503 case Intrinsic::amdgcn_sin: 6504 return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1)); 6505 6506 case Intrinsic::amdgcn_cos: 6507 return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1)); 6508 6509 case Intrinsic::amdgcn_mul_u24: 6510 return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6511 case Intrinsic::amdgcn_mul_i24: 6512 return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6513 6514 case Intrinsic::amdgcn_log_clamp: { 6515 if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS) 6516 return SDValue(); 6517 6518 return emitRemovedIntrinsicError(DAG, DL, VT); 6519 } 6520 case Intrinsic::amdgcn_ldexp: 6521 return DAG.getNode(AMDGPUISD::LDEXP, DL, VT, 6522 Op.getOperand(1), Op.getOperand(2)); 6523 6524 case Intrinsic::amdgcn_fract: 6525 return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1)); 6526 6527 case Intrinsic::amdgcn_class: 6528 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT, 6529 Op.getOperand(1), Op.getOperand(2)); 6530 case Intrinsic::amdgcn_div_fmas: 6531 return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT, 6532 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6533 Op.getOperand(4)); 6534 6535 case Intrinsic::amdgcn_div_fixup: 6536 return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT, 6537 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6538 6539 case Intrinsic::amdgcn_div_scale: { 6540 const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3)); 6541 6542 // Translate to the operands expected by the machine instruction. The 6543 // first parameter must be the same as the first instruction. 6544 SDValue Numerator = Op.getOperand(1); 6545 SDValue Denominator = Op.getOperand(2); 6546 6547 // Note this order is opposite of the machine instruction's operations, 6548 // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The 6549 // intrinsic has the numerator as the first operand to match a normal 6550 // division operation. 6551 6552 SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator; 6553 6554 return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0, 6555 Denominator, Numerator); 6556 } 6557 case Intrinsic::amdgcn_icmp: { 6558 // There is a Pat that handles this variant, so return it as-is. 6559 if (Op.getOperand(1).getValueType() == MVT::i1 && 6560 Op.getConstantOperandVal(2) == 0 && 6561 Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE) 6562 return Op; 6563 return lowerICMPIntrinsic(*this, Op.getNode(), DAG); 6564 } 6565 case Intrinsic::amdgcn_fcmp: { 6566 return lowerFCMPIntrinsic(*this, Op.getNode(), DAG); 6567 } 6568 case Intrinsic::amdgcn_ballot: 6569 return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG); 6570 case Intrinsic::amdgcn_fmed3: 6571 return DAG.getNode(AMDGPUISD::FMED3, DL, VT, 6572 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6573 case Intrinsic::amdgcn_fdot2: 6574 return DAG.getNode(AMDGPUISD::FDOT2, DL, VT, 6575 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3), 6576 Op.getOperand(4)); 6577 case Intrinsic::amdgcn_fmul_legacy: 6578 return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT, 6579 Op.getOperand(1), Op.getOperand(2)); 6580 case Intrinsic::amdgcn_sffbh: 6581 return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1)); 6582 case Intrinsic::amdgcn_sbfe: 6583 return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT, 6584 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6585 case Intrinsic::amdgcn_ubfe: 6586 return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT, 6587 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6588 case Intrinsic::amdgcn_cvt_pkrtz: 6589 case Intrinsic::amdgcn_cvt_pknorm_i16: 6590 case Intrinsic::amdgcn_cvt_pknorm_u16: 6591 case Intrinsic::amdgcn_cvt_pk_i16: 6592 case Intrinsic::amdgcn_cvt_pk_u16: { 6593 // FIXME: Stop adding cast if v2f16/v2i16 are legal. 6594 EVT VT = Op.getValueType(); 6595 unsigned Opcode; 6596 6597 if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz) 6598 Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32; 6599 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16) 6600 Opcode = AMDGPUISD::CVT_PKNORM_I16_F32; 6601 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16) 6602 Opcode = AMDGPUISD::CVT_PKNORM_U16_F32; 6603 else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16) 6604 Opcode = AMDGPUISD::CVT_PK_I16_I32; 6605 else 6606 Opcode = AMDGPUISD::CVT_PK_U16_U32; 6607 6608 if (isTypeLegal(VT)) 6609 return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2)); 6610 6611 SDValue Node = DAG.getNode(Opcode, DL, MVT::i32, 6612 Op.getOperand(1), Op.getOperand(2)); 6613 return DAG.getNode(ISD::BITCAST, DL, VT, Node); 6614 } 6615 case Intrinsic::amdgcn_fmad_ftz: 6616 return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1), 6617 Op.getOperand(2), Op.getOperand(3)); 6618 6619 case Intrinsic::amdgcn_if_break: 6620 return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT, 6621 Op->getOperand(1), Op->getOperand(2)), 0); 6622 6623 case Intrinsic::amdgcn_groupstaticsize: { 6624 Triple::OSType OS = getTargetMachine().getTargetTriple().getOS(); 6625 if (OS == Triple::AMDHSA || OS == Triple::AMDPAL) 6626 return Op; 6627 6628 const Module *M = MF.getFunction().getParent(); 6629 const GlobalValue *GV = 6630 M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize)); 6631 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0, 6632 SIInstrInfo::MO_ABS32_LO); 6633 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6634 } 6635 case Intrinsic::amdgcn_is_shared: 6636 case Intrinsic::amdgcn_is_private: { 6637 SDLoc SL(Op); 6638 unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ? 6639 AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS; 6640 SDValue Aperture = getSegmentAperture(AS, SL, DAG); 6641 SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, 6642 Op.getOperand(1)); 6643 6644 SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec, 6645 DAG.getConstant(1, SL, MVT::i32)); 6646 return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ); 6647 } 6648 case Intrinsic::amdgcn_alignbit: 6649 return DAG.getNode(ISD::FSHR, DL, VT, 6650 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 6651 case Intrinsic::amdgcn_reloc_constant: { 6652 Module *M = const_cast<Module *>(MF.getFunction().getParent()); 6653 const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD(); 6654 auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString(); 6655 auto RelocSymbol = cast<GlobalVariable>( 6656 M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext()))); 6657 SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0, 6658 SIInstrInfo::MO_ABS32_LO); 6659 return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0}; 6660 } 6661 default: 6662 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 6663 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 6664 return lowerImage(Op, ImageDimIntr, DAG, false); 6665 6666 return Op; 6667 } 6668 } 6669 6670 // This function computes an appropriate offset to pass to 6671 // MachineMemOperand::setOffset() based on the offset inputs to 6672 // an intrinsic. If any of the offsets are non-contstant or 6673 // if VIndex is non-zero then this function returns 0. Otherwise, 6674 // it returns the sum of VOffset, SOffset, and Offset. 6675 static unsigned getBufferOffsetForMMO(SDValue VOffset, 6676 SDValue SOffset, 6677 SDValue Offset, 6678 SDValue VIndex = SDValue()) { 6679 6680 if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) || 6681 !isa<ConstantSDNode>(Offset)) 6682 return 0; 6683 6684 if (VIndex) { 6685 if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue()) 6686 return 0; 6687 } 6688 6689 return cast<ConstantSDNode>(VOffset)->getSExtValue() + 6690 cast<ConstantSDNode>(SOffset)->getSExtValue() + 6691 cast<ConstantSDNode>(Offset)->getSExtValue(); 6692 } 6693 6694 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op, 6695 SelectionDAG &DAG, 6696 unsigned NewOpcode) const { 6697 SDLoc DL(Op); 6698 6699 SDValue VData = Op.getOperand(2); 6700 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6701 SDValue Ops[] = { 6702 Op.getOperand(0), // Chain 6703 VData, // vdata 6704 Op.getOperand(3), // rsrc 6705 DAG.getConstant(0, DL, MVT::i32), // vindex 6706 Offsets.first, // voffset 6707 Op.getOperand(5), // soffset 6708 Offsets.second, // offset 6709 Op.getOperand(6), // cachepolicy 6710 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6711 }; 6712 6713 auto *M = cast<MemSDNode>(Op); 6714 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 6715 6716 EVT MemVT = VData.getValueType(); 6717 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6718 M->getMemOperand()); 6719 } 6720 6721 SDValue 6722 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG, 6723 unsigned NewOpcode) const { 6724 SDLoc DL(Op); 6725 6726 SDValue VData = Op.getOperand(2); 6727 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 6728 SDValue Ops[] = { 6729 Op.getOperand(0), // Chain 6730 VData, // vdata 6731 Op.getOperand(3), // rsrc 6732 Op.getOperand(4), // vindex 6733 Offsets.first, // voffset 6734 Op.getOperand(6), // soffset 6735 Offsets.second, // offset 6736 Op.getOperand(7), // cachepolicy 6737 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6738 }; 6739 6740 auto *M = cast<MemSDNode>(Op); 6741 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 6742 Ops[3])); 6743 6744 EVT MemVT = VData.getValueType(); 6745 return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT, 6746 M->getMemOperand()); 6747 } 6748 6749 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 6750 SelectionDAG &DAG) const { 6751 unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 6752 SDLoc DL(Op); 6753 6754 switch (IntrID) { 6755 case Intrinsic::amdgcn_ds_ordered_add: 6756 case Intrinsic::amdgcn_ds_ordered_swap: { 6757 MemSDNode *M = cast<MemSDNode>(Op); 6758 SDValue Chain = M->getOperand(0); 6759 SDValue M0 = M->getOperand(2); 6760 SDValue Value = M->getOperand(3); 6761 unsigned IndexOperand = M->getConstantOperandVal(7); 6762 unsigned WaveRelease = M->getConstantOperandVal(8); 6763 unsigned WaveDone = M->getConstantOperandVal(9); 6764 6765 unsigned OrderedCountIndex = IndexOperand & 0x3f; 6766 IndexOperand &= ~0x3f; 6767 unsigned CountDw = 0; 6768 6769 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) { 6770 CountDw = (IndexOperand >> 24) & 0xf; 6771 IndexOperand &= ~(0xf << 24); 6772 6773 if (CountDw < 1 || CountDw > 4) { 6774 report_fatal_error( 6775 "ds_ordered_count: dword count must be between 1 and 4"); 6776 } 6777 } 6778 6779 if (IndexOperand) 6780 report_fatal_error("ds_ordered_count: bad index operand"); 6781 6782 if (WaveDone && !WaveRelease) 6783 report_fatal_error("ds_ordered_count: wave_done requires wave_release"); 6784 6785 unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1; 6786 unsigned ShaderType = 6787 SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction()); 6788 unsigned Offset0 = OrderedCountIndex << 2; 6789 unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) | 6790 (Instruction << 4); 6791 6792 if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) 6793 Offset1 |= (CountDw - 1) << 6; 6794 6795 unsigned Offset = Offset0 | (Offset1 << 8); 6796 6797 SDValue Ops[] = { 6798 Chain, 6799 Value, 6800 DAG.getTargetConstant(Offset, DL, MVT::i16), 6801 copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue 6802 }; 6803 return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL, 6804 M->getVTList(), Ops, M->getMemoryVT(), 6805 M->getMemOperand()); 6806 } 6807 case Intrinsic::amdgcn_ds_fadd: { 6808 MemSDNode *M = cast<MemSDNode>(Op); 6809 unsigned Opc; 6810 switch (IntrID) { 6811 case Intrinsic::amdgcn_ds_fadd: 6812 Opc = ISD::ATOMIC_LOAD_FADD; 6813 break; 6814 } 6815 6816 return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(), 6817 M->getOperand(0), M->getOperand(2), M->getOperand(3), 6818 M->getMemOperand()); 6819 } 6820 case Intrinsic::amdgcn_atomic_inc: 6821 case Intrinsic::amdgcn_atomic_dec: 6822 case Intrinsic::amdgcn_ds_fmin: 6823 case Intrinsic::amdgcn_ds_fmax: { 6824 MemSDNode *M = cast<MemSDNode>(Op); 6825 unsigned Opc; 6826 switch (IntrID) { 6827 case Intrinsic::amdgcn_atomic_inc: 6828 Opc = AMDGPUISD::ATOMIC_INC; 6829 break; 6830 case Intrinsic::amdgcn_atomic_dec: 6831 Opc = AMDGPUISD::ATOMIC_DEC; 6832 break; 6833 case Intrinsic::amdgcn_ds_fmin: 6834 Opc = AMDGPUISD::ATOMIC_LOAD_FMIN; 6835 break; 6836 case Intrinsic::amdgcn_ds_fmax: 6837 Opc = AMDGPUISD::ATOMIC_LOAD_FMAX; 6838 break; 6839 default: 6840 llvm_unreachable("Unknown intrinsic!"); 6841 } 6842 SDValue Ops[] = { 6843 M->getOperand(0), // Chain 6844 M->getOperand(2), // Ptr 6845 M->getOperand(3) // Value 6846 }; 6847 6848 return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops, 6849 M->getMemoryVT(), M->getMemOperand()); 6850 } 6851 case Intrinsic::amdgcn_buffer_load: 6852 case Intrinsic::amdgcn_buffer_load_format: { 6853 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue(); 6854 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 6855 unsigned IdxEn = 1; 6856 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6857 IdxEn = Idx->getZExtValue() != 0; 6858 SDValue Ops[] = { 6859 Op.getOperand(0), // Chain 6860 Op.getOperand(2), // rsrc 6861 Op.getOperand(3), // vindex 6862 SDValue(), // voffset -- will be set by setBufferOffsets 6863 SDValue(), // soffset -- will be set by setBufferOffsets 6864 SDValue(), // offset -- will be set by setBufferOffsets 6865 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6866 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 6867 }; 6868 6869 unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]); 6870 // We don't know the offset if vindex is non-zero, so clear it. 6871 if (IdxEn) 6872 Offset = 0; 6873 6874 unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ? 6875 AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT; 6876 6877 EVT VT = Op.getValueType(); 6878 EVT IntVT = VT.changeTypeToInteger(); 6879 auto *M = cast<MemSDNode>(Op); 6880 M->getMemOperand()->setOffset(Offset); 6881 EVT LoadVT = Op.getValueType(); 6882 6883 if (LoadVT.getScalarType() == MVT::f16) 6884 return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, 6885 M, DAG, Ops); 6886 6887 // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics 6888 if (LoadVT.getScalarType() == MVT::i8 || 6889 LoadVT.getScalarType() == MVT::i16) 6890 return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M); 6891 6892 return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT, 6893 M->getMemOperand(), DAG); 6894 } 6895 case Intrinsic::amdgcn_raw_buffer_load: 6896 case Intrinsic::amdgcn_raw_buffer_load_format: { 6897 const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format; 6898 6899 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6900 SDValue Ops[] = { 6901 Op.getOperand(0), // Chain 6902 Op.getOperand(2), // rsrc 6903 DAG.getConstant(0, DL, MVT::i32), // vindex 6904 Offsets.first, // voffset 6905 Op.getOperand(4), // soffset 6906 Offsets.second, // offset 6907 Op.getOperand(5), // cachepolicy, swizzled buffer 6908 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6909 }; 6910 6911 auto *M = cast<MemSDNode>(Op); 6912 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5])); 6913 return lowerIntrinsicLoad(M, IsFormat, DAG, Ops); 6914 } 6915 case Intrinsic::amdgcn_struct_buffer_load: 6916 case Intrinsic::amdgcn_struct_buffer_load_format: { 6917 const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format; 6918 6919 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6920 SDValue Ops[] = { 6921 Op.getOperand(0), // Chain 6922 Op.getOperand(2), // rsrc 6923 Op.getOperand(3), // vindex 6924 Offsets.first, // voffset 6925 Op.getOperand(5), // soffset 6926 Offsets.second, // offset 6927 Op.getOperand(6), // cachepolicy, swizzled buffer 6928 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 6929 }; 6930 6931 auto *M = cast<MemSDNode>(Op); 6932 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5], 6933 Ops[2])); 6934 return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops); 6935 } 6936 case Intrinsic::amdgcn_tbuffer_load: { 6937 MemSDNode *M = cast<MemSDNode>(Op); 6938 EVT LoadVT = Op.getValueType(); 6939 6940 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 6941 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 6942 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 6943 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 6944 unsigned IdxEn = 1; 6945 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3))) 6946 IdxEn = Idx->getZExtValue() != 0; 6947 SDValue Ops[] = { 6948 Op.getOperand(0), // Chain 6949 Op.getOperand(2), // rsrc 6950 Op.getOperand(3), // vindex 6951 Op.getOperand(4), // voffset 6952 Op.getOperand(5), // soffset 6953 Op.getOperand(6), // offset 6954 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 6955 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 6956 DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen 6957 }; 6958 6959 if (LoadVT.getScalarType() == MVT::f16) 6960 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6961 M, DAG, Ops); 6962 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6963 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6964 DAG); 6965 } 6966 case Intrinsic::amdgcn_raw_tbuffer_load: { 6967 MemSDNode *M = cast<MemSDNode>(Op); 6968 EVT LoadVT = Op.getValueType(); 6969 auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG); 6970 6971 SDValue Ops[] = { 6972 Op.getOperand(0), // Chain 6973 Op.getOperand(2), // rsrc 6974 DAG.getConstant(0, DL, MVT::i32), // vindex 6975 Offsets.first, // voffset 6976 Op.getOperand(4), // soffset 6977 Offsets.second, // offset 6978 Op.getOperand(5), // format 6979 Op.getOperand(6), // cachepolicy, swizzled buffer 6980 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 6981 }; 6982 6983 if (LoadVT.getScalarType() == MVT::f16) 6984 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 6985 M, DAG, Ops); 6986 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 6987 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 6988 DAG); 6989 } 6990 case Intrinsic::amdgcn_struct_tbuffer_load: { 6991 MemSDNode *M = cast<MemSDNode>(Op); 6992 EVT LoadVT = Op.getValueType(); 6993 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 6994 6995 SDValue Ops[] = { 6996 Op.getOperand(0), // Chain 6997 Op.getOperand(2), // rsrc 6998 Op.getOperand(3), // vindex 6999 Offsets.first, // voffset 7000 Op.getOperand(5), // soffset 7001 Offsets.second, // offset 7002 Op.getOperand(6), // format 7003 Op.getOperand(7), // cachepolicy, swizzled buffer 7004 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7005 }; 7006 7007 if (LoadVT.getScalarType() == MVT::f16) 7008 return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, 7009 M, DAG, Ops); 7010 return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL, 7011 Op->getVTList(), Ops, LoadVT, M->getMemOperand(), 7012 DAG); 7013 } 7014 case Intrinsic::amdgcn_buffer_atomic_swap: 7015 case Intrinsic::amdgcn_buffer_atomic_add: 7016 case Intrinsic::amdgcn_buffer_atomic_sub: 7017 case Intrinsic::amdgcn_buffer_atomic_csub: 7018 case Intrinsic::amdgcn_buffer_atomic_smin: 7019 case Intrinsic::amdgcn_buffer_atomic_umin: 7020 case Intrinsic::amdgcn_buffer_atomic_smax: 7021 case Intrinsic::amdgcn_buffer_atomic_umax: 7022 case Intrinsic::amdgcn_buffer_atomic_and: 7023 case Intrinsic::amdgcn_buffer_atomic_or: 7024 case Intrinsic::amdgcn_buffer_atomic_xor: 7025 case Intrinsic::amdgcn_buffer_atomic_fadd: { 7026 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7027 unsigned IdxEn = 1; 7028 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7029 IdxEn = Idx->getZExtValue() != 0; 7030 SDValue Ops[] = { 7031 Op.getOperand(0), // Chain 7032 Op.getOperand(2), // vdata 7033 Op.getOperand(3), // rsrc 7034 Op.getOperand(4), // vindex 7035 SDValue(), // voffset -- will be set by setBufferOffsets 7036 SDValue(), // soffset -- will be set by setBufferOffsets 7037 SDValue(), // offset -- will be set by setBufferOffsets 7038 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7039 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7040 }; 7041 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7042 // We don't know the offset if vindex is non-zero, so clear it. 7043 if (IdxEn) 7044 Offset = 0; 7045 EVT VT = Op.getValueType(); 7046 7047 auto *M = cast<MemSDNode>(Op); 7048 M->getMemOperand()->setOffset(Offset); 7049 unsigned Opcode = 0; 7050 7051 switch (IntrID) { 7052 case Intrinsic::amdgcn_buffer_atomic_swap: 7053 Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP; 7054 break; 7055 case Intrinsic::amdgcn_buffer_atomic_add: 7056 Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD; 7057 break; 7058 case Intrinsic::amdgcn_buffer_atomic_sub: 7059 Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB; 7060 break; 7061 case Intrinsic::amdgcn_buffer_atomic_csub: 7062 Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB; 7063 break; 7064 case Intrinsic::amdgcn_buffer_atomic_smin: 7065 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN; 7066 break; 7067 case Intrinsic::amdgcn_buffer_atomic_umin: 7068 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN; 7069 break; 7070 case Intrinsic::amdgcn_buffer_atomic_smax: 7071 Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX; 7072 break; 7073 case Intrinsic::amdgcn_buffer_atomic_umax: 7074 Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX; 7075 break; 7076 case Intrinsic::amdgcn_buffer_atomic_and: 7077 Opcode = AMDGPUISD::BUFFER_ATOMIC_AND; 7078 break; 7079 case Intrinsic::amdgcn_buffer_atomic_or: 7080 Opcode = AMDGPUISD::BUFFER_ATOMIC_OR; 7081 break; 7082 case Intrinsic::amdgcn_buffer_atomic_xor: 7083 Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR; 7084 break; 7085 case Intrinsic::amdgcn_buffer_atomic_fadd: 7086 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7087 DiagnosticInfoUnsupported 7088 NoFpRet(DAG.getMachineFunction().getFunction(), 7089 "return versions of fp atomics not supported", 7090 DL.getDebugLoc(), DS_Error); 7091 DAG.getContext()->diagnose(NoFpRet); 7092 return SDValue(); 7093 } 7094 Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD; 7095 break; 7096 default: 7097 llvm_unreachable("unhandled atomic opcode"); 7098 } 7099 7100 return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT, 7101 M->getMemOperand()); 7102 } 7103 case Intrinsic::amdgcn_raw_buffer_atomic_fadd: 7104 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7105 case Intrinsic::amdgcn_struct_buffer_atomic_fadd: 7106 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD); 7107 case Intrinsic::amdgcn_raw_buffer_atomic_fmin: 7108 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7109 case Intrinsic::amdgcn_struct_buffer_atomic_fmin: 7110 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMIN); 7111 case Intrinsic::amdgcn_raw_buffer_atomic_fmax: 7112 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7113 case Intrinsic::amdgcn_struct_buffer_atomic_fmax: 7114 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FMAX); 7115 case Intrinsic::amdgcn_raw_buffer_atomic_swap: 7116 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP); 7117 case Intrinsic::amdgcn_raw_buffer_atomic_add: 7118 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7119 case Intrinsic::amdgcn_raw_buffer_atomic_sub: 7120 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7121 case Intrinsic::amdgcn_raw_buffer_atomic_smin: 7122 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN); 7123 case Intrinsic::amdgcn_raw_buffer_atomic_umin: 7124 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN); 7125 case Intrinsic::amdgcn_raw_buffer_atomic_smax: 7126 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX); 7127 case Intrinsic::amdgcn_raw_buffer_atomic_umax: 7128 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX); 7129 case Intrinsic::amdgcn_raw_buffer_atomic_and: 7130 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7131 case Intrinsic::amdgcn_raw_buffer_atomic_or: 7132 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7133 case Intrinsic::amdgcn_raw_buffer_atomic_xor: 7134 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7135 case Intrinsic::amdgcn_raw_buffer_atomic_inc: 7136 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7137 case Intrinsic::amdgcn_raw_buffer_atomic_dec: 7138 return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7139 case Intrinsic::amdgcn_struct_buffer_atomic_swap: 7140 return lowerStructBufferAtomicIntrin(Op, DAG, 7141 AMDGPUISD::BUFFER_ATOMIC_SWAP); 7142 case Intrinsic::amdgcn_struct_buffer_atomic_add: 7143 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD); 7144 case Intrinsic::amdgcn_struct_buffer_atomic_sub: 7145 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB); 7146 case Intrinsic::amdgcn_struct_buffer_atomic_smin: 7147 return lowerStructBufferAtomicIntrin(Op, DAG, 7148 AMDGPUISD::BUFFER_ATOMIC_SMIN); 7149 case Intrinsic::amdgcn_struct_buffer_atomic_umin: 7150 return lowerStructBufferAtomicIntrin(Op, DAG, 7151 AMDGPUISD::BUFFER_ATOMIC_UMIN); 7152 case Intrinsic::amdgcn_struct_buffer_atomic_smax: 7153 return lowerStructBufferAtomicIntrin(Op, DAG, 7154 AMDGPUISD::BUFFER_ATOMIC_SMAX); 7155 case Intrinsic::amdgcn_struct_buffer_atomic_umax: 7156 return lowerStructBufferAtomicIntrin(Op, DAG, 7157 AMDGPUISD::BUFFER_ATOMIC_UMAX); 7158 case Intrinsic::amdgcn_struct_buffer_atomic_and: 7159 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND); 7160 case Intrinsic::amdgcn_struct_buffer_atomic_or: 7161 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR); 7162 case Intrinsic::amdgcn_struct_buffer_atomic_xor: 7163 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR); 7164 case Intrinsic::amdgcn_struct_buffer_atomic_inc: 7165 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC); 7166 case Intrinsic::amdgcn_struct_buffer_atomic_dec: 7167 return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC); 7168 7169 case Intrinsic::amdgcn_buffer_atomic_cmpswap: { 7170 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7171 unsigned IdxEn = 1; 7172 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5))) 7173 IdxEn = Idx->getZExtValue() != 0; 7174 SDValue Ops[] = { 7175 Op.getOperand(0), // Chain 7176 Op.getOperand(2), // src 7177 Op.getOperand(3), // cmp 7178 Op.getOperand(4), // rsrc 7179 Op.getOperand(5), // vindex 7180 SDValue(), // voffset -- will be set by setBufferOffsets 7181 SDValue(), // soffset -- will be set by setBufferOffsets 7182 SDValue(), // offset -- will be set by setBufferOffsets 7183 DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy 7184 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7185 }; 7186 unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]); 7187 // We don't know the offset if vindex is non-zero, so clear it. 7188 if (IdxEn) 7189 Offset = 0; 7190 EVT VT = Op.getValueType(); 7191 auto *M = cast<MemSDNode>(Op); 7192 M->getMemOperand()->setOffset(Offset); 7193 7194 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7195 Op->getVTList(), Ops, VT, M->getMemOperand()); 7196 } 7197 case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: { 7198 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7199 SDValue Ops[] = { 7200 Op.getOperand(0), // Chain 7201 Op.getOperand(2), // src 7202 Op.getOperand(3), // cmp 7203 Op.getOperand(4), // rsrc 7204 DAG.getConstant(0, DL, MVT::i32), // vindex 7205 Offsets.first, // voffset 7206 Op.getOperand(6), // soffset 7207 Offsets.second, // offset 7208 Op.getOperand(7), // cachepolicy 7209 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7210 }; 7211 EVT VT = Op.getValueType(); 7212 auto *M = cast<MemSDNode>(Op); 7213 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7])); 7214 7215 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7216 Op->getVTList(), Ops, VT, M->getMemOperand()); 7217 } 7218 case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: { 7219 auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG); 7220 SDValue Ops[] = { 7221 Op.getOperand(0), // Chain 7222 Op.getOperand(2), // src 7223 Op.getOperand(3), // cmp 7224 Op.getOperand(4), // rsrc 7225 Op.getOperand(5), // vindex 7226 Offsets.first, // voffset 7227 Op.getOperand(7), // soffset 7228 Offsets.second, // offset 7229 Op.getOperand(8), // cachepolicy 7230 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7231 }; 7232 EVT VT = Op.getValueType(); 7233 auto *M = cast<MemSDNode>(Op); 7234 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7], 7235 Ops[4])); 7236 7237 return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL, 7238 Op->getVTList(), Ops, VT, M->getMemOperand()); 7239 } 7240 case Intrinsic::amdgcn_image_bvh_intersect_ray: { 7241 SDLoc DL(Op); 7242 MemSDNode *M = cast<MemSDNode>(Op); 7243 SDValue NodePtr = M->getOperand(2); 7244 SDValue RayExtent = M->getOperand(3); 7245 SDValue RayOrigin = M->getOperand(4); 7246 SDValue RayDir = M->getOperand(5); 7247 SDValue RayInvDir = M->getOperand(6); 7248 SDValue TDescr = M->getOperand(7); 7249 7250 assert(NodePtr.getValueType() == MVT::i32 || 7251 NodePtr.getValueType() == MVT::i64); 7252 assert(RayDir.getValueType() == MVT::v4f16 || 7253 RayDir.getValueType() == MVT::v4f32); 7254 7255 bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16; 7256 bool Is64 = NodePtr.getValueType() == MVT::i64; 7257 unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa 7258 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa 7259 : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa 7260 : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa; 7261 7262 SmallVector<SDValue, 16> Ops; 7263 7264 auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) { 7265 SmallVector<SDValue, 3> Lanes; 7266 DAG.ExtractVectorElements(Op, Lanes, 0, 3); 7267 if (Lanes[0].getValueSizeInBits() == 32) { 7268 for (unsigned I = 0; I < 3; ++I) 7269 Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I])); 7270 } else { 7271 if (IsAligned) { 7272 Ops.push_back( 7273 DAG.getBitcast(MVT::i32, 7274 DAG.getBuildVector(MVT::v2f16, DL, 7275 { Lanes[0], Lanes[1] }))); 7276 Ops.push_back(Lanes[2]); 7277 } else { 7278 SDValue Elt0 = Ops.pop_back_val(); 7279 Ops.push_back( 7280 DAG.getBitcast(MVT::i32, 7281 DAG.getBuildVector(MVT::v2f16, DL, 7282 { Elt0, Lanes[0] }))); 7283 Ops.push_back( 7284 DAG.getBitcast(MVT::i32, 7285 DAG.getBuildVector(MVT::v2f16, DL, 7286 { Lanes[1], Lanes[2] }))); 7287 } 7288 } 7289 }; 7290 7291 if (Is64) 7292 DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2); 7293 else 7294 Ops.push_back(NodePtr); 7295 7296 Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent)); 7297 packLanes(RayOrigin, true); 7298 packLanes(RayDir, true); 7299 packLanes(RayInvDir, false); 7300 Ops.push_back(TDescr); 7301 if (IsA16) 7302 Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1)); 7303 Ops.push_back(M->getChain()); 7304 7305 auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops); 7306 MachineMemOperand *MemRef = M->getMemOperand(); 7307 DAG.setNodeMemRefs(NewNode, {MemRef}); 7308 return SDValue(NewNode, 0); 7309 } 7310 case Intrinsic::amdgcn_global_atomic_fadd: 7311 if (!Op.getValue(0).use_empty() && !Subtarget->hasGFX90AInsts()) { 7312 DiagnosticInfoUnsupported 7313 NoFpRet(DAG.getMachineFunction().getFunction(), 7314 "return versions of fp atomics not supported", 7315 DL.getDebugLoc(), DS_Error); 7316 DAG.getContext()->diagnose(NoFpRet); 7317 return SDValue(); 7318 } 7319 LLVM_FALLTHROUGH; 7320 case Intrinsic::amdgcn_global_atomic_fmin: 7321 case Intrinsic::amdgcn_global_atomic_fmax: 7322 case Intrinsic::amdgcn_flat_atomic_fadd: 7323 case Intrinsic::amdgcn_flat_atomic_fmin: 7324 case Intrinsic::amdgcn_flat_atomic_fmax: { 7325 MemSDNode *M = cast<MemSDNode>(Op); 7326 SDValue Ops[] = { 7327 M->getOperand(0), // Chain 7328 M->getOperand(2), // Ptr 7329 M->getOperand(3) // Value 7330 }; 7331 unsigned Opcode = 0; 7332 switch (IntrID) { 7333 case Intrinsic::amdgcn_global_atomic_fadd: 7334 case Intrinsic::amdgcn_flat_atomic_fadd: { 7335 EVT VT = Op.getOperand(3).getValueType(); 7336 return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT, 7337 DAG.getVTList(VT, MVT::Other), Ops, 7338 M->getMemOperand()); 7339 } 7340 case Intrinsic::amdgcn_global_atomic_fmin: 7341 case Intrinsic::amdgcn_flat_atomic_fmin: { 7342 Opcode = AMDGPUISD::ATOMIC_LOAD_FMIN; 7343 break; 7344 } 7345 case Intrinsic::amdgcn_global_atomic_fmax: 7346 case Intrinsic::amdgcn_flat_atomic_fmax: { 7347 Opcode = AMDGPUISD::ATOMIC_LOAD_FMAX; 7348 break; 7349 } 7350 default: 7351 llvm_unreachable("unhandled atomic opcode"); 7352 } 7353 return DAG.getMemIntrinsicNode(Opcode, SDLoc(Op), 7354 M->getVTList(), Ops, M->getMemoryVT(), 7355 M->getMemOperand()); 7356 } 7357 default: 7358 7359 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7360 AMDGPU::getImageDimIntrinsicInfo(IntrID)) 7361 return lowerImage(Op, ImageDimIntr, DAG, true); 7362 7363 return SDValue(); 7364 } 7365 } 7366 7367 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to 7368 // dwordx4 if on SI. 7369 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL, 7370 SDVTList VTList, 7371 ArrayRef<SDValue> Ops, EVT MemVT, 7372 MachineMemOperand *MMO, 7373 SelectionDAG &DAG) const { 7374 EVT VT = VTList.VTs[0]; 7375 EVT WidenedVT = VT; 7376 EVT WidenedMemVT = MemVT; 7377 if (!Subtarget->hasDwordx3LoadStores() && 7378 (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) { 7379 WidenedVT = EVT::getVectorVT(*DAG.getContext(), 7380 WidenedVT.getVectorElementType(), 4); 7381 WidenedMemVT = EVT::getVectorVT(*DAG.getContext(), 7382 WidenedMemVT.getVectorElementType(), 4); 7383 MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16); 7384 } 7385 7386 assert(VTList.NumVTs == 2); 7387 SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]); 7388 7389 auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops, 7390 WidenedMemVT, MMO); 7391 if (WidenedVT != VT) { 7392 auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp, 7393 DAG.getVectorIdxConstant(0, DL)); 7394 NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL); 7395 } 7396 return NewOp; 7397 } 7398 7399 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG, 7400 bool ImageStore) const { 7401 EVT StoreVT = VData.getValueType(); 7402 7403 // No change for f16 and legal vector D16 types. 7404 if (!StoreVT.isVector()) 7405 return VData; 7406 7407 SDLoc DL(VData); 7408 unsigned NumElements = StoreVT.getVectorNumElements(); 7409 7410 if (Subtarget->hasUnpackedD16VMem()) { 7411 // We need to unpack the packed data to store. 7412 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7413 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7414 7415 EVT EquivStoreVT = 7416 EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements); 7417 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData); 7418 return DAG.UnrollVectorOp(ZExt.getNode()); 7419 } 7420 7421 // The sq block of gfx8.1 does not estimate register use correctly for d16 7422 // image store instructions. The data operand is computed as if it were not a 7423 // d16 image instruction. 7424 if (ImageStore && Subtarget->hasImageStoreD16Bug()) { 7425 // Bitcast to i16 7426 EVT IntStoreVT = StoreVT.changeTypeToInteger(); 7427 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7428 7429 // Decompose into scalars 7430 SmallVector<SDValue, 4> Elts; 7431 DAG.ExtractVectorElements(IntVData, Elts); 7432 7433 // Group pairs of i16 into v2i16 and bitcast to i32 7434 SmallVector<SDValue, 4> PackedElts; 7435 for (unsigned I = 0; I < Elts.size() / 2; I += 1) { 7436 SDValue Pair = 7437 DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]}); 7438 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7439 PackedElts.push_back(IntPair); 7440 } 7441 if ((NumElements % 2) == 1) { 7442 // Handle v3i16 7443 unsigned I = Elts.size() / 2; 7444 SDValue Pair = DAG.getBuildVector(MVT::v2i16, DL, 7445 {Elts[I * 2], DAG.getUNDEF(MVT::i16)}); 7446 SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair); 7447 PackedElts.push_back(IntPair); 7448 } 7449 7450 // Pad using UNDEF 7451 PackedElts.resize(Elts.size(), DAG.getUNDEF(MVT::i32)); 7452 7453 // Build final vector 7454 EVT VecVT = 7455 EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size()); 7456 return DAG.getBuildVector(VecVT, DL, PackedElts); 7457 } 7458 7459 if (NumElements == 3) { 7460 EVT IntStoreVT = 7461 EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits()); 7462 SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData); 7463 7464 EVT WidenedStoreVT = EVT::getVectorVT( 7465 *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1); 7466 EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(), 7467 WidenedStoreVT.getStoreSizeInBits()); 7468 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData); 7469 return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt); 7470 } 7471 7472 assert(isTypeLegal(StoreVT)); 7473 return VData; 7474 } 7475 7476 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op, 7477 SelectionDAG &DAG) const { 7478 SDLoc DL(Op); 7479 SDValue Chain = Op.getOperand(0); 7480 unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue(); 7481 MachineFunction &MF = DAG.getMachineFunction(); 7482 7483 switch (IntrinsicID) { 7484 case Intrinsic::amdgcn_exp_compr: { 7485 SDValue Src0 = Op.getOperand(4); 7486 SDValue Src1 = Op.getOperand(5); 7487 // Hack around illegal type on SI by directly selecting it. 7488 if (isTypeLegal(Src0.getValueType())) 7489 return SDValue(); 7490 7491 const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6)); 7492 SDValue Undef = DAG.getUNDEF(MVT::f32); 7493 const SDValue Ops[] = { 7494 Op.getOperand(2), // tgt 7495 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0 7496 DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1 7497 Undef, // src2 7498 Undef, // src3 7499 Op.getOperand(7), // vm 7500 DAG.getTargetConstant(1, DL, MVT::i1), // compr 7501 Op.getOperand(3), // en 7502 Op.getOperand(0) // Chain 7503 }; 7504 7505 unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE; 7506 return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0); 7507 } 7508 case Intrinsic::amdgcn_s_barrier: { 7509 if (getTargetMachine().getOptLevel() > CodeGenOpt::None) { 7510 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 7511 unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second; 7512 if (WGSize <= ST.getWavefrontSize()) 7513 return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other, 7514 Op.getOperand(0)), 0); 7515 } 7516 return SDValue(); 7517 }; 7518 case Intrinsic::amdgcn_tbuffer_store: { 7519 SDValue VData = Op.getOperand(2); 7520 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7521 if (IsD16) 7522 VData = handleD16VData(VData, DAG); 7523 unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue(); 7524 unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue(); 7525 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue(); 7526 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue(); 7527 unsigned IdxEn = 1; 7528 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7529 IdxEn = Idx->getZExtValue() != 0; 7530 SDValue Ops[] = { 7531 Chain, 7532 VData, // vdata 7533 Op.getOperand(3), // rsrc 7534 Op.getOperand(4), // vindex 7535 Op.getOperand(5), // voffset 7536 Op.getOperand(6), // soffset 7537 Op.getOperand(7), // offset 7538 DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format 7539 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7540 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen 7541 }; 7542 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7543 AMDGPUISD::TBUFFER_STORE_FORMAT; 7544 MemSDNode *M = cast<MemSDNode>(Op); 7545 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7546 M->getMemoryVT(), M->getMemOperand()); 7547 } 7548 7549 case Intrinsic::amdgcn_struct_tbuffer_store: { 7550 SDValue VData = Op.getOperand(2); 7551 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7552 if (IsD16) 7553 VData = handleD16VData(VData, DAG); 7554 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7555 SDValue Ops[] = { 7556 Chain, 7557 VData, // vdata 7558 Op.getOperand(3), // rsrc 7559 Op.getOperand(4), // vindex 7560 Offsets.first, // voffset 7561 Op.getOperand(6), // soffset 7562 Offsets.second, // offset 7563 Op.getOperand(7), // format 7564 Op.getOperand(8), // cachepolicy, swizzled buffer 7565 DAG.getTargetConstant(1, DL, MVT::i1), // idexen 7566 }; 7567 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7568 AMDGPUISD::TBUFFER_STORE_FORMAT; 7569 MemSDNode *M = cast<MemSDNode>(Op); 7570 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7571 M->getMemoryVT(), M->getMemOperand()); 7572 } 7573 7574 case Intrinsic::amdgcn_raw_tbuffer_store: { 7575 SDValue VData = Op.getOperand(2); 7576 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7577 if (IsD16) 7578 VData = handleD16VData(VData, DAG); 7579 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7580 SDValue Ops[] = { 7581 Chain, 7582 VData, // vdata 7583 Op.getOperand(3), // rsrc 7584 DAG.getConstant(0, DL, MVT::i32), // vindex 7585 Offsets.first, // voffset 7586 Op.getOperand(5), // soffset 7587 Offsets.second, // offset 7588 Op.getOperand(6), // format 7589 Op.getOperand(7), // cachepolicy, swizzled buffer 7590 DAG.getTargetConstant(0, DL, MVT::i1), // idexen 7591 }; 7592 unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 : 7593 AMDGPUISD::TBUFFER_STORE_FORMAT; 7594 MemSDNode *M = cast<MemSDNode>(Op); 7595 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7596 M->getMemoryVT(), M->getMemOperand()); 7597 } 7598 7599 case Intrinsic::amdgcn_buffer_store: 7600 case Intrinsic::amdgcn_buffer_store_format: { 7601 SDValue VData = Op.getOperand(2); 7602 bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16); 7603 if (IsD16) 7604 VData = handleD16VData(VData, DAG); 7605 unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue(); 7606 unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue(); 7607 unsigned IdxEn = 1; 7608 if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4))) 7609 IdxEn = Idx->getZExtValue() != 0; 7610 SDValue Ops[] = { 7611 Chain, 7612 VData, 7613 Op.getOperand(3), // rsrc 7614 Op.getOperand(4), // vindex 7615 SDValue(), // voffset -- will be set by setBufferOffsets 7616 SDValue(), // soffset -- will be set by setBufferOffsets 7617 SDValue(), // offset -- will be set by setBufferOffsets 7618 DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy 7619 DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen 7620 }; 7621 unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]); 7622 // We don't know the offset if vindex is non-zero, so clear it. 7623 if (IdxEn) 7624 Offset = 0; 7625 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ? 7626 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7627 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7628 MemSDNode *M = cast<MemSDNode>(Op); 7629 M->getMemOperand()->setOffset(Offset); 7630 7631 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7632 EVT VDataType = VData.getValueType().getScalarType(); 7633 if (VDataType == MVT::i8 || VDataType == MVT::i16) 7634 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7635 7636 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7637 M->getMemoryVT(), M->getMemOperand()); 7638 } 7639 7640 case Intrinsic::amdgcn_raw_buffer_store: 7641 case Intrinsic::amdgcn_raw_buffer_store_format: { 7642 const bool IsFormat = 7643 IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format; 7644 7645 SDValue VData = Op.getOperand(2); 7646 EVT VDataVT = VData.getValueType(); 7647 EVT EltType = VDataVT.getScalarType(); 7648 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7649 if (IsD16) { 7650 VData = handleD16VData(VData, DAG); 7651 VDataVT = VData.getValueType(); 7652 } 7653 7654 if (!isTypeLegal(VDataVT)) { 7655 VData = 7656 DAG.getNode(ISD::BITCAST, DL, 7657 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7658 } 7659 7660 auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG); 7661 SDValue Ops[] = { 7662 Chain, 7663 VData, 7664 Op.getOperand(3), // rsrc 7665 DAG.getConstant(0, DL, MVT::i32), // vindex 7666 Offsets.first, // voffset 7667 Op.getOperand(5), // soffset 7668 Offsets.second, // offset 7669 Op.getOperand(6), // cachepolicy, swizzled buffer 7670 DAG.getTargetConstant(0, DL, MVT::i1), // idxen 7671 }; 7672 unsigned Opc = 7673 IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE; 7674 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7675 MemSDNode *M = cast<MemSDNode>(Op); 7676 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6])); 7677 7678 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7679 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7680 return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M); 7681 7682 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7683 M->getMemoryVT(), M->getMemOperand()); 7684 } 7685 7686 case Intrinsic::amdgcn_struct_buffer_store: 7687 case Intrinsic::amdgcn_struct_buffer_store_format: { 7688 const bool IsFormat = 7689 IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format; 7690 7691 SDValue VData = Op.getOperand(2); 7692 EVT VDataVT = VData.getValueType(); 7693 EVT EltType = VDataVT.getScalarType(); 7694 bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16); 7695 7696 if (IsD16) { 7697 VData = handleD16VData(VData, DAG); 7698 VDataVT = VData.getValueType(); 7699 } 7700 7701 if (!isTypeLegal(VDataVT)) { 7702 VData = 7703 DAG.getNode(ISD::BITCAST, DL, 7704 getEquivalentMemType(*DAG.getContext(), VDataVT), VData); 7705 } 7706 7707 auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG); 7708 SDValue Ops[] = { 7709 Chain, 7710 VData, 7711 Op.getOperand(3), // rsrc 7712 Op.getOperand(4), // vindex 7713 Offsets.first, // voffset 7714 Op.getOperand(6), // soffset 7715 Offsets.second, // offset 7716 Op.getOperand(7), // cachepolicy, swizzled buffer 7717 DAG.getTargetConstant(1, DL, MVT::i1), // idxen 7718 }; 7719 unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ? 7720 AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT; 7721 Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc; 7722 MemSDNode *M = cast<MemSDNode>(Op); 7723 M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6], 7724 Ops[3])); 7725 7726 // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics 7727 EVT VDataType = VData.getValueType().getScalarType(); 7728 if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32) 7729 return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M); 7730 7731 return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, 7732 M->getMemoryVT(), M->getMemOperand()); 7733 } 7734 case Intrinsic::amdgcn_end_cf: 7735 return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other, 7736 Op->getOperand(2), Chain), 0); 7737 7738 default: { 7739 if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr = 7740 AMDGPU::getImageDimIntrinsicInfo(IntrinsicID)) 7741 return lowerImage(Op, ImageDimIntr, DAG, true); 7742 7743 return Op; 7744 } 7745 } 7746 } 7747 7748 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args: 7749 // offset (the offset that is included in bounds checking and swizzling, to be 7750 // split between the instruction's voffset and immoffset fields) and soffset 7751 // (the offset that is excluded from bounds checking and swizzling, to go in 7752 // the instruction's soffset field). This function takes the first kind of 7753 // offset and figures out how to split it between voffset and immoffset. 7754 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets( 7755 SDValue Offset, SelectionDAG &DAG) const { 7756 SDLoc DL(Offset); 7757 const unsigned MaxImm = 4095; 7758 SDValue N0 = Offset; 7759 ConstantSDNode *C1 = nullptr; 7760 7761 if ((C1 = dyn_cast<ConstantSDNode>(N0))) 7762 N0 = SDValue(); 7763 else if (DAG.isBaseWithConstantOffset(N0)) { 7764 C1 = cast<ConstantSDNode>(N0.getOperand(1)); 7765 N0 = N0.getOperand(0); 7766 } 7767 7768 if (C1) { 7769 unsigned ImmOffset = C1->getZExtValue(); 7770 // If the immediate value is too big for the immoffset field, put the value 7771 // and -4096 into the immoffset field so that the value that is copied/added 7772 // for the voffset field is a multiple of 4096, and it stands more chance 7773 // of being CSEd with the copy/add for another similar load/store. 7774 // However, do not do that rounding down to a multiple of 4096 if that is a 7775 // negative number, as it appears to be illegal to have a negative offset 7776 // in the vgpr, even if adding the immediate offset makes it positive. 7777 unsigned Overflow = ImmOffset & ~MaxImm; 7778 ImmOffset -= Overflow; 7779 if ((int32_t)Overflow < 0) { 7780 Overflow += ImmOffset; 7781 ImmOffset = 0; 7782 } 7783 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32)); 7784 if (Overflow) { 7785 auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32); 7786 if (!N0) 7787 N0 = OverflowVal; 7788 else { 7789 SDValue Ops[] = { N0, OverflowVal }; 7790 N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops); 7791 } 7792 } 7793 } 7794 if (!N0) 7795 N0 = DAG.getConstant(0, DL, MVT::i32); 7796 if (!C1) 7797 C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32)); 7798 return {N0, SDValue(C1, 0)}; 7799 } 7800 7801 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the 7802 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array 7803 // pointed to by Offsets. 7804 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset, 7805 SelectionDAG &DAG, SDValue *Offsets, 7806 Align Alignment) const { 7807 SDLoc DL(CombinedOffset); 7808 if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) { 7809 uint32_t Imm = C->getZExtValue(); 7810 uint32_t SOffset, ImmOffset; 7811 if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, 7812 Alignment)) { 7813 Offsets[0] = DAG.getConstant(0, DL, MVT::i32); 7814 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7815 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7816 return SOffset + ImmOffset; 7817 } 7818 } 7819 if (DAG.isBaseWithConstantOffset(CombinedOffset)) { 7820 SDValue N0 = CombinedOffset.getOperand(0); 7821 SDValue N1 = CombinedOffset.getOperand(1); 7822 uint32_t SOffset, ImmOffset; 7823 int Offset = cast<ConstantSDNode>(N1)->getSExtValue(); 7824 if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset, 7825 Subtarget, Alignment)) { 7826 Offsets[0] = N0; 7827 Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32); 7828 Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32); 7829 return 0; 7830 } 7831 } 7832 Offsets[0] = CombinedOffset; 7833 Offsets[1] = DAG.getConstant(0, DL, MVT::i32); 7834 Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32); 7835 return 0; 7836 } 7837 7838 // Handle 8 bit and 16 bit buffer loads 7839 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG, 7840 EVT LoadVT, SDLoc DL, 7841 ArrayRef<SDValue> Ops, 7842 MemSDNode *M) const { 7843 EVT IntVT = LoadVT.changeTypeToInteger(); 7844 unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ? 7845 AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT; 7846 7847 SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other); 7848 SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList, 7849 Ops, IntVT, 7850 M->getMemOperand()); 7851 SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad); 7852 LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal); 7853 7854 return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL); 7855 } 7856 7857 // Handle 8 bit and 16 bit buffer stores 7858 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG, 7859 EVT VDataType, SDLoc DL, 7860 SDValue Ops[], 7861 MemSDNode *M) const { 7862 if (VDataType == MVT::f16) 7863 Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]); 7864 7865 SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]); 7866 Ops[1] = BufferStoreExt; 7867 unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE : 7868 AMDGPUISD::BUFFER_STORE_SHORT; 7869 ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9); 7870 return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType, 7871 M->getMemOperand()); 7872 } 7873 7874 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG, 7875 ISD::LoadExtType ExtType, SDValue Op, 7876 const SDLoc &SL, EVT VT) { 7877 if (VT.bitsLT(Op.getValueType())) 7878 return DAG.getNode(ISD::TRUNCATE, SL, VT, Op); 7879 7880 switch (ExtType) { 7881 case ISD::SEXTLOAD: 7882 return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op); 7883 case ISD::ZEXTLOAD: 7884 return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op); 7885 case ISD::EXTLOAD: 7886 return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op); 7887 case ISD::NON_EXTLOAD: 7888 return Op; 7889 } 7890 7891 llvm_unreachable("invalid ext type"); 7892 } 7893 7894 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const { 7895 SelectionDAG &DAG = DCI.DAG; 7896 if (Ld->getAlignment() < 4 || Ld->isDivergent()) 7897 return SDValue(); 7898 7899 // FIXME: Constant loads should all be marked invariant. 7900 unsigned AS = Ld->getAddressSpace(); 7901 if (AS != AMDGPUAS::CONSTANT_ADDRESS && 7902 AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT && 7903 (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant())) 7904 return SDValue(); 7905 7906 // Don't do this early, since it may interfere with adjacent load merging for 7907 // illegal types. We can avoid losing alignment information for exotic types 7908 // pre-legalize. 7909 EVT MemVT = Ld->getMemoryVT(); 7910 if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) || 7911 MemVT.getSizeInBits() >= 32) 7912 return SDValue(); 7913 7914 SDLoc SL(Ld); 7915 7916 assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) && 7917 "unexpected vector extload"); 7918 7919 // TODO: Drop only high part of range. 7920 SDValue Ptr = Ld->getBasePtr(); 7921 SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, 7922 MVT::i32, SL, Ld->getChain(), Ptr, 7923 Ld->getOffset(), 7924 Ld->getPointerInfo(), MVT::i32, 7925 Ld->getAlignment(), 7926 Ld->getMemOperand()->getFlags(), 7927 Ld->getAAInfo(), 7928 nullptr); // Drop ranges 7929 7930 EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()); 7931 if (MemVT.isFloatingPoint()) { 7932 assert(Ld->getExtensionType() == ISD::NON_EXTLOAD && 7933 "unexpected fp extload"); 7934 TruncVT = MemVT.changeTypeToInteger(); 7935 } 7936 7937 SDValue Cvt = NewLoad; 7938 if (Ld->getExtensionType() == ISD::SEXTLOAD) { 7939 Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad, 7940 DAG.getValueType(TruncVT)); 7941 } else if (Ld->getExtensionType() == ISD::ZEXTLOAD || 7942 Ld->getExtensionType() == ISD::NON_EXTLOAD) { 7943 Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT); 7944 } else { 7945 assert(Ld->getExtensionType() == ISD::EXTLOAD); 7946 } 7947 7948 EVT VT = Ld->getValueType(0); 7949 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits()); 7950 7951 DCI.AddToWorklist(Cvt.getNode()); 7952 7953 // We may need to handle exotic cases, such as i16->i64 extloads, so insert 7954 // the appropriate extension from the 32-bit load. 7955 Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT); 7956 DCI.AddToWorklist(Cvt.getNode()); 7957 7958 // Handle conversion back to floating point if necessary. 7959 Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt); 7960 7961 return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL); 7962 } 7963 7964 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const { 7965 SDLoc DL(Op); 7966 LoadSDNode *Load = cast<LoadSDNode>(Op); 7967 ISD::LoadExtType ExtType = Load->getExtensionType(); 7968 EVT MemVT = Load->getMemoryVT(); 7969 7970 if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) { 7971 if (MemVT == MVT::i16 && isTypeLegal(MVT::i16)) 7972 return SDValue(); 7973 7974 // FIXME: Copied from PPC 7975 // First, load into 32 bits, then truncate to 1 bit. 7976 7977 SDValue Chain = Load->getChain(); 7978 SDValue BasePtr = Load->getBasePtr(); 7979 MachineMemOperand *MMO = Load->getMemOperand(); 7980 7981 EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16; 7982 7983 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain, 7984 BasePtr, RealMemVT, MMO); 7985 7986 if (!MemVT.isVector()) { 7987 SDValue Ops[] = { 7988 DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD), 7989 NewLD.getValue(1) 7990 }; 7991 7992 return DAG.getMergeValues(Ops, DL); 7993 } 7994 7995 SmallVector<SDValue, 3> Elts; 7996 for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) { 7997 SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD, 7998 DAG.getConstant(I, DL, MVT::i32)); 7999 8000 Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt)); 8001 } 8002 8003 SDValue Ops[] = { 8004 DAG.getBuildVector(MemVT, DL, Elts), 8005 NewLD.getValue(1) 8006 }; 8007 8008 return DAG.getMergeValues(Ops, DL); 8009 } 8010 8011 if (!MemVT.isVector()) 8012 return SDValue(); 8013 8014 assert(Op.getValueType().getVectorElementType() == MVT::i32 && 8015 "Custom lowering for non-i32 vectors hasn't been implemented."); 8016 8017 unsigned Alignment = Load->getAlignment(); 8018 unsigned AS = Load->getAddressSpace(); 8019 if (Subtarget->hasLDSMisalignedBug() && 8020 AS == AMDGPUAS::FLAT_ADDRESS && 8021 Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) { 8022 return SplitVectorLoad(Op, DAG); 8023 } 8024 8025 MachineFunction &MF = DAG.getMachineFunction(); 8026 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8027 // If there is a possibilty that flat instruction access scratch memory 8028 // then we need to use the same legalization rules we use for private. 8029 if (AS == AMDGPUAS::FLAT_ADDRESS && 8030 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8031 AS = MFI->hasFlatScratchInit() ? 8032 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8033 8034 unsigned NumElements = MemVT.getVectorNumElements(); 8035 8036 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8037 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) { 8038 if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) { 8039 if (MemVT.isPow2VectorType()) 8040 return SDValue(); 8041 return WidenOrSplitVectorLoad(Op, DAG); 8042 } 8043 // Non-uniform loads will be selected to MUBUF instructions, so they 8044 // have the same legalization requirements as global and private 8045 // loads. 8046 // 8047 } 8048 8049 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8050 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8051 AS == AMDGPUAS::GLOBAL_ADDRESS) { 8052 if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() && 8053 Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) && 8054 Alignment >= 4 && NumElements < 32) { 8055 if (MemVT.isPow2VectorType()) 8056 return SDValue(); 8057 return WidenOrSplitVectorLoad(Op, DAG); 8058 } 8059 // Non-uniform loads will be selected to MUBUF instructions, so they 8060 // have the same legalization requirements as global and private 8061 // loads. 8062 // 8063 } 8064 if (AS == AMDGPUAS::CONSTANT_ADDRESS || 8065 AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT || 8066 AS == AMDGPUAS::GLOBAL_ADDRESS || 8067 AS == AMDGPUAS::FLAT_ADDRESS) { 8068 if (NumElements > 4) 8069 return SplitVectorLoad(Op, DAG); 8070 // v3 loads not supported on SI. 8071 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8072 return WidenOrSplitVectorLoad(Op, DAG); 8073 8074 // v3 and v4 loads are supported for private and global memory. 8075 return SDValue(); 8076 } 8077 if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8078 // Depending on the setting of the private_element_size field in the 8079 // resource descriptor, we can only make private accesses up to a certain 8080 // size. 8081 switch (Subtarget->getMaxPrivateElementSize()) { 8082 case 4: { 8083 SDValue Ops[2]; 8084 std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG); 8085 return DAG.getMergeValues(Ops, DL); 8086 } 8087 case 8: 8088 if (NumElements > 2) 8089 return SplitVectorLoad(Op, DAG); 8090 return SDValue(); 8091 case 16: 8092 // Same as global/flat 8093 if (NumElements > 4) 8094 return SplitVectorLoad(Op, DAG); 8095 // v3 loads not supported on SI. 8096 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8097 return WidenOrSplitVectorLoad(Op, DAG); 8098 8099 return SDValue(); 8100 default: 8101 llvm_unreachable("unsupported private_element_size"); 8102 } 8103 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8104 // Use ds_read_b128 or ds_read_b96 when possible. 8105 if (Subtarget->hasDS96AndDS128() && 8106 ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) || 8107 MemVT.getStoreSize() == 12) && 8108 allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS, 8109 Load->getAlign())) 8110 return SDValue(); 8111 8112 if (NumElements > 2) 8113 return SplitVectorLoad(Op, DAG); 8114 8115 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8116 // address is negative, then the instruction is incorrectly treated as 8117 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8118 // loads here to avoid emitting ds_read2_b32. We may re-combine the 8119 // load later in the SILoadStoreOptimizer. 8120 if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS && 8121 NumElements == 2 && MemVT.getStoreSize() == 8 && 8122 Load->getAlignment() < 8) { 8123 return SplitVectorLoad(Op, DAG); 8124 } 8125 } 8126 8127 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8128 MemVT, *Load->getMemOperand())) { 8129 SDValue Ops[2]; 8130 std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG); 8131 return DAG.getMergeValues(Ops, DL); 8132 } 8133 8134 return SDValue(); 8135 } 8136 8137 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const { 8138 EVT VT = Op.getValueType(); 8139 assert(VT.getSizeInBits() == 64); 8140 8141 SDLoc DL(Op); 8142 SDValue Cond = Op.getOperand(0); 8143 8144 SDValue Zero = DAG.getConstant(0, DL, MVT::i32); 8145 SDValue One = DAG.getConstant(1, DL, MVT::i32); 8146 8147 SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1)); 8148 SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2)); 8149 8150 SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero); 8151 SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero); 8152 8153 SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1); 8154 8155 SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One); 8156 SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One); 8157 8158 SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1); 8159 8160 SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi}); 8161 return DAG.getNode(ISD::BITCAST, DL, VT, Res); 8162 } 8163 8164 // Catch division cases where we can use shortcuts with rcp and rsq 8165 // instructions. 8166 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op, 8167 SelectionDAG &DAG) const { 8168 SDLoc SL(Op); 8169 SDValue LHS = Op.getOperand(0); 8170 SDValue RHS = Op.getOperand(1); 8171 EVT VT = Op.getValueType(); 8172 const SDNodeFlags Flags = Op->getFlags(); 8173 8174 bool AllowInaccurateRcp = Flags.hasApproximateFuncs(); 8175 8176 // Without !fpmath accuracy information, we can't do more because we don't 8177 // know exactly whether rcp is accurate enough to meet !fpmath requirement. 8178 if (!AllowInaccurateRcp) 8179 return SDValue(); 8180 8181 if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) { 8182 if (CLHS->isExactlyValue(1.0)) { 8183 // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to 8184 // the CI documentation has a worst case error of 1 ulp. 8185 // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to 8186 // use it as long as we aren't trying to use denormals. 8187 // 8188 // v_rcp_f16 and v_rsq_f16 DO support denormals. 8189 8190 // 1.0 / sqrt(x) -> rsq(x) 8191 8192 // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP 8193 // error seems really high at 2^29 ULP. 8194 if (RHS.getOpcode() == ISD::FSQRT) 8195 return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0)); 8196 8197 // 1.0 / x -> rcp(x) 8198 return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8199 } 8200 8201 // Same as for 1.0, but expand the sign out of the constant. 8202 if (CLHS->isExactlyValue(-1.0)) { 8203 // -1.0 / x -> rcp (fneg x) 8204 SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 8205 return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS); 8206 } 8207 } 8208 8209 // Turn into multiply by the reciprocal. 8210 // x / y -> x * (1.0 / y) 8211 SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS); 8212 return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags); 8213 } 8214 8215 SDValue SITargetLowering::lowerFastUnsafeFDIV64(SDValue Op, 8216 SelectionDAG &DAG) const { 8217 SDLoc SL(Op); 8218 SDValue X = Op.getOperand(0); 8219 SDValue Y = Op.getOperand(1); 8220 EVT VT = Op.getValueType(); 8221 const SDNodeFlags Flags = Op->getFlags(); 8222 8223 bool AllowInaccurateDiv = Flags.hasApproximateFuncs() || 8224 DAG.getTarget().Options.UnsafeFPMath; 8225 if (!AllowInaccurateDiv) 8226 return SDValue(); 8227 8228 SDValue NegY = DAG.getNode(ISD::FNEG, SL, VT, Y); 8229 SDValue One = DAG.getConstantFP(1.0, SL, VT); 8230 8231 SDValue R = DAG.getNode(AMDGPUISD::RCP, SL, VT, Y); 8232 SDValue Tmp0 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8233 8234 R = DAG.getNode(ISD::FMA, SL, VT, Tmp0, R, R); 8235 SDValue Tmp1 = DAG.getNode(ISD::FMA, SL, VT, NegY, R, One); 8236 R = DAG.getNode(ISD::FMA, SL, VT, Tmp1, R, R); 8237 SDValue Ret = DAG.getNode(ISD::FMUL, SL, VT, X, R); 8238 SDValue Tmp2 = DAG.getNode(ISD::FMA, SL, VT, NegY, Ret, X); 8239 return DAG.getNode(ISD::FMA, SL, VT, Tmp2, R, Ret); 8240 } 8241 8242 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8243 EVT VT, SDValue A, SDValue B, SDValue GlueChain, 8244 SDNodeFlags Flags) { 8245 if (GlueChain->getNumValues() <= 1) { 8246 return DAG.getNode(Opcode, SL, VT, A, B, Flags); 8247 } 8248 8249 assert(GlueChain->getNumValues() == 3); 8250 8251 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8252 switch (Opcode) { 8253 default: llvm_unreachable("no chain equivalent for opcode"); 8254 case ISD::FMUL: 8255 Opcode = AMDGPUISD::FMUL_W_CHAIN; 8256 break; 8257 } 8258 8259 return DAG.getNode(Opcode, SL, VTList, 8260 {GlueChain.getValue(1), A, B, GlueChain.getValue(2)}, 8261 Flags); 8262 } 8263 8264 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL, 8265 EVT VT, SDValue A, SDValue B, SDValue C, 8266 SDValue GlueChain, SDNodeFlags Flags) { 8267 if (GlueChain->getNumValues() <= 1) { 8268 return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags); 8269 } 8270 8271 assert(GlueChain->getNumValues() == 3); 8272 8273 SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue); 8274 switch (Opcode) { 8275 default: llvm_unreachable("no chain equivalent for opcode"); 8276 case ISD::FMA: 8277 Opcode = AMDGPUISD::FMA_W_CHAIN; 8278 break; 8279 } 8280 8281 return DAG.getNode(Opcode, SL, VTList, 8282 {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)}, 8283 Flags); 8284 } 8285 8286 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const { 8287 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8288 return FastLowered; 8289 8290 SDLoc SL(Op); 8291 SDValue Src0 = Op.getOperand(0); 8292 SDValue Src1 = Op.getOperand(1); 8293 8294 SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0); 8295 SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1); 8296 8297 SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1); 8298 SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1); 8299 8300 SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32); 8301 SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag); 8302 8303 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0); 8304 } 8305 8306 // Faster 2.5 ULP division that does not support denormals. 8307 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const { 8308 SDLoc SL(Op); 8309 SDValue LHS = Op.getOperand(1); 8310 SDValue RHS = Op.getOperand(2); 8311 8312 SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS); 8313 8314 const APFloat K0Val(BitsToFloat(0x6f800000)); 8315 const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32); 8316 8317 const APFloat K1Val(BitsToFloat(0x2f800000)); 8318 const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32); 8319 8320 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8321 8322 EVT SetCCVT = 8323 getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32); 8324 8325 SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT); 8326 8327 SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One); 8328 8329 // TODO: Should this propagate fast-math-flags? 8330 r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3); 8331 8332 // rcp does not support denormals. 8333 SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1); 8334 8335 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0); 8336 8337 return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul); 8338 } 8339 8340 // Returns immediate value for setting the F32 denorm mode when using the 8341 // S_DENORM_MODE instruction. 8342 static SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG, 8343 const SDLoc &SL, const GCNSubtarget *ST) { 8344 assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE"); 8345 int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction()) 8346 ? FP_DENORM_FLUSH_NONE 8347 : FP_DENORM_FLUSH_IN_FLUSH_OUT; 8348 8349 int Mode = SPDenormMode | (DPDenormModeDefault << 2); 8350 return DAG.getTargetConstant(Mode, SL, MVT::i32); 8351 } 8352 8353 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const { 8354 if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG)) 8355 return FastLowered; 8356 8357 // The selection matcher assumes anything with a chain selecting to a 8358 // mayRaiseFPException machine instruction. Since we're introducing a chain 8359 // here, we need to explicitly report nofpexcept for the regular fdiv 8360 // lowering. 8361 SDNodeFlags Flags = Op->getFlags(); 8362 Flags.setNoFPExcept(true); 8363 8364 SDLoc SL(Op); 8365 SDValue LHS = Op.getOperand(0); 8366 SDValue RHS = Op.getOperand(1); 8367 8368 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32); 8369 8370 SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1); 8371 8372 SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8373 {RHS, RHS, LHS}, Flags); 8374 SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, 8375 {LHS, RHS, LHS}, Flags); 8376 8377 // Denominator is scaled to not be denormal, so using rcp is ok. 8378 SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, 8379 DenominatorScaled, Flags); 8380 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32, 8381 DenominatorScaled, Flags); 8382 8383 const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE | 8384 (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) | 8385 (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_); 8386 const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32); 8387 8388 const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction()); 8389 8390 if (!HasFP32Denormals) { 8391 // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV 8392 // lowering. The chain dependence is insufficient, and we need glue. We do 8393 // not need the glue variants in a strictfp function. 8394 8395 SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue); 8396 8397 SDNode *EnableDenorm; 8398 if (Subtarget->hasDenormModeInst()) { 8399 const SDValue EnableDenormValue = 8400 getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget); 8401 8402 EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs, 8403 DAG.getEntryNode(), EnableDenormValue).getNode(); 8404 } else { 8405 const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE, 8406 SL, MVT::i32); 8407 EnableDenorm = 8408 DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs, 8409 {EnableDenormValue, BitField, DAG.getEntryNode()}); 8410 } 8411 8412 SDValue Ops[3] = { 8413 NegDivScale0, 8414 SDValue(EnableDenorm, 0), 8415 SDValue(EnableDenorm, 1) 8416 }; 8417 8418 NegDivScale0 = DAG.getMergeValues(Ops, SL); 8419 } 8420 8421 SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, 8422 ApproxRcp, One, NegDivScale0, Flags); 8423 8424 SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp, 8425 ApproxRcp, Fma0, Flags); 8426 8427 SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled, 8428 Fma1, Fma1, Flags); 8429 8430 SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul, 8431 NumeratorScaled, Mul, Flags); 8432 8433 SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, 8434 Fma2, Fma1, Mul, Fma2, Flags); 8435 8436 SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3, 8437 NumeratorScaled, Fma3, Flags); 8438 8439 if (!HasFP32Denormals) { 8440 SDNode *DisableDenorm; 8441 if (Subtarget->hasDenormModeInst()) { 8442 const SDValue DisableDenormValue = 8443 getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget); 8444 8445 DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other, 8446 Fma4.getValue(1), DisableDenormValue, 8447 Fma4.getValue(2)).getNode(); 8448 } else { 8449 const SDValue DisableDenormValue = 8450 DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32); 8451 8452 DisableDenorm = DAG.getMachineNode( 8453 AMDGPU::S_SETREG_B32, SL, MVT::Other, 8454 {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)}); 8455 } 8456 8457 SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, 8458 SDValue(DisableDenorm, 0), DAG.getRoot()); 8459 DAG.setRoot(OutputChain); 8460 } 8461 8462 SDValue Scale = NumeratorScaled.getValue(1); 8463 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32, 8464 {Fma4, Fma1, Fma3, Scale}, Flags); 8465 8466 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags); 8467 } 8468 8469 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const { 8470 if (SDValue FastLowered = lowerFastUnsafeFDIV64(Op, DAG)) 8471 return FastLowered; 8472 8473 SDLoc SL(Op); 8474 SDValue X = Op.getOperand(0); 8475 SDValue Y = Op.getOperand(1); 8476 8477 const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64); 8478 8479 SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1); 8480 8481 SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X); 8482 8483 SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0); 8484 8485 SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0); 8486 8487 SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One); 8488 8489 SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp); 8490 8491 SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One); 8492 8493 SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X); 8494 8495 SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1); 8496 SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3); 8497 8498 SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64, 8499 NegDivScale0, Mul, DivScale1); 8500 8501 SDValue Scale; 8502 8503 if (!Subtarget->hasUsableDivScaleConditionOutput()) { 8504 // Workaround a hardware bug on SI where the condition output from div_scale 8505 // is not usable. 8506 8507 const SDValue Hi = DAG.getConstant(1, SL, MVT::i32); 8508 8509 // Figure out if the scale to use for div_fmas. 8510 SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X); 8511 SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y); 8512 SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0); 8513 SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1); 8514 8515 SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi); 8516 SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi); 8517 8518 SDValue Scale0Hi 8519 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi); 8520 SDValue Scale1Hi 8521 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi); 8522 8523 SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ); 8524 SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ); 8525 Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen); 8526 } else { 8527 Scale = DivScale1.getValue(1); 8528 } 8529 8530 SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64, 8531 Fma4, Fma3, Mul, Scale); 8532 8533 return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X); 8534 } 8535 8536 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const { 8537 EVT VT = Op.getValueType(); 8538 8539 if (VT == MVT::f32) 8540 return LowerFDIV32(Op, DAG); 8541 8542 if (VT == MVT::f64) 8543 return LowerFDIV64(Op, DAG); 8544 8545 if (VT == MVT::f16) 8546 return LowerFDIV16(Op, DAG); 8547 8548 llvm_unreachable("Unexpected type for fdiv"); 8549 } 8550 8551 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const { 8552 SDLoc DL(Op); 8553 StoreSDNode *Store = cast<StoreSDNode>(Op); 8554 EVT VT = Store->getMemoryVT(); 8555 8556 if (VT == MVT::i1) { 8557 return DAG.getTruncStore(Store->getChain(), DL, 8558 DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32), 8559 Store->getBasePtr(), MVT::i1, Store->getMemOperand()); 8560 } 8561 8562 assert(VT.isVector() && 8563 Store->getValue().getValueType().getScalarType() == MVT::i32); 8564 8565 unsigned AS = Store->getAddressSpace(); 8566 if (Subtarget->hasLDSMisalignedBug() && 8567 AS == AMDGPUAS::FLAT_ADDRESS && 8568 Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) { 8569 return SplitVectorStore(Op, DAG); 8570 } 8571 8572 MachineFunction &MF = DAG.getMachineFunction(); 8573 SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 8574 // If there is a possibilty that flat instruction access scratch memory 8575 // then we need to use the same legalization rules we use for private. 8576 if (AS == AMDGPUAS::FLAT_ADDRESS && 8577 !Subtarget->hasMultiDwordFlatScratchAddressing()) 8578 AS = MFI->hasFlatScratchInit() ? 8579 AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS; 8580 8581 unsigned NumElements = VT.getVectorNumElements(); 8582 if (AS == AMDGPUAS::GLOBAL_ADDRESS || 8583 AS == AMDGPUAS::FLAT_ADDRESS) { 8584 if (NumElements > 4) 8585 return SplitVectorStore(Op, DAG); 8586 // v3 stores not supported on SI. 8587 if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores()) 8588 return SplitVectorStore(Op, DAG); 8589 8590 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8591 VT, *Store->getMemOperand())) 8592 return expandUnalignedStore(Store, DAG); 8593 8594 return SDValue(); 8595 } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) { 8596 switch (Subtarget->getMaxPrivateElementSize()) { 8597 case 4: 8598 return scalarizeVectorStore(Store, DAG); 8599 case 8: 8600 if (NumElements > 2) 8601 return SplitVectorStore(Op, DAG); 8602 return SDValue(); 8603 case 16: 8604 if (NumElements > 4 || 8605 (NumElements == 3 && !Subtarget->enableFlatScratch())) 8606 return SplitVectorStore(Op, DAG); 8607 return SDValue(); 8608 default: 8609 llvm_unreachable("unsupported private_element_size"); 8610 } 8611 } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) { 8612 // Use ds_write_b128 or ds_write_b96 when possible. 8613 if (Subtarget->hasDS96AndDS128() && 8614 ((Subtarget->useDS128() && VT.getStoreSize() == 16) || 8615 (VT.getStoreSize() == 12)) && 8616 allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS, 8617 Store->getAlign())) 8618 return SDValue(); 8619 8620 if (NumElements > 2) 8621 return SplitVectorStore(Op, DAG); 8622 8623 // SI has a hardware bug in the LDS / GDS boounds checking: if the base 8624 // address is negative, then the instruction is incorrectly treated as 8625 // out-of-bounds even if base + offsets is in bounds. Split vectorized 8626 // stores here to avoid emitting ds_write2_b32. We may re-combine the 8627 // store later in the SILoadStoreOptimizer. 8628 if (!Subtarget->hasUsableDSOffset() && 8629 NumElements == 2 && VT.getStoreSize() == 8 && 8630 Store->getAlignment() < 8) { 8631 return SplitVectorStore(Op, DAG); 8632 } 8633 8634 if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 8635 VT, *Store->getMemOperand())) { 8636 if (VT.isVector()) 8637 return SplitVectorStore(Op, DAG); 8638 return expandUnalignedStore(Store, DAG); 8639 } 8640 8641 return SDValue(); 8642 } else { 8643 llvm_unreachable("unhandled address space"); 8644 } 8645 } 8646 8647 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const { 8648 SDLoc DL(Op); 8649 EVT VT = Op.getValueType(); 8650 SDValue Arg = Op.getOperand(0); 8651 SDValue TrigVal; 8652 8653 // Propagate fast-math flags so that the multiply we introduce can be folded 8654 // if Arg is already the result of a multiply by constant. 8655 auto Flags = Op->getFlags(); 8656 8657 SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT); 8658 8659 if (Subtarget->hasTrigReducedRange()) { 8660 SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8661 TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags); 8662 } else { 8663 TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags); 8664 } 8665 8666 switch (Op.getOpcode()) { 8667 case ISD::FCOS: 8668 return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags); 8669 case ISD::FSIN: 8670 return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags); 8671 default: 8672 llvm_unreachable("Wrong trig opcode"); 8673 } 8674 } 8675 8676 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const { 8677 AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op); 8678 assert(AtomicNode->isCompareAndSwap()); 8679 unsigned AS = AtomicNode->getAddressSpace(); 8680 8681 // No custom lowering required for local address space 8682 if (!AMDGPU::isFlatGlobalAddrSpace(AS)) 8683 return Op; 8684 8685 // Non-local address space requires custom lowering for atomic compare 8686 // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2 8687 SDLoc DL(Op); 8688 SDValue ChainIn = Op.getOperand(0); 8689 SDValue Addr = Op.getOperand(1); 8690 SDValue Old = Op.getOperand(2); 8691 SDValue New = Op.getOperand(3); 8692 EVT VT = Op.getValueType(); 8693 MVT SimpleVT = VT.getSimpleVT(); 8694 MVT VecType = MVT::getVectorVT(SimpleVT, 2); 8695 8696 SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old}); 8697 SDValue Ops[] = { ChainIn, Addr, NewOld }; 8698 8699 return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(), 8700 Ops, VT, AtomicNode->getMemOperand()); 8701 } 8702 8703 //===----------------------------------------------------------------------===// 8704 // Custom DAG optimizations 8705 //===----------------------------------------------------------------------===// 8706 8707 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N, 8708 DAGCombinerInfo &DCI) const { 8709 EVT VT = N->getValueType(0); 8710 EVT ScalarVT = VT.getScalarType(); 8711 if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16) 8712 return SDValue(); 8713 8714 SelectionDAG &DAG = DCI.DAG; 8715 SDLoc DL(N); 8716 8717 SDValue Src = N->getOperand(0); 8718 EVT SrcVT = Src.getValueType(); 8719 8720 // TODO: We could try to match extracting the higher bytes, which would be 8721 // easier if i8 vectors weren't promoted to i32 vectors, particularly after 8722 // types are legalized. v4i8 -> v4f32 is probably the only case to worry 8723 // about in practice. 8724 if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) { 8725 if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) { 8726 SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src); 8727 DCI.AddToWorklist(Cvt.getNode()); 8728 8729 // For the f16 case, fold to a cast to f32 and then cast back to f16. 8730 if (ScalarVT != MVT::f32) { 8731 Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt, 8732 DAG.getTargetConstant(0, DL, MVT::i32)); 8733 } 8734 return Cvt; 8735 } 8736 } 8737 8738 return SDValue(); 8739 } 8740 8741 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2) 8742 8743 // This is a variant of 8744 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2), 8745 // 8746 // The normal DAG combiner will do this, but only if the add has one use since 8747 // that would increase the number of instructions. 8748 // 8749 // This prevents us from seeing a constant offset that can be folded into a 8750 // memory instruction's addressing mode. If we know the resulting add offset of 8751 // a pointer can be folded into an addressing offset, we can replace the pointer 8752 // operand with the add of new constant offset. This eliminates one of the uses, 8753 // and may allow the remaining use to also be simplified. 8754 // 8755 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N, 8756 unsigned AddrSpace, 8757 EVT MemVT, 8758 DAGCombinerInfo &DCI) const { 8759 SDValue N0 = N->getOperand(0); 8760 SDValue N1 = N->getOperand(1); 8761 8762 // We only do this to handle cases where it's profitable when there are 8763 // multiple uses of the add, so defer to the standard combine. 8764 if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) || 8765 N0->hasOneUse()) 8766 return SDValue(); 8767 8768 const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1); 8769 if (!CN1) 8770 return SDValue(); 8771 8772 const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1)); 8773 if (!CAdd) 8774 return SDValue(); 8775 8776 // If the resulting offset is too large, we can't fold it into the addressing 8777 // mode offset. 8778 APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue(); 8779 Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext()); 8780 8781 AddrMode AM; 8782 AM.HasBaseReg = true; 8783 AM.BaseOffs = Offset.getSExtValue(); 8784 if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace)) 8785 return SDValue(); 8786 8787 SelectionDAG &DAG = DCI.DAG; 8788 SDLoc SL(N); 8789 EVT VT = N->getValueType(0); 8790 8791 SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1); 8792 SDValue COffset = DAG.getConstant(Offset, SL, VT); 8793 8794 SDNodeFlags Flags; 8795 Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() && 8796 (N0.getOpcode() == ISD::OR || 8797 N0->getFlags().hasNoUnsignedWrap())); 8798 8799 return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags); 8800 } 8801 8802 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset 8803 /// by the chain and intrinsic ID. Theoretically we would also need to check the 8804 /// specific intrinsic, but they all place the pointer operand first. 8805 static unsigned getBasePtrIndex(const MemSDNode *N) { 8806 switch (N->getOpcode()) { 8807 case ISD::STORE: 8808 case ISD::INTRINSIC_W_CHAIN: 8809 case ISD::INTRINSIC_VOID: 8810 return 2; 8811 default: 8812 return 1; 8813 } 8814 } 8815 8816 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N, 8817 DAGCombinerInfo &DCI) const { 8818 SelectionDAG &DAG = DCI.DAG; 8819 SDLoc SL(N); 8820 8821 unsigned PtrIdx = getBasePtrIndex(N); 8822 SDValue Ptr = N->getOperand(PtrIdx); 8823 8824 // TODO: We could also do this for multiplies. 8825 if (Ptr.getOpcode() == ISD::SHL) { 8826 SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(), N->getAddressSpace(), 8827 N->getMemoryVT(), DCI); 8828 if (NewPtr) { 8829 SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end()); 8830 8831 NewOps[PtrIdx] = NewPtr; 8832 return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0); 8833 } 8834 } 8835 8836 return SDValue(); 8837 } 8838 8839 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) { 8840 return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) || 8841 (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) || 8842 (Opc == ISD::XOR && Val == 0); 8843 } 8844 8845 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This 8846 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit 8847 // integer combine opportunities since most 64-bit operations are decomposed 8848 // this way. TODO: We won't want this for SALU especially if it is an inline 8849 // immediate. 8850 SDValue SITargetLowering::splitBinaryBitConstantOp( 8851 DAGCombinerInfo &DCI, 8852 const SDLoc &SL, 8853 unsigned Opc, SDValue LHS, 8854 const ConstantSDNode *CRHS) const { 8855 uint64_t Val = CRHS->getZExtValue(); 8856 uint32_t ValLo = Lo_32(Val); 8857 uint32_t ValHi = Hi_32(Val); 8858 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 8859 8860 if ((bitOpWithConstantIsReducible(Opc, ValLo) || 8861 bitOpWithConstantIsReducible(Opc, ValHi)) || 8862 (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) { 8863 // If we need to materialize a 64-bit immediate, it will be split up later 8864 // anyway. Avoid creating the harder to understand 64-bit immediate 8865 // materialization. 8866 return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi); 8867 } 8868 8869 return SDValue(); 8870 } 8871 8872 // Returns true if argument is a boolean value which is not serialized into 8873 // memory or argument and does not require v_cndmask_b32 to be deserialized. 8874 static bool isBoolSGPR(SDValue V) { 8875 if (V.getValueType() != MVT::i1) 8876 return false; 8877 switch (V.getOpcode()) { 8878 default: 8879 break; 8880 case ISD::SETCC: 8881 case AMDGPUISD::FP_CLASS: 8882 return true; 8883 case ISD::AND: 8884 case ISD::OR: 8885 case ISD::XOR: 8886 return isBoolSGPR(V.getOperand(0)) && isBoolSGPR(V.getOperand(1)); 8887 } 8888 return false; 8889 } 8890 8891 // If a constant has all zeroes or all ones within each byte return it. 8892 // Otherwise return 0. 8893 static uint32_t getConstantPermuteMask(uint32_t C) { 8894 // 0xff for any zero byte in the mask 8895 uint32_t ZeroByteMask = 0; 8896 if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff; 8897 if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00; 8898 if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000; 8899 if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000; 8900 uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte 8901 if ((NonZeroByteMask & C) != NonZeroByteMask) 8902 return 0; // Partial bytes selected. 8903 return C; 8904 } 8905 8906 // Check if a node selects whole bytes from its operand 0 starting at a byte 8907 // boundary while masking the rest. Returns select mask as in the v_perm_b32 8908 // or -1 if not succeeded. 8909 // Note byte select encoding: 8910 // value 0-3 selects corresponding source byte; 8911 // value 0xc selects zero; 8912 // value 0xff selects 0xff. 8913 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) { 8914 assert(V.getValueSizeInBits() == 32); 8915 8916 if (V.getNumOperands() != 2) 8917 return ~0; 8918 8919 ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1)); 8920 if (!N1) 8921 return ~0; 8922 8923 uint32_t C = N1->getZExtValue(); 8924 8925 switch (V.getOpcode()) { 8926 default: 8927 break; 8928 case ISD::AND: 8929 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8930 return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask); 8931 } 8932 break; 8933 8934 case ISD::OR: 8935 if (uint32_t ConstMask = getConstantPermuteMask(C)) { 8936 return (0x03020100 & ~ConstMask) | ConstMask; 8937 } 8938 break; 8939 8940 case ISD::SHL: 8941 if (C % 8) 8942 return ~0; 8943 8944 return uint32_t((0x030201000c0c0c0cull << C) >> 32); 8945 8946 case ISD::SRL: 8947 if (C % 8) 8948 return ~0; 8949 8950 return uint32_t(0x0c0c0c0c03020100ull >> C); 8951 } 8952 8953 return ~0; 8954 } 8955 8956 SDValue SITargetLowering::performAndCombine(SDNode *N, 8957 DAGCombinerInfo &DCI) const { 8958 if (DCI.isBeforeLegalize()) 8959 return SDValue(); 8960 8961 SelectionDAG &DAG = DCI.DAG; 8962 EVT VT = N->getValueType(0); 8963 SDValue LHS = N->getOperand(0); 8964 SDValue RHS = N->getOperand(1); 8965 8966 8967 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 8968 if (VT == MVT::i64 && CRHS) { 8969 if (SDValue Split 8970 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS)) 8971 return Split; 8972 } 8973 8974 if (CRHS && VT == MVT::i32) { 8975 // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb 8976 // nb = number of trailing zeroes in mask 8977 // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass, 8978 // given that we are selecting 8 or 16 bit fields starting at byte boundary. 8979 uint64_t Mask = CRHS->getZExtValue(); 8980 unsigned Bits = countPopulation(Mask); 8981 if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL && 8982 (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) { 8983 if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) { 8984 unsigned Shift = CShift->getZExtValue(); 8985 unsigned NB = CRHS->getAPIntValue().countTrailingZeros(); 8986 unsigned Offset = NB + Shift; 8987 if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary. 8988 SDLoc SL(N); 8989 SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32, 8990 LHS->getOperand(0), 8991 DAG.getConstant(Offset, SL, MVT::i32), 8992 DAG.getConstant(Bits, SL, MVT::i32)); 8993 EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits); 8994 SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE, 8995 DAG.getValueType(NarrowVT)); 8996 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext, 8997 DAG.getConstant(NB, SDLoc(CRHS), MVT::i32)); 8998 return Shl; 8999 } 9000 } 9001 } 9002 9003 // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9004 if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM && 9005 isa<ConstantSDNode>(LHS.getOperand(2))) { 9006 uint32_t Sel = getConstantPermuteMask(Mask); 9007 if (!Sel) 9008 return SDValue(); 9009 9010 // Select 0xc for all zero bytes 9011 Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c); 9012 SDLoc DL(N); 9013 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9014 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9015 } 9016 } 9017 9018 // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) -> 9019 // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity) 9020 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) { 9021 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9022 ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get(); 9023 9024 SDValue X = LHS.getOperand(0); 9025 SDValue Y = RHS.getOperand(0); 9026 if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X) 9027 return SDValue(); 9028 9029 if (LCC == ISD::SETO) { 9030 if (X != LHS.getOperand(1)) 9031 return SDValue(); 9032 9033 if (RCC == ISD::SETUNE) { 9034 const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1)); 9035 if (!C1 || !C1->isInfinity() || C1->isNegative()) 9036 return SDValue(); 9037 9038 const uint32_t Mask = SIInstrFlags::N_NORMAL | 9039 SIInstrFlags::N_SUBNORMAL | 9040 SIInstrFlags::N_ZERO | 9041 SIInstrFlags::P_ZERO | 9042 SIInstrFlags::P_SUBNORMAL | 9043 SIInstrFlags::P_NORMAL; 9044 9045 static_assert(((~(SIInstrFlags::S_NAN | 9046 SIInstrFlags::Q_NAN | 9047 SIInstrFlags::N_INFINITY | 9048 SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask, 9049 "mask not equal"); 9050 9051 SDLoc DL(N); 9052 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9053 X, DAG.getConstant(Mask, DL, MVT::i32)); 9054 } 9055 } 9056 } 9057 9058 if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS) 9059 std::swap(LHS, RHS); 9060 9061 if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS && 9062 RHS.hasOneUse()) { 9063 ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9064 // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan) 9065 // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan) 9066 const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9067 if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask && 9068 (RHS.getOperand(0) == LHS.getOperand(0) && 9069 LHS.getOperand(0) == LHS.getOperand(1))) { 9070 const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN; 9071 unsigned NewMask = LCC == ISD::SETO ? 9072 Mask->getZExtValue() & ~OrdMask : 9073 Mask->getZExtValue() & OrdMask; 9074 9075 SDLoc DL(N); 9076 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0), 9077 DAG.getConstant(NewMask, DL, MVT::i32)); 9078 } 9079 } 9080 9081 if (VT == MVT::i32 && 9082 (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) { 9083 // and x, (sext cc from i1) => select cc, x, 0 9084 if (RHS.getOpcode() != ISD::SIGN_EXTEND) 9085 std::swap(LHS, RHS); 9086 if (isBoolSGPR(RHS.getOperand(0))) 9087 return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0), 9088 LHS, DAG.getConstant(0, SDLoc(N), MVT::i32)); 9089 } 9090 9091 // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9092 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9093 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9094 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9095 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9096 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9097 if (LHSMask != ~0u && RHSMask != ~0u) { 9098 // Canonicalize the expression in an attempt to have fewer unique masks 9099 // and therefore fewer registers used to hold the masks. 9100 if (LHSMask > RHSMask) { 9101 std::swap(LHSMask, RHSMask); 9102 std::swap(LHS, RHS); 9103 } 9104 9105 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9106 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9107 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9108 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9109 9110 // Check of we need to combine values from two sources within a byte. 9111 if (!(LHSUsedLanes & RHSUsedLanes) && 9112 // If we select high and lower word keep it for SDWA. 9113 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9114 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9115 // Each byte in each mask is either selector mask 0-3, or has higher 9116 // bits set in either of masks, which can be 0xff for 0xff or 0x0c for 9117 // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise 9118 // mask which is not 0xff wins. By anding both masks we have a correct 9119 // result except that 0x0c shall be corrected to give 0x0c only. 9120 uint32_t Mask = LHSMask & RHSMask; 9121 for (unsigned I = 0; I < 32; I += 8) { 9122 uint32_t ByteSel = 0xff << I; 9123 if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c) 9124 Mask &= (0x0c << I) & 0xffffffff; 9125 } 9126 9127 // Add 4 to each active LHS lane. It will not affect any existing 0xff 9128 // or 0x0c. 9129 uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404); 9130 SDLoc DL(N); 9131 9132 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9133 LHS.getOperand(0), RHS.getOperand(0), 9134 DAG.getConstant(Sel, DL, MVT::i32)); 9135 } 9136 } 9137 } 9138 9139 return SDValue(); 9140 } 9141 9142 SDValue SITargetLowering::performOrCombine(SDNode *N, 9143 DAGCombinerInfo &DCI) const { 9144 SelectionDAG &DAG = DCI.DAG; 9145 SDValue LHS = N->getOperand(0); 9146 SDValue RHS = N->getOperand(1); 9147 9148 EVT VT = N->getValueType(0); 9149 if (VT == MVT::i1) { 9150 // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2) 9151 if (LHS.getOpcode() == AMDGPUISD::FP_CLASS && 9152 RHS.getOpcode() == AMDGPUISD::FP_CLASS) { 9153 SDValue Src = LHS.getOperand(0); 9154 if (Src != RHS.getOperand(0)) 9155 return SDValue(); 9156 9157 const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 9158 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 9159 if (!CLHS || !CRHS) 9160 return SDValue(); 9161 9162 // Only 10 bits are used. 9163 static const uint32_t MaxMask = 0x3ff; 9164 9165 uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask; 9166 SDLoc DL(N); 9167 return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, 9168 Src, DAG.getConstant(NewMask, DL, MVT::i32)); 9169 } 9170 9171 return SDValue(); 9172 } 9173 9174 // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2) 9175 if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() && 9176 LHS.getOpcode() == AMDGPUISD::PERM && 9177 isa<ConstantSDNode>(LHS.getOperand(2))) { 9178 uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1)); 9179 if (!Sel) 9180 return SDValue(); 9181 9182 Sel |= LHS.getConstantOperandVal(2); 9183 SDLoc DL(N); 9184 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0), 9185 LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32)); 9186 } 9187 9188 // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2) 9189 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9190 if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() && 9191 N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32_e64) != -1) { 9192 uint32_t LHSMask = getPermuteMask(DAG, LHS); 9193 uint32_t RHSMask = getPermuteMask(DAG, RHS); 9194 if (LHSMask != ~0u && RHSMask != ~0u) { 9195 // Canonicalize the expression in an attempt to have fewer unique masks 9196 // and therefore fewer registers used to hold the masks. 9197 if (LHSMask > RHSMask) { 9198 std::swap(LHSMask, RHSMask); 9199 std::swap(LHS, RHS); 9200 } 9201 9202 // Select 0xc for each lane used from source operand. Zero has 0xc mask 9203 // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range. 9204 uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9205 uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c; 9206 9207 // Check of we need to combine values from two sources within a byte. 9208 if (!(LHSUsedLanes & RHSUsedLanes) && 9209 // If we select high and lower word keep it for SDWA. 9210 // TODO: teach SDWA to work with v_perm_b32 and remove the check. 9211 !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) { 9212 // Kill zero bytes selected by other mask. Zero value is 0xc. 9213 LHSMask &= ~RHSUsedLanes; 9214 RHSMask &= ~LHSUsedLanes; 9215 // Add 4 to each active LHS lane 9216 LHSMask |= LHSUsedLanes & 0x04040404; 9217 // Combine masks 9218 uint32_t Sel = LHSMask | RHSMask; 9219 SDLoc DL(N); 9220 9221 return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, 9222 LHS.getOperand(0), RHS.getOperand(0), 9223 DAG.getConstant(Sel, DL, MVT::i32)); 9224 } 9225 } 9226 } 9227 9228 if (VT != MVT::i64 || DCI.isBeforeLegalizeOps()) 9229 return SDValue(); 9230 9231 // TODO: This could be a generic combine with a predicate for extracting the 9232 // high half of an integer being free. 9233 9234 // (or i64:x, (zero_extend i32:y)) -> 9235 // i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x))) 9236 if (LHS.getOpcode() == ISD::ZERO_EXTEND && 9237 RHS.getOpcode() != ISD::ZERO_EXTEND) 9238 std::swap(LHS, RHS); 9239 9240 if (RHS.getOpcode() == ISD::ZERO_EXTEND) { 9241 SDValue ExtSrc = RHS.getOperand(0); 9242 EVT SrcVT = ExtSrc.getValueType(); 9243 if (SrcVT == MVT::i32) { 9244 SDLoc SL(N); 9245 SDValue LowLHS, HiBits; 9246 std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG); 9247 SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc); 9248 9249 DCI.AddToWorklist(LowOr.getNode()); 9250 DCI.AddToWorklist(HiBits.getNode()); 9251 9252 SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, 9253 LowOr, HiBits); 9254 return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec); 9255 } 9256 } 9257 9258 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9259 if (CRHS) { 9260 if (SDValue Split 9261 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS)) 9262 return Split; 9263 } 9264 9265 return SDValue(); 9266 } 9267 9268 SDValue SITargetLowering::performXorCombine(SDNode *N, 9269 DAGCombinerInfo &DCI) const { 9270 EVT VT = N->getValueType(0); 9271 if (VT != MVT::i64) 9272 return SDValue(); 9273 9274 SDValue LHS = N->getOperand(0); 9275 SDValue RHS = N->getOperand(1); 9276 9277 const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS); 9278 if (CRHS) { 9279 if (SDValue Split 9280 = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS)) 9281 return Split; 9282 } 9283 9284 return SDValue(); 9285 } 9286 9287 // Instructions that will be lowered with a final instruction that zeros the 9288 // high result bits. 9289 // XXX - probably only need to list legal operations. 9290 static bool fp16SrcZerosHighBits(unsigned Opc) { 9291 switch (Opc) { 9292 case ISD::FADD: 9293 case ISD::FSUB: 9294 case ISD::FMUL: 9295 case ISD::FDIV: 9296 case ISD::FREM: 9297 case ISD::FMA: 9298 case ISD::FMAD: 9299 case ISD::FCANONICALIZE: 9300 case ISD::FP_ROUND: 9301 case ISD::UINT_TO_FP: 9302 case ISD::SINT_TO_FP: 9303 case ISD::FABS: 9304 // Fabs is lowered to a bit operation, but it's an and which will clear the 9305 // high bits anyway. 9306 case ISD::FSQRT: 9307 case ISD::FSIN: 9308 case ISD::FCOS: 9309 case ISD::FPOWI: 9310 case ISD::FPOW: 9311 case ISD::FLOG: 9312 case ISD::FLOG2: 9313 case ISD::FLOG10: 9314 case ISD::FEXP: 9315 case ISD::FEXP2: 9316 case ISD::FCEIL: 9317 case ISD::FTRUNC: 9318 case ISD::FRINT: 9319 case ISD::FNEARBYINT: 9320 case ISD::FROUND: 9321 case ISD::FFLOOR: 9322 case ISD::FMINNUM: 9323 case ISD::FMAXNUM: 9324 case AMDGPUISD::FRACT: 9325 case AMDGPUISD::CLAMP: 9326 case AMDGPUISD::COS_HW: 9327 case AMDGPUISD::SIN_HW: 9328 case AMDGPUISD::FMIN3: 9329 case AMDGPUISD::FMAX3: 9330 case AMDGPUISD::FMED3: 9331 case AMDGPUISD::FMAD_FTZ: 9332 case AMDGPUISD::RCP: 9333 case AMDGPUISD::RSQ: 9334 case AMDGPUISD::RCP_IFLAG: 9335 case AMDGPUISD::LDEXP: 9336 return true; 9337 default: 9338 // fcopysign, select and others may be lowered to 32-bit bit operations 9339 // which don't zero the high bits. 9340 return false; 9341 } 9342 } 9343 9344 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N, 9345 DAGCombinerInfo &DCI) const { 9346 if (!Subtarget->has16BitInsts() || 9347 DCI.getDAGCombineLevel() < AfterLegalizeDAG) 9348 return SDValue(); 9349 9350 EVT VT = N->getValueType(0); 9351 if (VT != MVT::i32) 9352 return SDValue(); 9353 9354 SDValue Src = N->getOperand(0); 9355 if (Src.getValueType() != MVT::i16) 9356 return SDValue(); 9357 9358 // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src 9359 // FIXME: It is not universally true that the high bits are zeroed on gfx9. 9360 if (Src.getOpcode() == ISD::BITCAST) { 9361 SDValue BCSrc = Src.getOperand(0); 9362 if (BCSrc.getValueType() == MVT::f16 && 9363 fp16SrcZerosHighBits(BCSrc.getOpcode())) 9364 return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc); 9365 } 9366 9367 return SDValue(); 9368 } 9369 9370 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N, 9371 DAGCombinerInfo &DCI) 9372 const { 9373 SDValue Src = N->getOperand(0); 9374 auto *VTSign = cast<VTSDNode>(N->getOperand(1)); 9375 9376 if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE && 9377 VTSign->getVT() == MVT::i8) || 9378 (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT && 9379 VTSign->getVT() == MVT::i16)) && 9380 Src.hasOneUse()) { 9381 auto *M = cast<MemSDNode>(Src); 9382 SDValue Ops[] = { 9383 Src.getOperand(0), // Chain 9384 Src.getOperand(1), // rsrc 9385 Src.getOperand(2), // vindex 9386 Src.getOperand(3), // voffset 9387 Src.getOperand(4), // soffset 9388 Src.getOperand(5), // offset 9389 Src.getOperand(6), 9390 Src.getOperand(7) 9391 }; 9392 // replace with BUFFER_LOAD_BYTE/SHORT 9393 SDVTList ResList = DCI.DAG.getVTList(MVT::i32, 9394 Src.getOperand(0).getValueType()); 9395 unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ? 9396 AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT; 9397 SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N), 9398 ResList, 9399 Ops, M->getMemoryVT(), 9400 M->getMemOperand()); 9401 return DCI.DAG.getMergeValues({BufferLoadSignExt, 9402 BufferLoadSignExt.getValue(1)}, SDLoc(N)); 9403 } 9404 return SDValue(); 9405 } 9406 9407 SDValue SITargetLowering::performClassCombine(SDNode *N, 9408 DAGCombinerInfo &DCI) const { 9409 SelectionDAG &DAG = DCI.DAG; 9410 SDValue Mask = N->getOperand(1); 9411 9412 // fp_class x, 0 -> false 9413 if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) { 9414 if (CMask->isNullValue()) 9415 return DAG.getConstant(0, SDLoc(N), MVT::i1); 9416 } 9417 9418 if (N->getOperand(0).isUndef()) 9419 return DAG.getUNDEF(MVT::i1); 9420 9421 return SDValue(); 9422 } 9423 9424 SDValue SITargetLowering::performRcpCombine(SDNode *N, 9425 DAGCombinerInfo &DCI) const { 9426 EVT VT = N->getValueType(0); 9427 SDValue N0 = N->getOperand(0); 9428 9429 if (N0.isUndef()) 9430 return N0; 9431 9432 if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP || 9433 N0.getOpcode() == ISD::SINT_TO_FP)) { 9434 return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0, 9435 N->getFlags()); 9436 } 9437 9438 if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) { 9439 return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT, 9440 N0.getOperand(0), N->getFlags()); 9441 } 9442 9443 return AMDGPUTargetLowering::performRcpCombine(N, DCI); 9444 } 9445 9446 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op, 9447 unsigned MaxDepth) const { 9448 unsigned Opcode = Op.getOpcode(); 9449 if (Opcode == ISD::FCANONICALIZE) 9450 return true; 9451 9452 if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9453 auto F = CFP->getValueAPF(); 9454 if (F.isNaN() && F.isSignaling()) 9455 return false; 9456 return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType()); 9457 } 9458 9459 // If source is a result of another standard FP operation it is already in 9460 // canonical form. 9461 if (MaxDepth == 0) 9462 return false; 9463 9464 switch (Opcode) { 9465 // These will flush denorms if required. 9466 case ISD::FADD: 9467 case ISD::FSUB: 9468 case ISD::FMUL: 9469 case ISD::FCEIL: 9470 case ISD::FFLOOR: 9471 case ISD::FMA: 9472 case ISD::FMAD: 9473 case ISD::FSQRT: 9474 case ISD::FDIV: 9475 case ISD::FREM: 9476 case ISD::FP_ROUND: 9477 case ISD::FP_EXTEND: 9478 case AMDGPUISD::FMUL_LEGACY: 9479 case AMDGPUISD::FMAD_FTZ: 9480 case AMDGPUISD::RCP: 9481 case AMDGPUISD::RSQ: 9482 case AMDGPUISD::RSQ_CLAMP: 9483 case AMDGPUISD::RCP_LEGACY: 9484 case AMDGPUISD::RCP_IFLAG: 9485 case AMDGPUISD::DIV_SCALE: 9486 case AMDGPUISD::DIV_FMAS: 9487 case AMDGPUISD::DIV_FIXUP: 9488 case AMDGPUISD::FRACT: 9489 case AMDGPUISD::LDEXP: 9490 case AMDGPUISD::CVT_PKRTZ_F16_F32: 9491 case AMDGPUISD::CVT_F32_UBYTE0: 9492 case AMDGPUISD::CVT_F32_UBYTE1: 9493 case AMDGPUISD::CVT_F32_UBYTE2: 9494 case AMDGPUISD::CVT_F32_UBYTE3: 9495 return true; 9496 9497 // It can/will be lowered or combined as a bit operation. 9498 // Need to check their input recursively to handle. 9499 case ISD::FNEG: 9500 case ISD::FABS: 9501 case ISD::FCOPYSIGN: 9502 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9503 9504 case ISD::FSIN: 9505 case ISD::FCOS: 9506 case ISD::FSINCOS: 9507 return Op.getValueType().getScalarType() != MVT::f16; 9508 9509 case ISD::FMINNUM: 9510 case ISD::FMAXNUM: 9511 case ISD::FMINNUM_IEEE: 9512 case ISD::FMAXNUM_IEEE: 9513 case AMDGPUISD::CLAMP: 9514 case AMDGPUISD::FMED3: 9515 case AMDGPUISD::FMAX3: 9516 case AMDGPUISD::FMIN3: { 9517 // FIXME: Shouldn't treat the generic operations different based these. 9518 // However, we aren't really required to flush the result from 9519 // minnum/maxnum.. 9520 9521 // snans will be quieted, so we only need to worry about denormals. 9522 if (Subtarget->supportsMinMaxDenormModes() || 9523 denormalsEnabledForType(DAG, Op.getValueType())) 9524 return true; 9525 9526 // Flushing may be required. 9527 // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such 9528 // targets need to check their input recursively. 9529 9530 // FIXME: Does this apply with clamp? It's implemented with max. 9531 for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) { 9532 if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1)) 9533 return false; 9534 } 9535 9536 return true; 9537 } 9538 case ISD::SELECT: { 9539 return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) && 9540 isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1); 9541 } 9542 case ISD::BUILD_VECTOR: { 9543 for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) { 9544 SDValue SrcOp = Op.getOperand(i); 9545 if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1)) 9546 return false; 9547 } 9548 9549 return true; 9550 } 9551 case ISD::EXTRACT_VECTOR_ELT: 9552 case ISD::EXTRACT_SUBVECTOR: { 9553 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1); 9554 } 9555 case ISD::INSERT_VECTOR_ELT: { 9556 return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) && 9557 isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1); 9558 } 9559 case ISD::UNDEF: 9560 // Could be anything. 9561 return false; 9562 9563 case ISD::BITCAST: { 9564 // Hack round the mess we make when legalizing extract_vector_elt 9565 SDValue Src = Op.getOperand(0); 9566 if (Src.getValueType() == MVT::i16 && 9567 Src.getOpcode() == ISD::TRUNCATE) { 9568 SDValue TruncSrc = Src.getOperand(0); 9569 if (TruncSrc.getValueType() == MVT::i32 && 9570 TruncSrc.getOpcode() == ISD::BITCAST && 9571 TruncSrc.getOperand(0).getValueType() == MVT::v2f16) { 9572 return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1); 9573 } 9574 } 9575 9576 return false; 9577 } 9578 case ISD::INTRINSIC_WO_CHAIN: { 9579 unsigned IntrinsicID 9580 = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 9581 // TODO: Handle more intrinsics 9582 switch (IntrinsicID) { 9583 case Intrinsic::amdgcn_cvt_pkrtz: 9584 case Intrinsic::amdgcn_cubeid: 9585 case Intrinsic::amdgcn_frexp_mant: 9586 case Intrinsic::amdgcn_fdot2: 9587 case Intrinsic::amdgcn_rcp: 9588 case Intrinsic::amdgcn_rsq: 9589 case Intrinsic::amdgcn_rsq_clamp: 9590 case Intrinsic::amdgcn_rcp_legacy: 9591 case Intrinsic::amdgcn_rsq_legacy: 9592 case Intrinsic::amdgcn_trig_preop: 9593 return true; 9594 default: 9595 break; 9596 } 9597 9598 LLVM_FALLTHROUGH; 9599 } 9600 default: 9601 return denormalsEnabledForType(DAG, Op.getValueType()) && 9602 DAG.isKnownNeverSNaN(Op); 9603 } 9604 9605 llvm_unreachable("invalid operation"); 9606 } 9607 9608 // Constant fold canonicalize. 9609 SDValue SITargetLowering::getCanonicalConstantFP( 9610 SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const { 9611 // Flush denormals to 0 if not enabled. 9612 if (C.isDenormal() && !denormalsEnabledForType(DAG, VT)) 9613 return DAG.getConstantFP(0.0, SL, VT); 9614 9615 if (C.isNaN()) { 9616 APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics()); 9617 if (C.isSignaling()) { 9618 // Quiet a signaling NaN. 9619 // FIXME: Is this supposed to preserve payload bits? 9620 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9621 } 9622 9623 // Make sure it is the canonical NaN bitpattern. 9624 // 9625 // TODO: Can we use -1 as the canonical NaN value since it's an inline 9626 // immediate? 9627 if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt()) 9628 return DAG.getConstantFP(CanonicalQNaN, SL, VT); 9629 } 9630 9631 // Already canonical. 9632 return DAG.getConstantFP(C, SL, VT); 9633 } 9634 9635 static bool vectorEltWillFoldAway(SDValue Op) { 9636 return Op.isUndef() || isa<ConstantFPSDNode>(Op); 9637 } 9638 9639 SDValue SITargetLowering::performFCanonicalizeCombine( 9640 SDNode *N, 9641 DAGCombinerInfo &DCI) const { 9642 SelectionDAG &DAG = DCI.DAG; 9643 SDValue N0 = N->getOperand(0); 9644 EVT VT = N->getValueType(0); 9645 9646 // fcanonicalize undef -> qnan 9647 if (N0.isUndef()) { 9648 APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT)); 9649 return DAG.getConstantFP(QNaN, SDLoc(N), VT); 9650 } 9651 9652 if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) { 9653 EVT VT = N->getValueType(0); 9654 return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF()); 9655 } 9656 9657 // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x), 9658 // (fcanonicalize k) 9659 // 9660 // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0 9661 9662 // TODO: This could be better with wider vectors that will be split to v2f16, 9663 // and to consider uses since there aren't that many packed operations. 9664 if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 && 9665 isTypeLegal(MVT::v2f16)) { 9666 SDLoc SL(N); 9667 SDValue NewElts[2]; 9668 SDValue Lo = N0.getOperand(0); 9669 SDValue Hi = N0.getOperand(1); 9670 EVT EltVT = Lo.getValueType(); 9671 9672 if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) { 9673 for (unsigned I = 0; I != 2; ++I) { 9674 SDValue Op = N0.getOperand(I); 9675 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) { 9676 NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT, 9677 CFP->getValueAPF()); 9678 } else if (Op.isUndef()) { 9679 // Handled below based on what the other operand is. 9680 NewElts[I] = Op; 9681 } else { 9682 NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op); 9683 } 9684 } 9685 9686 // If one half is undef, and one is constant, perfer a splat vector rather 9687 // than the normal qNaN. If it's a register, prefer 0.0 since that's 9688 // cheaper to use and may be free with a packed operation. 9689 if (NewElts[0].isUndef()) { 9690 if (isa<ConstantFPSDNode>(NewElts[1])) 9691 NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ? 9692 NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT); 9693 } 9694 9695 if (NewElts[1].isUndef()) { 9696 NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ? 9697 NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT); 9698 } 9699 9700 return DAG.getBuildVector(VT, SL, NewElts); 9701 } 9702 } 9703 9704 unsigned SrcOpc = N0.getOpcode(); 9705 9706 // If it's free to do so, push canonicalizes further up the source, which may 9707 // find a canonical source. 9708 // 9709 // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for 9710 // sNaNs. 9711 if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) { 9712 auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1)); 9713 if (CRHS && N0.hasOneUse()) { 9714 SDLoc SL(N); 9715 SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT, 9716 N0.getOperand(0)); 9717 SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF()); 9718 DCI.AddToWorklist(Canon0.getNode()); 9719 9720 return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1); 9721 } 9722 } 9723 9724 return isCanonicalized(DAG, N0) ? N0 : SDValue(); 9725 } 9726 9727 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) { 9728 switch (Opc) { 9729 case ISD::FMAXNUM: 9730 case ISD::FMAXNUM_IEEE: 9731 return AMDGPUISD::FMAX3; 9732 case ISD::SMAX: 9733 return AMDGPUISD::SMAX3; 9734 case ISD::UMAX: 9735 return AMDGPUISD::UMAX3; 9736 case ISD::FMINNUM: 9737 case ISD::FMINNUM_IEEE: 9738 return AMDGPUISD::FMIN3; 9739 case ISD::SMIN: 9740 return AMDGPUISD::SMIN3; 9741 case ISD::UMIN: 9742 return AMDGPUISD::UMIN3; 9743 default: 9744 llvm_unreachable("Not a min/max opcode"); 9745 } 9746 } 9747 9748 SDValue SITargetLowering::performIntMed3ImmCombine( 9749 SelectionDAG &DAG, const SDLoc &SL, 9750 SDValue Op0, SDValue Op1, bool Signed) const { 9751 ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1); 9752 if (!K1) 9753 return SDValue(); 9754 9755 ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1)); 9756 if (!K0) 9757 return SDValue(); 9758 9759 if (Signed) { 9760 if (K0->getAPIntValue().sge(K1->getAPIntValue())) 9761 return SDValue(); 9762 } else { 9763 if (K0->getAPIntValue().uge(K1->getAPIntValue())) 9764 return SDValue(); 9765 } 9766 9767 EVT VT = K0->getValueType(0); 9768 unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3; 9769 if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) { 9770 return DAG.getNode(Med3Opc, SL, VT, 9771 Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0)); 9772 } 9773 9774 // If there isn't a 16-bit med3 operation, convert to 32-bit. 9775 if (VT == MVT::i16) { 9776 MVT NVT = MVT::i32; 9777 unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 9778 9779 SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0)); 9780 SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1)); 9781 SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1); 9782 9783 SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3); 9784 return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3); 9785 } 9786 9787 return SDValue(); 9788 } 9789 9790 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) { 9791 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) 9792 return C; 9793 9794 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) { 9795 if (ConstantFPSDNode *C = BV->getConstantFPSplatNode()) 9796 return C; 9797 } 9798 9799 return nullptr; 9800 } 9801 9802 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG, 9803 const SDLoc &SL, 9804 SDValue Op0, 9805 SDValue Op1) const { 9806 ConstantFPSDNode *K1 = getSplatConstantFP(Op1); 9807 if (!K1) 9808 return SDValue(); 9809 9810 ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1)); 9811 if (!K0) 9812 return SDValue(); 9813 9814 // Ordered >= (although NaN inputs should have folded away by now). 9815 if (K0->getValueAPF() > K1->getValueAPF()) 9816 return SDValue(); 9817 9818 const MachineFunction &MF = DAG.getMachineFunction(); 9819 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9820 9821 // TODO: Check IEEE bit enabled? 9822 EVT VT = Op0.getValueType(); 9823 if (Info->getMode().DX10Clamp) { 9824 // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the 9825 // hardware fmed3 behavior converting to a min. 9826 // FIXME: Should this be allowing -0.0? 9827 if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0)) 9828 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0)); 9829 } 9830 9831 // med3 for f16 is only available on gfx9+, and not available for v2f16. 9832 if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) { 9833 // This isn't safe with signaling NaNs because in IEEE mode, min/max on a 9834 // signaling NaN gives a quiet NaN. The quiet NaN input to the min would 9835 // then give the other result, which is different from med3 with a NaN 9836 // input. 9837 SDValue Var = Op0.getOperand(0); 9838 if (!DAG.isKnownNeverSNaN(Var)) 9839 return SDValue(); 9840 9841 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 9842 9843 if ((!K0->hasOneUse() || 9844 TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) && 9845 (!K1->hasOneUse() || 9846 TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) { 9847 return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0), 9848 Var, SDValue(K0, 0), SDValue(K1, 0)); 9849 } 9850 } 9851 9852 return SDValue(); 9853 } 9854 9855 SDValue SITargetLowering::performMinMaxCombine(SDNode *N, 9856 DAGCombinerInfo &DCI) const { 9857 SelectionDAG &DAG = DCI.DAG; 9858 9859 EVT VT = N->getValueType(0); 9860 unsigned Opc = N->getOpcode(); 9861 SDValue Op0 = N->getOperand(0); 9862 SDValue Op1 = N->getOperand(1); 9863 9864 // Only do this if the inner op has one use since this will just increases 9865 // register pressure for no benefit. 9866 9867 if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY && 9868 !VT.isVector() && 9869 (VT == MVT::i32 || VT == MVT::f32 || 9870 ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) { 9871 // max(max(a, b), c) -> max3(a, b, c) 9872 // min(min(a, b), c) -> min3(a, b, c) 9873 if (Op0.getOpcode() == Opc && Op0.hasOneUse()) { 9874 SDLoc DL(N); 9875 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9876 DL, 9877 N->getValueType(0), 9878 Op0.getOperand(0), 9879 Op0.getOperand(1), 9880 Op1); 9881 } 9882 9883 // Try commuted. 9884 // max(a, max(b, c)) -> max3(a, b, c) 9885 // min(a, min(b, c)) -> min3(a, b, c) 9886 if (Op1.getOpcode() == Opc && Op1.hasOneUse()) { 9887 SDLoc DL(N); 9888 return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc), 9889 DL, 9890 N->getValueType(0), 9891 Op0, 9892 Op1.getOperand(0), 9893 Op1.getOperand(1)); 9894 } 9895 } 9896 9897 // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1) 9898 if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) { 9899 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true)) 9900 return Med3; 9901 } 9902 9903 if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) { 9904 if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false)) 9905 return Med3; 9906 } 9907 9908 // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1) 9909 if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) || 9910 (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) || 9911 (Opc == AMDGPUISD::FMIN_LEGACY && 9912 Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) && 9913 (VT == MVT::f32 || VT == MVT::f64 || 9914 (VT == MVT::f16 && Subtarget->has16BitInsts()) || 9915 (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) && 9916 Op0.hasOneUse()) { 9917 if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1)) 9918 return Res; 9919 } 9920 9921 return SDValue(); 9922 } 9923 9924 static bool isClampZeroToOne(SDValue A, SDValue B) { 9925 if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) { 9926 if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) { 9927 // FIXME: Should this be allowing -0.0? 9928 return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) || 9929 (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0)); 9930 } 9931 } 9932 9933 return false; 9934 } 9935 9936 // FIXME: Should only worry about snans for version with chain. 9937 SDValue SITargetLowering::performFMed3Combine(SDNode *N, 9938 DAGCombinerInfo &DCI) const { 9939 EVT VT = N->getValueType(0); 9940 // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and 9941 // NaNs. With a NaN input, the order of the operands may change the result. 9942 9943 SelectionDAG &DAG = DCI.DAG; 9944 SDLoc SL(N); 9945 9946 SDValue Src0 = N->getOperand(0); 9947 SDValue Src1 = N->getOperand(1); 9948 SDValue Src2 = N->getOperand(2); 9949 9950 if (isClampZeroToOne(Src0, Src1)) { 9951 // const_a, const_b, x -> clamp is safe in all cases including signaling 9952 // nans. 9953 // FIXME: Should this be allowing -0.0? 9954 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2); 9955 } 9956 9957 const MachineFunction &MF = DAG.getMachineFunction(); 9958 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 9959 9960 // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother 9961 // handling no dx10-clamp? 9962 if (Info->getMode().DX10Clamp) { 9963 // If NaNs is clamped to 0, we are free to reorder the inputs. 9964 9965 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9966 std::swap(Src0, Src1); 9967 9968 if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2)) 9969 std::swap(Src1, Src2); 9970 9971 if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1)) 9972 std::swap(Src0, Src1); 9973 9974 if (isClampZeroToOne(Src1, Src2)) 9975 return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0); 9976 } 9977 9978 return SDValue(); 9979 } 9980 9981 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N, 9982 DAGCombinerInfo &DCI) const { 9983 SDValue Src0 = N->getOperand(0); 9984 SDValue Src1 = N->getOperand(1); 9985 if (Src0.isUndef() && Src1.isUndef()) 9986 return DCI.DAG.getUNDEF(N->getValueType(0)); 9987 return SDValue(); 9988 } 9989 9990 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be 9991 // expanded into a set of cmp/select instructions. 9992 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize, 9993 unsigned NumElem, 9994 bool IsDivergentIdx) { 9995 if (UseDivergentRegisterIndexing) 9996 return false; 9997 9998 unsigned VecSize = EltSize * NumElem; 9999 10000 // Sub-dword vectors of size 2 dword or less have better implementation. 10001 if (VecSize <= 64 && EltSize < 32) 10002 return false; 10003 10004 // Always expand the rest of sub-dword instructions, otherwise it will be 10005 // lowered via memory. 10006 if (EltSize < 32) 10007 return true; 10008 10009 // Always do this if var-idx is divergent, otherwise it will become a loop. 10010 if (IsDivergentIdx) 10011 return true; 10012 10013 // Large vectors would yield too many compares and v_cndmask_b32 instructions. 10014 unsigned NumInsts = NumElem /* Number of compares */ + 10015 ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */; 10016 return NumInsts <= 16; 10017 } 10018 10019 static bool shouldExpandVectorDynExt(SDNode *N) { 10020 SDValue Idx = N->getOperand(N->getNumOperands() - 1); 10021 if (isa<ConstantSDNode>(Idx)) 10022 return false; 10023 10024 SDValue Vec = N->getOperand(0); 10025 EVT VecVT = Vec.getValueType(); 10026 EVT EltVT = VecVT.getVectorElementType(); 10027 unsigned EltSize = EltVT.getSizeInBits(); 10028 unsigned NumElem = VecVT.getVectorNumElements(); 10029 10030 return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem, 10031 Idx->isDivergent()); 10032 } 10033 10034 SDValue SITargetLowering::performExtractVectorEltCombine( 10035 SDNode *N, DAGCombinerInfo &DCI) const { 10036 SDValue Vec = N->getOperand(0); 10037 SelectionDAG &DAG = DCI.DAG; 10038 10039 EVT VecVT = Vec.getValueType(); 10040 EVT EltVT = VecVT.getVectorElementType(); 10041 10042 if ((Vec.getOpcode() == ISD::FNEG || 10043 Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) { 10044 SDLoc SL(N); 10045 EVT EltVT = N->getValueType(0); 10046 SDValue Idx = N->getOperand(1); 10047 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10048 Vec.getOperand(0), Idx); 10049 return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt); 10050 } 10051 10052 // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx) 10053 // => 10054 // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx) 10055 // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx) 10056 // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt 10057 if (Vec.hasOneUse() && DCI.isBeforeLegalize()) { 10058 SDLoc SL(N); 10059 EVT EltVT = N->getValueType(0); 10060 SDValue Idx = N->getOperand(1); 10061 unsigned Opc = Vec.getOpcode(); 10062 10063 switch(Opc) { 10064 default: 10065 break; 10066 // TODO: Support other binary operations. 10067 case ISD::FADD: 10068 case ISD::FSUB: 10069 case ISD::FMUL: 10070 case ISD::ADD: 10071 case ISD::UMIN: 10072 case ISD::UMAX: 10073 case ISD::SMIN: 10074 case ISD::SMAX: 10075 case ISD::FMAXNUM: 10076 case ISD::FMINNUM: 10077 case ISD::FMAXNUM_IEEE: 10078 case ISD::FMINNUM_IEEE: { 10079 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10080 Vec.getOperand(0), Idx); 10081 SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, 10082 Vec.getOperand(1), Idx); 10083 10084 DCI.AddToWorklist(Elt0.getNode()); 10085 DCI.AddToWorklist(Elt1.getNode()); 10086 return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags()); 10087 } 10088 } 10089 } 10090 10091 unsigned VecSize = VecVT.getSizeInBits(); 10092 unsigned EltSize = EltVT.getSizeInBits(); 10093 10094 // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx) 10095 if (::shouldExpandVectorDynExt(N)) { 10096 SDLoc SL(N); 10097 SDValue Idx = N->getOperand(1); 10098 SDValue V; 10099 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10100 SDValue IC = DAG.getVectorIdxConstant(I, SL); 10101 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10102 if (I == 0) 10103 V = Elt; 10104 else 10105 V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ); 10106 } 10107 return V; 10108 } 10109 10110 if (!DCI.isBeforeLegalize()) 10111 return SDValue(); 10112 10113 // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit 10114 // elements. This exposes more load reduction opportunities by replacing 10115 // multiple small extract_vector_elements with a single 32-bit extract. 10116 auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10117 if (isa<MemSDNode>(Vec) && 10118 EltSize <= 16 && 10119 EltVT.isByteSized() && 10120 VecSize > 32 && 10121 VecSize % 32 == 0 && 10122 Idx) { 10123 EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT); 10124 10125 unsigned BitIndex = Idx->getZExtValue() * EltSize; 10126 unsigned EltIdx = BitIndex / 32; 10127 unsigned LeftoverBitIdx = BitIndex % 32; 10128 SDLoc SL(N); 10129 10130 SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec); 10131 DCI.AddToWorklist(Cast.getNode()); 10132 10133 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast, 10134 DAG.getConstant(EltIdx, SL, MVT::i32)); 10135 DCI.AddToWorklist(Elt.getNode()); 10136 SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt, 10137 DAG.getConstant(LeftoverBitIdx, SL, MVT::i32)); 10138 DCI.AddToWorklist(Srl.getNode()); 10139 10140 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl); 10141 DCI.AddToWorklist(Trunc.getNode()); 10142 return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc); 10143 } 10144 10145 return SDValue(); 10146 } 10147 10148 SDValue 10149 SITargetLowering::performInsertVectorEltCombine(SDNode *N, 10150 DAGCombinerInfo &DCI) const { 10151 SDValue Vec = N->getOperand(0); 10152 SDValue Idx = N->getOperand(2); 10153 EVT VecVT = Vec.getValueType(); 10154 EVT EltVT = VecVT.getVectorElementType(); 10155 10156 // INSERT_VECTOR_ELT (<n x e>, var-idx) 10157 // => BUILD_VECTOR n x select (e, const-idx) 10158 if (!::shouldExpandVectorDynExt(N)) 10159 return SDValue(); 10160 10161 SelectionDAG &DAG = DCI.DAG; 10162 SDLoc SL(N); 10163 SDValue Ins = N->getOperand(1); 10164 EVT IdxVT = Idx.getValueType(); 10165 10166 SmallVector<SDValue, 16> Ops; 10167 for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) { 10168 SDValue IC = DAG.getConstant(I, SL, IdxVT); 10169 SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC); 10170 SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ); 10171 Ops.push_back(V); 10172 } 10173 10174 return DAG.getBuildVector(VecVT, SL, Ops); 10175 } 10176 10177 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG, 10178 const SDNode *N0, 10179 const SDNode *N1) const { 10180 EVT VT = N0->getValueType(0); 10181 10182 // Only do this if we are not trying to support denormals. v_mad_f32 does not 10183 // support denormals ever. 10184 if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) || 10185 (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) && 10186 getSubtarget()->hasMadF16())) && 10187 isOperationLegal(ISD::FMAD, VT)) 10188 return ISD::FMAD; 10189 10190 const TargetOptions &Options = DAG.getTarget().Options; 10191 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10192 (N0->getFlags().hasAllowContract() && 10193 N1->getFlags().hasAllowContract())) && 10194 isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) { 10195 return ISD::FMA; 10196 } 10197 10198 return 0; 10199 } 10200 10201 // For a reassociatable opcode perform: 10202 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform 10203 SDValue SITargetLowering::reassociateScalarOps(SDNode *N, 10204 SelectionDAG &DAG) const { 10205 EVT VT = N->getValueType(0); 10206 if (VT != MVT::i32 && VT != MVT::i64) 10207 return SDValue(); 10208 10209 unsigned Opc = N->getOpcode(); 10210 SDValue Op0 = N->getOperand(0); 10211 SDValue Op1 = N->getOperand(1); 10212 10213 if (!(Op0->isDivergent() ^ Op1->isDivergent())) 10214 return SDValue(); 10215 10216 if (Op0->isDivergent()) 10217 std::swap(Op0, Op1); 10218 10219 if (Op1.getOpcode() != Opc || !Op1.hasOneUse()) 10220 return SDValue(); 10221 10222 SDValue Op2 = Op1.getOperand(1); 10223 Op1 = Op1.getOperand(0); 10224 if (!(Op1->isDivergent() ^ Op2->isDivergent())) 10225 return SDValue(); 10226 10227 if (Op1->isDivergent()) 10228 std::swap(Op1, Op2); 10229 10230 // If either operand is constant this will conflict with 10231 // DAGCombiner::ReassociateOps(). 10232 if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) || 10233 DAG.isConstantIntBuildVectorOrConstantInt(Op1)) 10234 return SDValue(); 10235 10236 SDLoc SL(N); 10237 SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1); 10238 return DAG.getNode(Opc, SL, VT, Add1, Op2); 10239 } 10240 10241 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL, 10242 EVT VT, 10243 SDValue N0, SDValue N1, SDValue N2, 10244 bool Signed) { 10245 unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32; 10246 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1); 10247 SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2); 10248 return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad); 10249 } 10250 10251 SDValue SITargetLowering::performAddCombine(SDNode *N, 10252 DAGCombinerInfo &DCI) const { 10253 SelectionDAG &DAG = DCI.DAG; 10254 EVT VT = N->getValueType(0); 10255 SDLoc SL(N); 10256 SDValue LHS = N->getOperand(0); 10257 SDValue RHS = N->getOperand(1); 10258 10259 if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL) 10260 && Subtarget->hasMad64_32() && 10261 !VT.isVector() && VT.getScalarSizeInBits() > 32 && 10262 VT.getScalarSizeInBits() <= 64) { 10263 if (LHS.getOpcode() != ISD::MUL) 10264 std::swap(LHS, RHS); 10265 10266 SDValue MulLHS = LHS.getOperand(0); 10267 SDValue MulRHS = LHS.getOperand(1); 10268 SDValue AddRHS = RHS; 10269 10270 // TODO: Maybe restrict if SGPR inputs. 10271 if (numBitsUnsigned(MulLHS, DAG) <= 32 && 10272 numBitsUnsigned(MulRHS, DAG) <= 32) { 10273 MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32); 10274 MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32); 10275 AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64); 10276 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false); 10277 } 10278 10279 if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) { 10280 MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32); 10281 MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32); 10282 AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64); 10283 return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true); 10284 } 10285 10286 return SDValue(); 10287 } 10288 10289 if (SDValue V = reassociateScalarOps(N, DAG)) { 10290 return V; 10291 } 10292 10293 if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG()) 10294 return SDValue(); 10295 10296 // add x, zext (setcc) => addcarry x, 0, setcc 10297 // add x, sext (setcc) => subcarry x, 0, setcc 10298 unsigned Opc = LHS.getOpcode(); 10299 if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND || 10300 Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY) 10301 std::swap(RHS, LHS); 10302 10303 Opc = RHS.getOpcode(); 10304 switch (Opc) { 10305 default: break; 10306 case ISD::ZERO_EXTEND: 10307 case ISD::SIGN_EXTEND: 10308 case ISD::ANY_EXTEND: { 10309 auto Cond = RHS.getOperand(0); 10310 // If this won't be a real VOPC output, we would still need to insert an 10311 // extra instruction anyway. 10312 if (!isBoolSGPR(Cond)) 10313 break; 10314 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10315 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10316 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY; 10317 return DAG.getNode(Opc, SL, VTList, Args); 10318 } 10319 case ISD::ADDCARRY: { 10320 // add x, (addcarry y, 0, cc) => addcarry x, y, cc 10321 auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1)); 10322 if (!C || C->getZExtValue() != 0) break; 10323 SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) }; 10324 return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args); 10325 } 10326 } 10327 return SDValue(); 10328 } 10329 10330 SDValue SITargetLowering::performSubCombine(SDNode *N, 10331 DAGCombinerInfo &DCI) const { 10332 SelectionDAG &DAG = DCI.DAG; 10333 EVT VT = N->getValueType(0); 10334 10335 if (VT != MVT::i32) 10336 return SDValue(); 10337 10338 SDLoc SL(N); 10339 SDValue LHS = N->getOperand(0); 10340 SDValue RHS = N->getOperand(1); 10341 10342 // sub x, zext (setcc) => subcarry x, 0, setcc 10343 // sub x, sext (setcc) => addcarry x, 0, setcc 10344 unsigned Opc = RHS.getOpcode(); 10345 switch (Opc) { 10346 default: break; 10347 case ISD::ZERO_EXTEND: 10348 case ISD::SIGN_EXTEND: 10349 case ISD::ANY_EXTEND: { 10350 auto Cond = RHS.getOperand(0); 10351 // If this won't be a real VOPC output, we would still need to insert an 10352 // extra instruction anyway. 10353 if (!isBoolSGPR(Cond)) 10354 break; 10355 SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1); 10356 SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond }; 10357 Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY; 10358 return DAG.getNode(Opc, SL, VTList, Args); 10359 } 10360 } 10361 10362 if (LHS.getOpcode() == ISD::SUBCARRY) { 10363 // sub (subcarry x, 0, cc), y => subcarry x, y, cc 10364 auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1)); 10365 if (!C || !C->isNullValue()) 10366 return SDValue(); 10367 SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) }; 10368 return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args); 10369 } 10370 return SDValue(); 10371 } 10372 10373 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N, 10374 DAGCombinerInfo &DCI) const { 10375 10376 if (N->getValueType(0) != MVT::i32) 10377 return SDValue(); 10378 10379 auto C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 10380 if (!C || C->getZExtValue() != 0) 10381 return SDValue(); 10382 10383 SelectionDAG &DAG = DCI.DAG; 10384 SDValue LHS = N->getOperand(0); 10385 10386 // addcarry (add x, y), 0, cc => addcarry x, y, cc 10387 // subcarry (sub x, y), 0, cc => subcarry x, y, cc 10388 unsigned LHSOpc = LHS.getOpcode(); 10389 unsigned Opc = N->getOpcode(); 10390 if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) || 10391 (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) { 10392 SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) }; 10393 return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args); 10394 } 10395 return SDValue(); 10396 } 10397 10398 SDValue SITargetLowering::performFAddCombine(SDNode *N, 10399 DAGCombinerInfo &DCI) const { 10400 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10401 return SDValue(); 10402 10403 SelectionDAG &DAG = DCI.DAG; 10404 EVT VT = N->getValueType(0); 10405 10406 SDLoc SL(N); 10407 SDValue LHS = N->getOperand(0); 10408 SDValue RHS = N->getOperand(1); 10409 10410 // These should really be instruction patterns, but writing patterns with 10411 // source modiifiers is a pain. 10412 10413 // fadd (fadd (a, a), b) -> mad 2.0, a, b 10414 if (LHS.getOpcode() == ISD::FADD) { 10415 SDValue A = LHS.getOperand(0); 10416 if (A == LHS.getOperand(1)) { 10417 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10418 if (FusedOp != 0) { 10419 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10420 return DAG.getNode(FusedOp, SL, VT, A, Two, RHS); 10421 } 10422 } 10423 } 10424 10425 // fadd (b, fadd (a, a)) -> mad 2.0, a, b 10426 if (RHS.getOpcode() == ISD::FADD) { 10427 SDValue A = RHS.getOperand(0); 10428 if (A == RHS.getOperand(1)) { 10429 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10430 if (FusedOp != 0) { 10431 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10432 return DAG.getNode(FusedOp, SL, VT, A, Two, LHS); 10433 } 10434 } 10435 } 10436 10437 return SDValue(); 10438 } 10439 10440 SDValue SITargetLowering::performFSubCombine(SDNode *N, 10441 DAGCombinerInfo &DCI) const { 10442 if (DCI.getDAGCombineLevel() < AfterLegalizeDAG) 10443 return SDValue(); 10444 10445 SelectionDAG &DAG = DCI.DAG; 10446 SDLoc SL(N); 10447 EVT VT = N->getValueType(0); 10448 assert(!VT.isVector()); 10449 10450 // Try to get the fneg to fold into the source modifier. This undoes generic 10451 // DAG combines and folds them into the mad. 10452 // 10453 // Only do this if we are not trying to support denormals. v_mad_f32 does 10454 // not support denormals ever. 10455 SDValue LHS = N->getOperand(0); 10456 SDValue RHS = N->getOperand(1); 10457 if (LHS.getOpcode() == ISD::FADD) { 10458 // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c) 10459 SDValue A = LHS.getOperand(0); 10460 if (A == LHS.getOperand(1)) { 10461 unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode()); 10462 if (FusedOp != 0){ 10463 const SDValue Two = DAG.getConstantFP(2.0, SL, VT); 10464 SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS); 10465 10466 return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS); 10467 } 10468 } 10469 } 10470 10471 if (RHS.getOpcode() == ISD::FADD) { 10472 // (fsub c, (fadd a, a)) -> mad -2.0, a, c 10473 10474 SDValue A = RHS.getOperand(0); 10475 if (A == RHS.getOperand(1)) { 10476 unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode()); 10477 if (FusedOp != 0){ 10478 const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT); 10479 return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS); 10480 } 10481 } 10482 } 10483 10484 return SDValue(); 10485 } 10486 10487 SDValue SITargetLowering::performFMACombine(SDNode *N, 10488 DAGCombinerInfo &DCI) const { 10489 SelectionDAG &DAG = DCI.DAG; 10490 EVT VT = N->getValueType(0); 10491 SDLoc SL(N); 10492 10493 if (!Subtarget->hasDot7Insts() || VT != MVT::f32) 10494 return SDValue(); 10495 10496 // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) -> 10497 // FDOT2((V2F16)S0, (V2F16)S1, (F32)z)) 10498 SDValue Op1 = N->getOperand(0); 10499 SDValue Op2 = N->getOperand(1); 10500 SDValue FMA = N->getOperand(2); 10501 10502 if (FMA.getOpcode() != ISD::FMA || 10503 Op1.getOpcode() != ISD::FP_EXTEND || 10504 Op2.getOpcode() != ISD::FP_EXTEND) 10505 return SDValue(); 10506 10507 // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero, 10508 // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract 10509 // is sufficient to allow generaing fdot2. 10510 const TargetOptions &Options = DAG.getTarget().Options; 10511 if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath || 10512 (N->getFlags().hasAllowContract() && 10513 FMA->getFlags().hasAllowContract())) { 10514 Op1 = Op1.getOperand(0); 10515 Op2 = Op2.getOperand(0); 10516 if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10517 Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10518 return SDValue(); 10519 10520 SDValue Vec1 = Op1.getOperand(0); 10521 SDValue Idx1 = Op1.getOperand(1); 10522 SDValue Vec2 = Op2.getOperand(0); 10523 10524 SDValue FMAOp1 = FMA.getOperand(0); 10525 SDValue FMAOp2 = FMA.getOperand(1); 10526 SDValue FMAAcc = FMA.getOperand(2); 10527 10528 if (FMAOp1.getOpcode() != ISD::FP_EXTEND || 10529 FMAOp2.getOpcode() != ISD::FP_EXTEND) 10530 return SDValue(); 10531 10532 FMAOp1 = FMAOp1.getOperand(0); 10533 FMAOp2 = FMAOp2.getOperand(0); 10534 if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 10535 FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 10536 return SDValue(); 10537 10538 SDValue Vec3 = FMAOp1.getOperand(0); 10539 SDValue Vec4 = FMAOp2.getOperand(0); 10540 SDValue Idx2 = FMAOp1.getOperand(1); 10541 10542 if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) || 10543 // Idx1 and Idx2 cannot be the same. 10544 Idx1 == Idx2) 10545 return SDValue(); 10546 10547 if (Vec1 == Vec2 || Vec3 == Vec4) 10548 return SDValue(); 10549 10550 if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16) 10551 return SDValue(); 10552 10553 if ((Vec1 == Vec3 && Vec2 == Vec4) || 10554 (Vec1 == Vec4 && Vec2 == Vec3)) { 10555 return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc, 10556 DAG.getTargetConstant(0, SL, MVT::i1)); 10557 } 10558 } 10559 return SDValue(); 10560 } 10561 10562 SDValue SITargetLowering::performSetCCCombine(SDNode *N, 10563 DAGCombinerInfo &DCI) const { 10564 SelectionDAG &DAG = DCI.DAG; 10565 SDLoc SL(N); 10566 10567 SDValue LHS = N->getOperand(0); 10568 SDValue RHS = N->getOperand(1); 10569 EVT VT = LHS.getValueType(); 10570 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 10571 10572 auto CRHS = dyn_cast<ConstantSDNode>(RHS); 10573 if (!CRHS) { 10574 CRHS = dyn_cast<ConstantSDNode>(LHS); 10575 if (CRHS) { 10576 std::swap(LHS, RHS); 10577 CC = getSetCCSwappedOperands(CC); 10578 } 10579 } 10580 10581 if (CRHS) { 10582 if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND && 10583 isBoolSGPR(LHS.getOperand(0))) { 10584 // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1 10585 // setcc (sext from i1 cc), -1, eq|sle|uge) => cc 10586 // setcc (sext from i1 cc), 0, eq|sge|ule) => not cc => xor cc, -1 10587 // setcc (sext from i1 cc), 0, ne|ugt|slt) => cc 10588 if ((CRHS->isAllOnesValue() && 10589 (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) || 10590 (CRHS->isNullValue() && 10591 (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE))) 10592 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10593 DAG.getConstant(-1, SL, MVT::i1)); 10594 if ((CRHS->isAllOnesValue() && 10595 (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) || 10596 (CRHS->isNullValue() && 10597 (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT))) 10598 return LHS.getOperand(0); 10599 } 10600 10601 uint64_t CRHSVal = CRHS->getZExtValue(); 10602 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && 10603 LHS.getOpcode() == ISD::SELECT && 10604 isa<ConstantSDNode>(LHS.getOperand(1)) && 10605 isa<ConstantSDNode>(LHS.getOperand(2)) && 10606 LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) && 10607 isBoolSGPR(LHS.getOperand(0))) { 10608 // Given CT != FT: 10609 // setcc (select cc, CT, CF), CF, eq => xor cc, -1 10610 // setcc (select cc, CT, CF), CF, ne => cc 10611 // setcc (select cc, CT, CF), CT, ne => xor cc, -1 10612 // setcc (select cc, CT, CF), CT, eq => cc 10613 uint64_t CT = LHS.getConstantOperandVal(1); 10614 uint64_t CF = LHS.getConstantOperandVal(2); 10615 10616 if ((CF == CRHSVal && CC == ISD::SETEQ) || 10617 (CT == CRHSVal && CC == ISD::SETNE)) 10618 return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0), 10619 DAG.getConstant(-1, SL, MVT::i1)); 10620 if ((CF == CRHSVal && CC == ISD::SETNE) || 10621 (CT == CRHSVal && CC == ISD::SETEQ)) 10622 return LHS.getOperand(0); 10623 } 10624 } 10625 10626 if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() && 10627 VT != MVT::f16)) 10628 return SDValue(); 10629 10630 // Match isinf/isfinite pattern 10631 // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity)) 10632 // (fcmp one (fabs x), inf) -> (fp_class x, 10633 // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero) 10634 if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) { 10635 const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS); 10636 if (!CRHS) 10637 return SDValue(); 10638 10639 const APFloat &APF = CRHS->getValueAPF(); 10640 if (APF.isInfinity() && !APF.isNegative()) { 10641 const unsigned IsInfMask = SIInstrFlags::P_INFINITY | 10642 SIInstrFlags::N_INFINITY; 10643 const unsigned IsFiniteMask = SIInstrFlags::N_ZERO | 10644 SIInstrFlags::P_ZERO | 10645 SIInstrFlags::N_NORMAL | 10646 SIInstrFlags::P_NORMAL | 10647 SIInstrFlags::N_SUBNORMAL | 10648 SIInstrFlags::P_SUBNORMAL; 10649 unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask; 10650 return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0), 10651 DAG.getConstant(Mask, SL, MVT::i32)); 10652 } 10653 } 10654 10655 return SDValue(); 10656 } 10657 10658 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N, 10659 DAGCombinerInfo &DCI) const { 10660 SelectionDAG &DAG = DCI.DAG; 10661 SDLoc SL(N); 10662 unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0; 10663 10664 SDValue Src = N->getOperand(0); 10665 SDValue Shift = N->getOperand(0); 10666 10667 // TODO: Extend type shouldn't matter (assuming legal types). 10668 if (Shift.getOpcode() == ISD::ZERO_EXTEND) 10669 Shift = Shift.getOperand(0); 10670 10671 if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) { 10672 // cvt_f32_ubyte1 (shl x, 8) -> cvt_f32_ubyte0 x 10673 // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x 10674 // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x 10675 // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x 10676 // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x 10677 if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) { 10678 Shift = DAG.getZExtOrTrunc(Shift.getOperand(0), 10679 SDLoc(Shift.getOperand(0)), MVT::i32); 10680 10681 unsigned ShiftOffset = 8 * Offset; 10682 if (Shift.getOpcode() == ISD::SHL) 10683 ShiftOffset -= C->getZExtValue(); 10684 else 10685 ShiftOffset += C->getZExtValue(); 10686 10687 if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) { 10688 return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL, 10689 MVT::f32, Shift); 10690 } 10691 } 10692 } 10693 10694 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10695 APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8); 10696 if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) { 10697 // We simplified Src. If this node is not dead, visit it again so it is 10698 // folded properly. 10699 if (N->getOpcode() != ISD::DELETED_NODE) 10700 DCI.AddToWorklist(N); 10701 return SDValue(N, 0); 10702 } 10703 10704 // Handle (or x, (srl y, 8)) pattern when known bits are zero. 10705 if (SDValue DemandedSrc = 10706 TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG)) 10707 return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc); 10708 10709 return SDValue(); 10710 } 10711 10712 SDValue SITargetLowering::performClampCombine(SDNode *N, 10713 DAGCombinerInfo &DCI) const { 10714 ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0)); 10715 if (!CSrc) 10716 return SDValue(); 10717 10718 const MachineFunction &MF = DCI.DAG.getMachineFunction(); 10719 const APFloat &F = CSrc->getValueAPF(); 10720 APFloat Zero = APFloat::getZero(F.getSemantics()); 10721 if (F < Zero || 10722 (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) { 10723 return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0)); 10724 } 10725 10726 APFloat One(F.getSemantics(), "1.0"); 10727 if (F > One) 10728 return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0)); 10729 10730 return SDValue(CSrc, 0); 10731 } 10732 10733 10734 SDValue SITargetLowering::PerformDAGCombine(SDNode *N, 10735 DAGCombinerInfo &DCI) const { 10736 if (getTargetMachine().getOptLevel() == CodeGenOpt::None) 10737 return SDValue(); 10738 switch (N->getOpcode()) { 10739 case ISD::ADD: 10740 return performAddCombine(N, DCI); 10741 case ISD::SUB: 10742 return performSubCombine(N, DCI); 10743 case ISD::ADDCARRY: 10744 case ISD::SUBCARRY: 10745 return performAddCarrySubCarryCombine(N, DCI); 10746 case ISD::FADD: 10747 return performFAddCombine(N, DCI); 10748 case ISD::FSUB: 10749 return performFSubCombine(N, DCI); 10750 case ISD::SETCC: 10751 return performSetCCCombine(N, DCI); 10752 case ISD::FMAXNUM: 10753 case ISD::FMINNUM: 10754 case ISD::FMAXNUM_IEEE: 10755 case ISD::FMINNUM_IEEE: 10756 case ISD::SMAX: 10757 case ISD::SMIN: 10758 case ISD::UMAX: 10759 case ISD::UMIN: 10760 case AMDGPUISD::FMIN_LEGACY: 10761 case AMDGPUISD::FMAX_LEGACY: 10762 return performMinMaxCombine(N, DCI); 10763 case ISD::FMA: 10764 return performFMACombine(N, DCI); 10765 case ISD::AND: 10766 return performAndCombine(N, DCI); 10767 case ISD::OR: 10768 return performOrCombine(N, DCI); 10769 case ISD::XOR: 10770 return performXorCombine(N, DCI); 10771 case ISD::ZERO_EXTEND: 10772 return performZeroExtendCombine(N, DCI); 10773 case ISD::SIGN_EXTEND_INREG: 10774 return performSignExtendInRegCombine(N , DCI); 10775 case AMDGPUISD::FP_CLASS: 10776 return performClassCombine(N, DCI); 10777 case ISD::FCANONICALIZE: 10778 return performFCanonicalizeCombine(N, DCI); 10779 case AMDGPUISD::RCP: 10780 return performRcpCombine(N, DCI); 10781 case AMDGPUISD::FRACT: 10782 case AMDGPUISD::RSQ: 10783 case AMDGPUISD::RCP_LEGACY: 10784 case AMDGPUISD::RCP_IFLAG: 10785 case AMDGPUISD::RSQ_CLAMP: 10786 case AMDGPUISD::LDEXP: { 10787 // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted 10788 SDValue Src = N->getOperand(0); 10789 if (Src.isUndef()) 10790 return Src; 10791 break; 10792 } 10793 case ISD::SINT_TO_FP: 10794 case ISD::UINT_TO_FP: 10795 return performUCharToFloatCombine(N, DCI); 10796 case AMDGPUISD::CVT_F32_UBYTE0: 10797 case AMDGPUISD::CVT_F32_UBYTE1: 10798 case AMDGPUISD::CVT_F32_UBYTE2: 10799 case AMDGPUISD::CVT_F32_UBYTE3: 10800 return performCvtF32UByteNCombine(N, DCI); 10801 case AMDGPUISD::FMED3: 10802 return performFMed3Combine(N, DCI); 10803 case AMDGPUISD::CVT_PKRTZ_F16_F32: 10804 return performCvtPkRTZCombine(N, DCI); 10805 case AMDGPUISD::CLAMP: 10806 return performClampCombine(N, DCI); 10807 case ISD::SCALAR_TO_VECTOR: { 10808 SelectionDAG &DAG = DCI.DAG; 10809 EVT VT = N->getValueType(0); 10810 10811 // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x)) 10812 if (VT == MVT::v2i16 || VT == MVT::v2f16) { 10813 SDLoc SL(N); 10814 SDValue Src = N->getOperand(0); 10815 EVT EltVT = Src.getValueType(); 10816 if (EltVT == MVT::f16) 10817 Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src); 10818 10819 SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src); 10820 return DAG.getNode(ISD::BITCAST, SL, VT, Ext); 10821 } 10822 10823 break; 10824 } 10825 case ISD::EXTRACT_VECTOR_ELT: 10826 return performExtractVectorEltCombine(N, DCI); 10827 case ISD::INSERT_VECTOR_ELT: 10828 return performInsertVectorEltCombine(N, DCI); 10829 case ISD::LOAD: { 10830 if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI)) 10831 return Widended; 10832 LLVM_FALLTHROUGH; 10833 } 10834 default: { 10835 if (!DCI.isBeforeLegalize()) { 10836 if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N)) 10837 return performMemSDNodeCombine(MemNode, DCI); 10838 } 10839 10840 break; 10841 } 10842 } 10843 10844 return AMDGPUTargetLowering::PerformDAGCombine(N, DCI); 10845 } 10846 10847 /// Helper function for adjustWritemask 10848 static unsigned SubIdx2Lane(unsigned Idx) { 10849 switch (Idx) { 10850 default: return ~0u; 10851 case AMDGPU::sub0: return 0; 10852 case AMDGPU::sub1: return 1; 10853 case AMDGPU::sub2: return 2; 10854 case AMDGPU::sub3: return 3; 10855 case AMDGPU::sub4: return 4; // Possible with TFE/LWE 10856 } 10857 } 10858 10859 /// Adjust the writemask of MIMG instructions 10860 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node, 10861 SelectionDAG &DAG) const { 10862 unsigned Opcode = Node->getMachineOpcode(); 10863 10864 // Subtract 1 because the vdata output is not a MachineSDNode operand. 10865 int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1; 10866 if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx)) 10867 return Node; // not implemented for D16 10868 10869 SDNode *Users[5] = { nullptr }; 10870 unsigned Lane = 0; 10871 unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1; 10872 unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx); 10873 unsigned NewDmask = 0; 10874 unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1; 10875 unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1; 10876 bool UsesTFC = ((int(TFEIdx) >= 0 && Node->getConstantOperandVal(TFEIdx)) || 10877 Node->getConstantOperandVal(LWEIdx)) ? 1 : 0; 10878 unsigned TFCLane = 0; 10879 bool HasChain = Node->getNumValues() > 1; 10880 10881 if (OldDmask == 0) { 10882 // These are folded out, but on the chance it happens don't assert. 10883 return Node; 10884 } 10885 10886 unsigned OldBitsSet = countPopulation(OldDmask); 10887 // Work out which is the TFE/LWE lane if that is enabled. 10888 if (UsesTFC) { 10889 TFCLane = OldBitsSet; 10890 } 10891 10892 // Try to figure out the used register components 10893 for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end(); 10894 I != E; ++I) { 10895 10896 // Don't look at users of the chain. 10897 if (I.getUse().getResNo() != 0) 10898 continue; 10899 10900 // Abort if we can't understand the usage 10901 if (!I->isMachineOpcode() || 10902 I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG) 10903 return Node; 10904 10905 // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used. 10906 // Note that subregs are packed, i.e. Lane==0 is the first bit set 10907 // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit 10908 // set, etc. 10909 Lane = SubIdx2Lane(I->getConstantOperandVal(1)); 10910 if (Lane == ~0u) 10911 return Node; 10912 10913 // Check if the use is for the TFE/LWE generated result at VGPRn+1. 10914 if (UsesTFC && Lane == TFCLane) { 10915 Users[Lane] = *I; 10916 } else { 10917 // Set which texture component corresponds to the lane. 10918 unsigned Comp; 10919 for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) { 10920 Comp = countTrailingZeros(Dmask); 10921 Dmask &= ~(1 << Comp); 10922 } 10923 10924 // Abort if we have more than one user per component. 10925 if (Users[Lane]) 10926 return Node; 10927 10928 Users[Lane] = *I; 10929 NewDmask |= 1 << Comp; 10930 } 10931 } 10932 10933 // Don't allow 0 dmask, as hardware assumes one channel enabled. 10934 bool NoChannels = !NewDmask; 10935 if (NoChannels) { 10936 if (!UsesTFC) { 10937 // No uses of the result and not using TFC. Then do nothing. 10938 return Node; 10939 } 10940 // If the original dmask has one channel - then nothing to do 10941 if (OldBitsSet == 1) 10942 return Node; 10943 // Use an arbitrary dmask - required for the instruction to work 10944 NewDmask = 1; 10945 } 10946 // Abort if there's no change 10947 if (NewDmask == OldDmask) 10948 return Node; 10949 10950 unsigned BitsSet = countPopulation(NewDmask); 10951 10952 // Check for TFE or LWE - increase the number of channels by one to account 10953 // for the extra return value 10954 // This will need adjustment for D16 if this is also included in 10955 // adjustWriteMask (this function) but at present D16 are excluded. 10956 unsigned NewChannels = BitsSet + UsesTFC; 10957 10958 int NewOpcode = 10959 AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels); 10960 assert(NewOpcode != -1 && 10961 NewOpcode != static_cast<int>(Node->getMachineOpcode()) && 10962 "failed to find equivalent MIMG op"); 10963 10964 // Adjust the writemask in the node 10965 SmallVector<SDValue, 12> Ops; 10966 Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx); 10967 Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32)); 10968 Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end()); 10969 10970 MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT(); 10971 10972 MVT ResultVT = NewChannels == 1 ? 10973 SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 : 10974 NewChannels == 5 ? 8 : NewChannels); 10975 SDVTList NewVTList = HasChain ? 10976 DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT); 10977 10978 10979 MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node), 10980 NewVTList, Ops); 10981 10982 if (HasChain) { 10983 // Update chain. 10984 DAG.setNodeMemRefs(NewNode, Node->memoperands()); 10985 DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1)); 10986 } 10987 10988 if (NewChannels == 1) { 10989 assert(Node->hasNUsesOfValue(1, 0)); 10990 SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY, 10991 SDLoc(Node), Users[Lane]->getValueType(0), 10992 SDValue(NewNode, 0)); 10993 DAG.ReplaceAllUsesWith(Users[Lane], Copy); 10994 return nullptr; 10995 } 10996 10997 // Update the users of the node with the new indices 10998 for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) { 10999 SDNode *User = Users[i]; 11000 if (!User) { 11001 // Handle the special case of NoChannels. We set NewDmask to 1 above, but 11002 // Users[0] is still nullptr because channel 0 doesn't really have a use. 11003 if (i || !NoChannels) 11004 continue; 11005 } else { 11006 SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32); 11007 DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op); 11008 } 11009 11010 switch (Idx) { 11011 default: break; 11012 case AMDGPU::sub0: Idx = AMDGPU::sub1; break; 11013 case AMDGPU::sub1: Idx = AMDGPU::sub2; break; 11014 case AMDGPU::sub2: Idx = AMDGPU::sub3; break; 11015 case AMDGPU::sub3: Idx = AMDGPU::sub4; break; 11016 } 11017 } 11018 11019 DAG.RemoveDeadNode(Node); 11020 return nullptr; 11021 } 11022 11023 static bool isFrameIndexOp(SDValue Op) { 11024 if (Op.getOpcode() == ISD::AssertZext) 11025 Op = Op.getOperand(0); 11026 11027 return isa<FrameIndexSDNode>(Op); 11028 } 11029 11030 /// Legalize target independent instructions (e.g. INSERT_SUBREG) 11031 /// with frame index operands. 11032 /// LLVM assumes that inputs are to these instructions are registers. 11033 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node, 11034 SelectionDAG &DAG) const { 11035 if (Node->getOpcode() == ISD::CopyToReg) { 11036 RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1)); 11037 SDValue SrcVal = Node->getOperand(2); 11038 11039 // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have 11040 // to try understanding copies to physical registers. 11041 if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) { 11042 SDLoc SL(Node); 11043 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11044 SDValue VReg = DAG.getRegister( 11045 MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1); 11046 11047 SDNode *Glued = Node->getGluedNode(); 11048 SDValue ToVReg 11049 = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal, 11050 SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0)); 11051 SDValue ToResultReg 11052 = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0), 11053 VReg, ToVReg.getValue(1)); 11054 DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode()); 11055 DAG.RemoveDeadNode(Node); 11056 return ToResultReg.getNode(); 11057 } 11058 } 11059 11060 SmallVector<SDValue, 8> Ops; 11061 for (unsigned i = 0; i < Node->getNumOperands(); ++i) { 11062 if (!isFrameIndexOp(Node->getOperand(i))) { 11063 Ops.push_back(Node->getOperand(i)); 11064 continue; 11065 } 11066 11067 SDLoc DL(Node); 11068 Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, 11069 Node->getOperand(i).getValueType(), 11070 Node->getOperand(i)), 0)); 11071 } 11072 11073 return DAG.UpdateNodeOperands(Node, Ops); 11074 } 11075 11076 /// Fold the instructions after selecting them. 11077 /// Returns null if users were already updated. 11078 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node, 11079 SelectionDAG &DAG) const { 11080 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11081 unsigned Opcode = Node->getMachineOpcode(); 11082 11083 if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() && 11084 !TII->isGather4(Opcode) && 11085 AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) { 11086 return adjustWritemask(Node, DAG); 11087 } 11088 11089 if (Opcode == AMDGPU::INSERT_SUBREG || 11090 Opcode == AMDGPU::REG_SEQUENCE) { 11091 legalizeTargetIndependentNode(Node, DAG); 11092 return Node; 11093 } 11094 11095 switch (Opcode) { 11096 case AMDGPU::V_DIV_SCALE_F32_e64: 11097 case AMDGPU::V_DIV_SCALE_F64_e64: { 11098 // Satisfy the operand register constraint when one of the inputs is 11099 // undefined. Ordinarily each undef value will have its own implicit_def of 11100 // a vreg, so force these to use a single register. 11101 SDValue Src0 = Node->getOperand(1); 11102 SDValue Src1 = Node->getOperand(3); 11103 SDValue Src2 = Node->getOperand(5); 11104 11105 if ((Src0.isMachineOpcode() && 11106 Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) && 11107 (Src0 == Src1 || Src0 == Src2)) 11108 break; 11109 11110 MVT VT = Src0.getValueType().getSimpleVT(); 11111 const TargetRegisterClass *RC = 11112 getRegClassFor(VT, Src0.getNode()->isDivergent()); 11113 11114 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo(); 11115 SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT); 11116 11117 SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node), 11118 UndefReg, Src0, SDValue()); 11119 11120 // src0 must be the same register as src1 or src2, even if the value is 11121 // undefined, so make sure we don't violate this constraint. 11122 if (Src0.isMachineOpcode() && 11123 Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) { 11124 if (Src1.isMachineOpcode() && 11125 Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11126 Src0 = Src1; 11127 else if (Src2.isMachineOpcode() && 11128 Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) 11129 Src0 = Src2; 11130 else { 11131 assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF); 11132 Src0 = UndefReg; 11133 Src1 = UndefReg; 11134 } 11135 } else 11136 break; 11137 11138 SmallVector<SDValue, 9> Ops(Node->op_begin(), Node->op_end()); 11139 Ops[1] = Src0; 11140 Ops[3] = Src1; 11141 Ops[5] = Src2; 11142 Ops.push_back(ImpDef.getValue(1)); 11143 return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops); 11144 } 11145 default: 11146 break; 11147 } 11148 11149 return Node; 11150 } 11151 11152 /// Assign the register class depending on the number of 11153 /// bits set in the writemask 11154 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 11155 SDNode *Node) const { 11156 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11157 11158 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 11159 11160 if (TII->isVOP3(MI.getOpcode())) { 11161 // Make sure constant bus requirements are respected. 11162 TII->legalizeOperandsVOP3(MRI, MI); 11163 11164 // Prefer VGPRs over AGPRs in mAI instructions where possible. 11165 // This saves a chain-copy of registers and better ballance register 11166 // use between vgpr and agpr as agpr tuples tend to be big. 11167 if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) { 11168 unsigned Opc = MI.getOpcode(); 11169 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11170 for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0), 11171 AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) { 11172 if (I == -1) 11173 break; 11174 MachineOperand &Op = MI.getOperand(I); 11175 if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID && 11176 OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) || 11177 !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg())) 11178 continue; 11179 auto *Src = MRI.getUniqueVRegDef(Op.getReg()); 11180 if (!Src || !Src->isCopy() || 11181 !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg())) 11182 continue; 11183 auto *RC = TRI->getRegClassForReg(MRI, Op.getReg()); 11184 auto *NewRC = TRI->getEquivalentVGPRClass(RC); 11185 // All uses of agpr64 and agpr32 can also accept vgpr except for 11186 // v_accvgpr_read, but we do not produce agpr reads during selection, 11187 // so no use checks are needed. 11188 MRI.setRegClass(Op.getReg(), NewRC); 11189 } 11190 } 11191 11192 return; 11193 } 11194 11195 // Replace unused atomics with the no return version. 11196 int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode()); 11197 if (NoRetAtomicOp != -1) { 11198 if (!Node->hasAnyUseOfValue(0)) { 11199 int CPolIdx = AMDGPU::getNamedOperandIdx(MI.getOpcode(), 11200 AMDGPU::OpName::cpol); 11201 if (CPolIdx != -1) { 11202 MachineOperand &CPol = MI.getOperand(CPolIdx); 11203 CPol.setImm(CPol.getImm() & ~AMDGPU::CPol::GLC); 11204 } 11205 MI.RemoveOperand(0); 11206 MI.setDesc(TII->get(NoRetAtomicOp)); 11207 return; 11208 } 11209 11210 // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg 11211 // instruction, because the return type of these instructions is a vec2 of 11212 // the memory type, so it can be tied to the input operand. 11213 // This means these instructions always have a use, so we need to add a 11214 // special case to check if the atomic has only one extract_subreg use, 11215 // which itself has no uses. 11216 if ((Node->hasNUsesOfValue(1, 0) && 11217 Node->use_begin()->isMachineOpcode() && 11218 Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG && 11219 !Node->use_begin()->hasAnyUseOfValue(0))) { 11220 Register Def = MI.getOperand(0).getReg(); 11221 11222 // Change this into a noret atomic. 11223 MI.setDesc(TII->get(NoRetAtomicOp)); 11224 MI.RemoveOperand(0); 11225 11226 // If we only remove the def operand from the atomic instruction, the 11227 // extract_subreg will be left with a use of a vreg without a def. 11228 // So we need to insert an implicit_def to avoid machine verifier 11229 // errors. 11230 BuildMI(*MI.getParent(), MI, MI.getDebugLoc(), 11231 TII->get(AMDGPU::IMPLICIT_DEF), Def); 11232 } 11233 return; 11234 } 11235 } 11236 11237 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL, 11238 uint64_t Val) { 11239 SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32); 11240 return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0); 11241 } 11242 11243 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG, 11244 const SDLoc &DL, 11245 SDValue Ptr) const { 11246 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11247 11248 // Build the half of the subregister with the constants before building the 11249 // full 128-bit register. If we are building multiple resource descriptors, 11250 // this will allow CSEing of the 2-component register. 11251 const SDValue Ops0[] = { 11252 DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32), 11253 buildSMovImm32(DAG, DL, 0), 11254 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11255 buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32), 11256 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32) 11257 }; 11258 11259 SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, 11260 MVT::v2i32, Ops0), 0); 11261 11262 // Combine the constants and the pointer. 11263 const SDValue Ops1[] = { 11264 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11265 Ptr, 11266 DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32), 11267 SubRegHi, 11268 DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32) 11269 }; 11270 11271 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1); 11272 } 11273 11274 /// Return a resource descriptor with the 'Add TID' bit enabled 11275 /// The TID (Thread ID) is multiplied by the stride value (bits [61:48] 11276 /// of the resource descriptor) to create an offset, which is added to 11277 /// the resource pointer. 11278 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL, 11279 SDValue Ptr, uint32_t RsrcDword1, 11280 uint64_t RsrcDword2And3) const { 11281 SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr); 11282 SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr); 11283 if (RsrcDword1) { 11284 PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi, 11285 DAG.getConstant(RsrcDword1, DL, MVT::i32)), 11286 0); 11287 } 11288 11289 SDValue DataLo = buildSMovImm32(DAG, DL, 11290 RsrcDword2And3 & UINT64_C(0xFFFFFFFF)); 11291 SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32); 11292 11293 const SDValue Ops[] = { 11294 DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32), 11295 PtrLo, 11296 DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32), 11297 PtrHi, 11298 DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32), 11299 DataLo, 11300 DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32), 11301 DataHi, 11302 DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32) 11303 }; 11304 11305 return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops); 11306 } 11307 11308 //===----------------------------------------------------------------------===// 11309 // SI Inline Assembly Support 11310 //===----------------------------------------------------------------------===// 11311 11312 std::pair<unsigned, const TargetRegisterClass *> 11313 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI_, 11314 StringRef Constraint, 11315 MVT VT) const { 11316 const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(TRI_); 11317 11318 const TargetRegisterClass *RC = nullptr; 11319 if (Constraint.size() == 1) { 11320 const unsigned BitWidth = VT.getSizeInBits(); 11321 switch (Constraint[0]) { 11322 default: 11323 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11324 case 's': 11325 case 'r': 11326 switch (BitWidth) { 11327 case 16: 11328 RC = &AMDGPU::SReg_32RegClass; 11329 break; 11330 case 64: 11331 RC = &AMDGPU::SGPR_64RegClass; 11332 break; 11333 default: 11334 RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth); 11335 if (!RC) 11336 return std::make_pair(0U, nullptr); 11337 break; 11338 } 11339 break; 11340 case 'v': 11341 switch (BitWidth) { 11342 case 16: 11343 RC = &AMDGPU::VGPR_32RegClass; 11344 break; 11345 default: 11346 RC = TRI->getVGPRClassForBitWidth(BitWidth); 11347 if (!RC) 11348 return std::make_pair(0U, nullptr); 11349 break; 11350 } 11351 break; 11352 case 'a': 11353 if (!Subtarget->hasMAIInsts()) 11354 break; 11355 switch (BitWidth) { 11356 case 16: 11357 RC = &AMDGPU::AGPR_32RegClass; 11358 break; 11359 default: 11360 RC = TRI->getAGPRClassForBitWidth(BitWidth); 11361 if (!RC) 11362 return std::make_pair(0U, nullptr); 11363 break; 11364 } 11365 break; 11366 } 11367 // We actually support i128, i16 and f16 as inline parameters 11368 // even if they are not reported as legal 11369 if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 || 11370 VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16)) 11371 return std::make_pair(0U, RC); 11372 } 11373 11374 if (Constraint.size() > 1) { 11375 if (Constraint[1] == 'v') { 11376 RC = &AMDGPU::VGPR_32RegClass; 11377 } else if (Constraint[1] == 's') { 11378 RC = &AMDGPU::SGPR_32RegClass; 11379 } else if (Constraint[1] == 'a') { 11380 RC = &AMDGPU::AGPR_32RegClass; 11381 } 11382 11383 if (RC) { 11384 uint32_t Idx; 11385 bool Failed = Constraint.substr(2).getAsInteger(10, Idx); 11386 if (!Failed && Idx < RC->getNumRegs()) 11387 return std::make_pair(RC->getRegister(Idx), RC); 11388 } 11389 } 11390 11391 // FIXME: Returns VS_32 for physical SGPR constraints 11392 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11393 } 11394 11395 static bool isImmConstraint(StringRef Constraint) { 11396 if (Constraint.size() == 1) { 11397 switch (Constraint[0]) { 11398 default: break; 11399 case 'I': 11400 case 'J': 11401 case 'A': 11402 case 'B': 11403 case 'C': 11404 return true; 11405 } 11406 } else if (Constraint == "DA" || 11407 Constraint == "DB") { 11408 return true; 11409 } 11410 return false; 11411 } 11412 11413 SITargetLowering::ConstraintType 11414 SITargetLowering::getConstraintType(StringRef Constraint) const { 11415 if (Constraint.size() == 1) { 11416 switch (Constraint[0]) { 11417 default: break; 11418 case 's': 11419 case 'v': 11420 case 'a': 11421 return C_RegisterClass; 11422 } 11423 } 11424 if (isImmConstraint(Constraint)) { 11425 return C_Other; 11426 } 11427 return TargetLowering::getConstraintType(Constraint); 11428 } 11429 11430 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) { 11431 if (!AMDGPU::isInlinableIntLiteral(Val)) { 11432 Val = Val & maskTrailingOnes<uint64_t>(Size); 11433 } 11434 return Val; 11435 } 11436 11437 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op, 11438 std::string &Constraint, 11439 std::vector<SDValue> &Ops, 11440 SelectionDAG &DAG) const { 11441 if (isImmConstraint(Constraint)) { 11442 uint64_t Val; 11443 if (getAsmOperandConstVal(Op, Val) && 11444 checkAsmConstraintVal(Op, Constraint, Val)) { 11445 Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits()); 11446 Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64)); 11447 } 11448 } else { 11449 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11450 } 11451 } 11452 11453 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const { 11454 unsigned Size = Op.getScalarValueSizeInBits(); 11455 if (Size > 64) 11456 return false; 11457 11458 if (Size == 16 && !Subtarget->has16BitInsts()) 11459 return false; 11460 11461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) { 11462 Val = C->getSExtValue(); 11463 return true; 11464 } 11465 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) { 11466 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11467 return true; 11468 } 11469 if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) { 11470 if (Size != 16 || Op.getNumOperands() != 2) 11471 return false; 11472 if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef()) 11473 return false; 11474 if (ConstantSDNode *C = V->getConstantSplatNode()) { 11475 Val = C->getSExtValue(); 11476 return true; 11477 } 11478 if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) { 11479 Val = C->getValueAPF().bitcastToAPInt().getSExtValue(); 11480 return true; 11481 } 11482 } 11483 11484 return false; 11485 } 11486 11487 bool SITargetLowering::checkAsmConstraintVal(SDValue Op, 11488 const std::string &Constraint, 11489 uint64_t Val) const { 11490 if (Constraint.size() == 1) { 11491 switch (Constraint[0]) { 11492 case 'I': 11493 return AMDGPU::isInlinableIntLiteral(Val); 11494 case 'J': 11495 return isInt<16>(Val); 11496 case 'A': 11497 return checkAsmConstraintValA(Op, Val); 11498 case 'B': 11499 return isInt<32>(Val); 11500 case 'C': 11501 return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) || 11502 AMDGPU::isInlinableIntLiteral(Val); 11503 default: 11504 break; 11505 } 11506 } else if (Constraint.size() == 2) { 11507 if (Constraint == "DA") { 11508 int64_t HiBits = static_cast<int32_t>(Val >> 32); 11509 int64_t LoBits = static_cast<int32_t>(Val); 11510 return checkAsmConstraintValA(Op, HiBits, 32) && 11511 checkAsmConstraintValA(Op, LoBits, 32); 11512 } 11513 if (Constraint == "DB") { 11514 return true; 11515 } 11516 } 11517 llvm_unreachable("Invalid asm constraint"); 11518 } 11519 11520 bool SITargetLowering::checkAsmConstraintValA(SDValue Op, 11521 uint64_t Val, 11522 unsigned MaxSize) const { 11523 unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize); 11524 bool HasInv2Pi = Subtarget->hasInv2PiInlineImm(); 11525 if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) || 11526 (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) || 11527 (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) { 11528 return true; 11529 } 11530 return false; 11531 } 11532 11533 static int getAlignedAGPRClassID(unsigned UnalignedClassID) { 11534 switch (UnalignedClassID) { 11535 case AMDGPU::VReg_64RegClassID: 11536 return AMDGPU::VReg_64_Align2RegClassID; 11537 case AMDGPU::VReg_96RegClassID: 11538 return AMDGPU::VReg_96_Align2RegClassID; 11539 case AMDGPU::VReg_128RegClassID: 11540 return AMDGPU::VReg_128_Align2RegClassID; 11541 case AMDGPU::VReg_160RegClassID: 11542 return AMDGPU::VReg_160_Align2RegClassID; 11543 case AMDGPU::VReg_192RegClassID: 11544 return AMDGPU::VReg_192_Align2RegClassID; 11545 case AMDGPU::VReg_256RegClassID: 11546 return AMDGPU::VReg_256_Align2RegClassID; 11547 case AMDGPU::VReg_512RegClassID: 11548 return AMDGPU::VReg_512_Align2RegClassID; 11549 case AMDGPU::VReg_1024RegClassID: 11550 return AMDGPU::VReg_1024_Align2RegClassID; 11551 case AMDGPU::AReg_64RegClassID: 11552 return AMDGPU::AReg_64_Align2RegClassID; 11553 case AMDGPU::AReg_96RegClassID: 11554 return AMDGPU::AReg_96_Align2RegClassID; 11555 case AMDGPU::AReg_128RegClassID: 11556 return AMDGPU::AReg_128_Align2RegClassID; 11557 case AMDGPU::AReg_160RegClassID: 11558 return AMDGPU::AReg_160_Align2RegClassID; 11559 case AMDGPU::AReg_192RegClassID: 11560 return AMDGPU::AReg_192_Align2RegClassID; 11561 case AMDGPU::AReg_256RegClassID: 11562 return AMDGPU::AReg_256_Align2RegClassID; 11563 case AMDGPU::AReg_512RegClassID: 11564 return AMDGPU::AReg_512_Align2RegClassID; 11565 case AMDGPU::AReg_1024RegClassID: 11566 return AMDGPU::AReg_1024_Align2RegClassID; 11567 default: 11568 return -1; 11569 } 11570 } 11571 11572 // Figure out which registers should be reserved for stack access. Only after 11573 // the function is legalized do we know all of the non-spill stack objects or if 11574 // calls are present. 11575 void SITargetLowering::finalizeLowering(MachineFunction &MF) const { 11576 MachineRegisterInfo &MRI = MF.getRegInfo(); 11577 SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11578 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 11579 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11580 const SIInstrInfo *TII = ST.getInstrInfo(); 11581 11582 if (Info->isEntryFunction()) { 11583 // Callable functions have fixed registers used for stack access. 11584 reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info); 11585 } 11586 11587 assert(!TRI->isSubRegister(Info->getScratchRSrcReg(), 11588 Info->getStackPtrOffsetReg())); 11589 if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG) 11590 MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg()); 11591 11592 // We need to worry about replacing the default register with itself in case 11593 // of MIR testcases missing the MFI. 11594 if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG) 11595 MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg()); 11596 11597 if (Info->getFrameOffsetReg() != AMDGPU::FP_REG) 11598 MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg()); 11599 11600 Info->limitOccupancy(MF); 11601 11602 if (ST.isWave32() && !MF.empty()) { 11603 for (auto &MBB : MF) { 11604 for (auto &MI : MBB) { 11605 TII->fixImplicitOperands(MI); 11606 } 11607 } 11608 } 11609 11610 // FIXME: This is a hack to fixup AGPR classes to use the properly aligned 11611 // classes if required. Ideally the register class constraints would differ 11612 // per-subtarget, but there's no easy way to achieve that right now. This is 11613 // not a problem for VGPRs because the correctly aligned VGPR class is implied 11614 // from using them as the register class for legal types. 11615 if (ST.needsAlignedVGPRs()) { 11616 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 11617 const Register Reg = Register::index2VirtReg(I); 11618 const TargetRegisterClass *RC = MRI.getRegClassOrNull(Reg); 11619 if (!RC) 11620 continue; 11621 int NewClassID = getAlignedAGPRClassID(RC->getID()); 11622 if (NewClassID != -1) 11623 MRI.setRegClass(Reg, TRI->getRegClass(NewClassID)); 11624 } 11625 } 11626 11627 TargetLoweringBase::finalizeLowering(MF); 11628 11629 // Allocate a VGPR for future SGPR Spill if 11630 // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used 11631 // FIXME: We won't need this hack if we split SGPR allocation from VGPR 11632 if (VGPRReserveforSGPRSpill && TRI->spillSGPRToVGPR() && 11633 !Info->VGPRReservedForSGPRSpill && !Info->isEntryFunction()) 11634 Info->reserveVGPRforSGPRSpills(MF); 11635 } 11636 11637 void SITargetLowering::computeKnownBitsForFrameIndex( 11638 const int FI, KnownBits &Known, const MachineFunction &MF) const { 11639 TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF); 11640 11641 // Set the high bits to zero based on the maximum allowed scratch size per 11642 // wave. We can't use vaddr in MUBUF instructions if we don't know the address 11643 // calculation won't overflow, so assume the sign bit is never set. 11644 Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex()); 11645 } 11646 11647 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB, 11648 KnownBits &Known, unsigned Dim) { 11649 unsigned MaxValue = 11650 ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim); 11651 Known.Zero.setHighBits(countLeadingZeros(MaxValue)); 11652 } 11653 11654 void SITargetLowering::computeKnownBitsForTargetInstr( 11655 GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts, 11656 const MachineRegisterInfo &MRI, unsigned Depth) const { 11657 const MachineInstr *MI = MRI.getVRegDef(R); 11658 switch (MI->getOpcode()) { 11659 case AMDGPU::G_INTRINSIC: { 11660 switch (MI->getIntrinsicID()) { 11661 case Intrinsic::amdgcn_workitem_id_x: 11662 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0); 11663 break; 11664 case Intrinsic::amdgcn_workitem_id_y: 11665 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1); 11666 break; 11667 case Intrinsic::amdgcn_workitem_id_z: 11668 knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2); 11669 break; 11670 case Intrinsic::amdgcn_mbcnt_lo: 11671 case Intrinsic::amdgcn_mbcnt_hi: { 11672 // These return at most the wavefront size - 1. 11673 unsigned Size = MRI.getType(R).getSizeInBits(); 11674 Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2()); 11675 break; 11676 } 11677 case Intrinsic::amdgcn_groupstaticsize: { 11678 // We can report everything over the maximum size as 0. We can't report 11679 // based on the actual size because we don't know if it's accurate or not 11680 // at any given point. 11681 Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize())); 11682 break; 11683 } 11684 } 11685 break; 11686 } 11687 case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE: 11688 Known.Zero.setHighBits(24); 11689 break; 11690 case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT: 11691 Known.Zero.setHighBits(16); 11692 break; 11693 } 11694 } 11695 11696 Align SITargetLowering::computeKnownAlignForTargetInstr( 11697 GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI, 11698 unsigned Depth) const { 11699 const MachineInstr *MI = MRI.getVRegDef(R); 11700 switch (MI->getOpcode()) { 11701 case AMDGPU::G_INTRINSIC: 11702 case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: { 11703 // FIXME: Can this move to generic code? What about the case where the call 11704 // site specifies a lower alignment? 11705 Intrinsic::ID IID = MI->getIntrinsicID(); 11706 LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext(); 11707 AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID); 11708 if (MaybeAlign RetAlign = Attrs.getRetAlignment()) 11709 return *RetAlign; 11710 return Align(1); 11711 } 11712 default: 11713 return Align(1); 11714 } 11715 } 11716 11717 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const { 11718 const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML); 11719 const Align CacheLineAlign = Align(64); 11720 11721 // Pre-GFX10 target did not benefit from loop alignment 11722 if (!ML || DisableLoopAlignment || 11723 (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) || 11724 getSubtarget()->hasInstFwdPrefetchBug()) 11725 return PrefAlign; 11726 11727 // On GFX10 I$ is 4 x 64 bytes cache lines. 11728 // By default prefetcher keeps one cache line behind and reads two ahead. 11729 // We can modify it with S_INST_PREFETCH for larger loops to have two lines 11730 // behind and one ahead. 11731 // Therefor we can benefit from aligning loop headers if loop fits 192 bytes. 11732 // If loop fits 64 bytes it always spans no more than two cache lines and 11733 // does not need an alignment. 11734 // Else if loop is less or equal 128 bytes we do not need to modify prefetch, 11735 // Else if loop is less or equal 192 bytes we need two lines behind. 11736 11737 const SIInstrInfo *TII = getSubtarget()->getInstrInfo(); 11738 const MachineBasicBlock *Header = ML->getHeader(); 11739 if (Header->getAlignment() != PrefAlign) 11740 return Header->getAlignment(); // Already processed. 11741 11742 unsigned LoopSize = 0; 11743 for (const MachineBasicBlock *MBB : ML->blocks()) { 11744 // If inner loop block is aligned assume in average half of the alignment 11745 // size to be added as nops. 11746 if (MBB != Header) 11747 LoopSize += MBB->getAlignment().value() / 2; 11748 11749 for (const MachineInstr &MI : *MBB) { 11750 LoopSize += TII->getInstSizeInBytes(MI); 11751 if (LoopSize > 192) 11752 return PrefAlign; 11753 } 11754 } 11755 11756 if (LoopSize <= 64) 11757 return PrefAlign; 11758 11759 if (LoopSize <= 128) 11760 return CacheLineAlign; 11761 11762 // If any of parent loops is surrounded by prefetch instructions do not 11763 // insert new for inner loop, which would reset parent's settings. 11764 for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) { 11765 if (MachineBasicBlock *Exit = P->getExitBlock()) { 11766 auto I = Exit->getFirstNonDebugInstr(); 11767 if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH) 11768 return CacheLineAlign; 11769 } 11770 } 11771 11772 MachineBasicBlock *Pre = ML->getLoopPreheader(); 11773 MachineBasicBlock *Exit = ML->getExitBlock(); 11774 11775 if (Pre && Exit) { 11776 BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(), 11777 TII->get(AMDGPU::S_INST_PREFETCH)) 11778 .addImm(1); // prefetch 2 lines behind PC 11779 11780 BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(), 11781 TII->get(AMDGPU::S_INST_PREFETCH)) 11782 .addImm(2); // prefetch 1 line behind PC 11783 } 11784 11785 return CacheLineAlign; 11786 } 11787 11788 LLVM_ATTRIBUTE_UNUSED 11789 static bool isCopyFromRegOfInlineAsm(const SDNode *N) { 11790 assert(N->getOpcode() == ISD::CopyFromReg); 11791 do { 11792 // Follow the chain until we find an INLINEASM node. 11793 N = N->getOperand(0).getNode(); 11794 if (N->getOpcode() == ISD::INLINEASM || 11795 N->getOpcode() == ISD::INLINEASM_BR) 11796 return true; 11797 } while (N->getOpcode() == ISD::CopyFromReg); 11798 return false; 11799 } 11800 11801 bool SITargetLowering::isSDNodeSourceOfDivergence( 11802 const SDNode *N, FunctionLoweringInfo *FLI, 11803 LegacyDivergenceAnalysis *KDA) const { 11804 switch (N->getOpcode()) { 11805 case ISD::CopyFromReg: { 11806 const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1)); 11807 const MachineRegisterInfo &MRI = FLI->MF->getRegInfo(); 11808 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11809 Register Reg = R->getReg(); 11810 11811 // FIXME: Why does this need to consider isLiveIn? 11812 if (Reg.isPhysical() || MRI.isLiveIn(Reg)) 11813 return !TRI->isSGPRReg(MRI, Reg); 11814 11815 if (const Value *V = FLI->getValueFromVirtualReg(R->getReg())) 11816 return KDA->isDivergent(V); 11817 11818 assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N)); 11819 return !TRI->isSGPRReg(MRI, Reg); 11820 } 11821 case ISD::LOAD: { 11822 const LoadSDNode *L = cast<LoadSDNode>(N); 11823 unsigned AS = L->getAddressSpace(); 11824 // A flat load may access private memory. 11825 return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS; 11826 } 11827 case ISD::CALLSEQ_END: 11828 return true; 11829 case ISD::INTRINSIC_WO_CHAIN: 11830 return AMDGPU::isIntrinsicSourceOfDivergence( 11831 cast<ConstantSDNode>(N->getOperand(0))->getZExtValue()); 11832 case ISD::INTRINSIC_W_CHAIN: 11833 return AMDGPU::isIntrinsicSourceOfDivergence( 11834 cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()); 11835 case AMDGPUISD::ATOMIC_CMP_SWAP: 11836 case AMDGPUISD::ATOMIC_INC: 11837 case AMDGPUISD::ATOMIC_DEC: 11838 case AMDGPUISD::ATOMIC_LOAD_FMIN: 11839 case AMDGPUISD::ATOMIC_LOAD_FMAX: 11840 case AMDGPUISD::BUFFER_ATOMIC_SWAP: 11841 case AMDGPUISD::BUFFER_ATOMIC_ADD: 11842 case AMDGPUISD::BUFFER_ATOMIC_SUB: 11843 case AMDGPUISD::BUFFER_ATOMIC_SMIN: 11844 case AMDGPUISD::BUFFER_ATOMIC_UMIN: 11845 case AMDGPUISD::BUFFER_ATOMIC_SMAX: 11846 case AMDGPUISD::BUFFER_ATOMIC_UMAX: 11847 case AMDGPUISD::BUFFER_ATOMIC_AND: 11848 case AMDGPUISD::BUFFER_ATOMIC_OR: 11849 case AMDGPUISD::BUFFER_ATOMIC_XOR: 11850 case AMDGPUISD::BUFFER_ATOMIC_INC: 11851 case AMDGPUISD::BUFFER_ATOMIC_DEC: 11852 case AMDGPUISD::BUFFER_ATOMIC_CMPSWAP: 11853 case AMDGPUISD::BUFFER_ATOMIC_CSUB: 11854 case AMDGPUISD::BUFFER_ATOMIC_FADD: 11855 case AMDGPUISD::BUFFER_ATOMIC_FMIN: 11856 case AMDGPUISD::BUFFER_ATOMIC_FMAX: 11857 // Target-specific read-modify-write atomics are sources of divergence. 11858 return true; 11859 default: 11860 if (auto *A = dyn_cast<AtomicSDNode>(N)) { 11861 // Generic read-modify-write atomics are sources of divergence. 11862 return A->readMem() && A->writeMem(); 11863 } 11864 return false; 11865 } 11866 } 11867 11868 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG, 11869 EVT VT) const { 11870 switch (VT.getScalarType().getSimpleVT().SimpleTy) { 11871 case MVT::f32: 11872 return hasFP32Denormals(DAG.getMachineFunction()); 11873 case MVT::f64: 11874 case MVT::f16: 11875 return hasFP64FP16Denormals(DAG.getMachineFunction()); 11876 default: 11877 return false; 11878 } 11879 } 11880 11881 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op, 11882 const SelectionDAG &DAG, 11883 bool SNaN, 11884 unsigned Depth) const { 11885 if (Op.getOpcode() == AMDGPUISD::CLAMP) { 11886 const MachineFunction &MF = DAG.getMachineFunction(); 11887 const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>(); 11888 11889 if (Info->getMode().DX10Clamp) 11890 return true; // Clamped to 0. 11891 return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1); 11892 } 11893 11894 return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG, 11895 SNaN, Depth); 11896 } 11897 11898 // Global FP atomic instructions have a hardcoded FP mode and do not support 11899 // FP32 denormals, and only support v2f16 denormals. 11900 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) { 11901 const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics(); 11902 auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt); 11903 if (&Flt == &APFloat::IEEEsingle()) 11904 return DenormMode == DenormalMode::getPreserveSign(); 11905 return DenormMode == DenormalMode::getIEEE(); 11906 } 11907 11908 TargetLowering::AtomicExpansionKind 11909 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const { 11910 switch (RMW->getOperation()) { 11911 case AtomicRMWInst::FAdd: { 11912 Type *Ty = RMW->getType(); 11913 11914 // We don't have a way to support 16-bit atomics now, so just leave them 11915 // as-is. 11916 if (Ty->isHalfTy()) 11917 return AtomicExpansionKind::None; 11918 11919 if (!Ty->isFloatTy() && (!Subtarget->hasGFX90AInsts() || !Ty->isDoubleTy())) 11920 return AtomicExpansionKind::CmpXChg; 11921 11922 // TODO: Do have these for flat. Older targets also had them for buffers. 11923 unsigned AS = RMW->getPointerAddressSpace(); 11924 11925 if ((AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) && 11926 Subtarget->hasAtomicFaddInsts()) { 11927 if (!fpModeMatchesGlobalFPAtomicMode(RMW) || 11928 RMW->getFunction()->getFnAttribute("amdgpu-unsafe-fp-atomics") 11929 .getValueAsString() != "true") 11930 return AtomicExpansionKind::CmpXChg; 11931 11932 if (Subtarget->hasGFX90AInsts()) { 11933 auto SSID = RMW->getSyncScopeID(); 11934 if (SSID == SyncScope::System || 11935 SSID == RMW->getContext().getOrInsertSyncScopeID("one-as")) 11936 return AtomicExpansionKind::CmpXChg; 11937 11938 return (Ty->isFloatTy() && AS == AMDGPUAS::FLAT_ADDRESS) ? 11939 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11940 } 11941 11942 if (!Subtarget->hasGFX90AInsts() && AS != AMDGPUAS::GLOBAL_ADDRESS) 11943 return AtomicExpansionKind::CmpXChg; 11944 11945 return RMW->use_empty() ? AtomicExpansionKind::None : 11946 AtomicExpansionKind::CmpXChg; 11947 } 11948 11949 // DS FP atomics do repect the denormal mode, but the rounding mode is fixed 11950 // to round-to-nearest-even. 11951 // The only exception is DS_ADD_F64 which never flushes regardless of mode. 11952 if (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) { 11953 return (Ty->isDoubleTy() && !fpModeMatchesGlobalFPAtomicMode(RMW)) ? 11954 AtomicExpansionKind::CmpXChg : AtomicExpansionKind::None; 11955 } 11956 11957 return AtomicExpansionKind::CmpXChg; 11958 } 11959 default: 11960 break; 11961 } 11962 11963 return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW); 11964 } 11965 11966 const TargetRegisterClass * 11967 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const { 11968 const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false); 11969 const SIRegisterInfo *TRI = Subtarget->getRegisterInfo(); 11970 if (RC == &AMDGPU::VReg_1RegClass && !isDivergent) 11971 return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass 11972 : &AMDGPU::SReg_32RegClass; 11973 if (!TRI->isSGPRClass(RC) && !isDivergent) 11974 return TRI->getEquivalentSGPRClass(RC); 11975 else if (TRI->isSGPRClass(RC) && isDivergent) 11976 return TRI->getEquivalentVGPRClass(RC); 11977 11978 return RC; 11979 } 11980 11981 // FIXME: This is a workaround for DivergenceAnalysis not understanding always 11982 // uniform values (as produced by the mask results of control flow intrinsics) 11983 // used outside of divergent blocks. The phi users need to also be treated as 11984 // always uniform. 11985 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited, 11986 unsigned WaveSize) { 11987 // FIXME: We asssume we never cast the mask results of a control flow 11988 // intrinsic. 11989 // Early exit if the type won't be consistent as a compile time hack. 11990 IntegerType *IT = dyn_cast<IntegerType>(V->getType()); 11991 if (!IT || IT->getBitWidth() != WaveSize) 11992 return false; 11993 11994 if (!isa<Instruction>(V)) 11995 return false; 11996 if (!Visited.insert(V).second) 11997 return false; 11998 bool Result = false; 11999 for (auto U : V->users()) { 12000 if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) { 12001 if (V == U->getOperand(1)) { 12002 switch (Intrinsic->getIntrinsicID()) { 12003 default: 12004 Result = false; 12005 break; 12006 case Intrinsic::amdgcn_if_break: 12007 case Intrinsic::amdgcn_if: 12008 case Intrinsic::amdgcn_else: 12009 Result = true; 12010 break; 12011 } 12012 } 12013 if (V == U->getOperand(0)) { 12014 switch (Intrinsic->getIntrinsicID()) { 12015 default: 12016 Result = false; 12017 break; 12018 case Intrinsic::amdgcn_end_cf: 12019 case Intrinsic::amdgcn_loop: 12020 Result = true; 12021 break; 12022 } 12023 } 12024 } else { 12025 Result = hasCFUser(U, Visited, WaveSize); 12026 } 12027 if (Result) 12028 break; 12029 } 12030 return Result; 12031 } 12032 12033 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF, 12034 const Value *V) const { 12035 if (const CallInst *CI = dyn_cast<CallInst>(V)) { 12036 if (CI->isInlineAsm()) { 12037 // FIXME: This cannot give a correct answer. This should only trigger in 12038 // the case where inline asm returns mixed SGPR and VGPR results, used 12039 // outside the defining block. We don't have a specific result to 12040 // consider, so this assumes if any value is SGPR, the overall register 12041 // also needs to be SGPR. 12042 const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo(); 12043 TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints( 12044 MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI); 12045 for (auto &TC : TargetConstraints) { 12046 if (TC.Type == InlineAsm::isOutput) { 12047 ComputeConstraintToUse(TC, SDValue()); 12048 unsigned AssignedReg; 12049 const TargetRegisterClass *RC; 12050 std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint( 12051 SIRI, TC.ConstraintCode, TC.ConstraintVT); 12052 if (RC) { 12053 MachineRegisterInfo &MRI = MF.getRegInfo(); 12054 if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg)) 12055 return true; 12056 else if (SIRI->isSGPRClass(RC)) 12057 return true; 12058 } 12059 } 12060 } 12061 } 12062 } 12063 SmallPtrSet<const Value *, 16> Visited; 12064 return hasCFUser(V, Visited, Subtarget->getWavefrontSize()); 12065 } 12066 12067 std::pair<int, MVT> 12068 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL, 12069 Type *Ty) const { 12070 auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty); 12071 auto Size = DL.getTypeSizeInBits(Ty); 12072 // Maximum load or store can handle 8 dwords for scalar and 4 for 12073 // vector ALU. Let's assume anything above 8 dwords is expensive 12074 // even if legal. 12075 if (Size <= 256) 12076 return Cost; 12077 12078 Cost.first = (Size + 255) / 256; 12079 return Cost; 12080 } 12081